Jump to content

r3wt

Members
  • Posts

    43
  • Joined

  • Last visited

  • Days Won

    2

r3wt last won the day on April 26 2017

r3wt had the most liked content!

r3wt's Achievements

Member

Member (2/5)

17

Reputation

  1. remove the space in this line: before $curlresult2 = curl_exec ($curl); after $curlresult2 = curl_exec($curl);
  2. I was able to refactor the code and get it working $('.showBox').click(function() { $('.pop-box').hide(); var toshow = $('#box'+$(this).attr('target')); var simple = 'box'+$(this).attr('target'); $(toshow).show(500); setTimeout(function() { if (simple == 'box3') { getTweets( function(){ resizeTweetBox(); }); } },500); if (simple == 'box5') { scrollChat(); } });
  3. Hi, i've recently been learning javascript, and i've found that sometimes code works when it shouldn't, even though it throws an error. The Problem First, i need to explain that i am using two separate onclick events here. The first acts on the class of the toggle button, hiding the other toggleable divs then loading the unique one by id. the second onclick event fires specifically on the id to load the twitter feed. the problem is that the twitter feed finishes loading before the show() animation completes on the div, making the feed render at about half the size of the div, when its suppose to be 100% minus padding. We all know that loading a twitter feed can add unnecessary lag to a page, so i created a way to load it dynamically when the feed is slidetoggled onto the screen, like so: The Solution: function getTweets() { !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https'; if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); } The side effect Now that i've loaded the twitter feed in this method, due to animations(a timer set on the show() method that makes the box appear to "grow", the twitter feed renders at half the size of the div, because the code is called for the twitter feed before the animation has completed. The Nitty Gritty Hack to make it work At first i thought i had solved the problem with this, but really i'm just preloading the twitter box, which means all of my work was for naught: getTweets().finish( function() { resizeTweetbox();//this throws an error but still works }); here's the resizeTweetbox() function for reference: function resizeTweetBox() { $("#twitter-widget-0").css("width","100%"); } I'm wondering if there is a better way i can do this. its one of those weird situations where i can't just add the function to the onclick function of the class, because its unique to the twitter feed's div. if you need to take a look my site is located at https://openex.info Thanks for your time. Garrett
  4. function getWheelsByCar($car_id) { $mysqli = new mysqli("localhost","username","password","databasename"); $wheel_id = null; $stmt = $mysqli->prepare("SELECT wheel_id FROM car WHERE car_model= ?");//initiate prepared statement $stmt->bind_param('i',$car_id);//when you bind parameters to a query, i stands for integer, s stands for string, d stands for double //the following line asks whether $stmt->execute() is true. i assume its an integer here, but it may be a string. if($stmt->execute()) { //if it did $stmt->bind_result($wheel_id);//bind our result object to a variable while($stmt->fetch()) { $wheel_id = $wheel_id;//while fetching the statement, we force writing the result to the variable } if(!empty($wheel_id)) { //if the wheel id exists, we close the first statement and run the second query. $stmt->close(); $stmt = $mysqli->prepare("SELECT wheel_name,wheel_image,wheel_category,wheel_info FROM wheel WHERE wheel_id= ?"); $stmt->bind_param('i',$wheel_id); if($stmt->execute()) { $_array = array();//setup our result array $stmt->bind_result($wheel_name,$wheel_image,$wheel_category,$wheel_info); while($stmt->fetch()) { $_array[] = array( 'wheel_name'=>$wheel_name, 'wheel_image'=>$wheel_image, 'wheel_category'=>$wheel_category, 'wheel_info'=>$wheel_info );//write an array with each result rows information } $stmt->close(); foreach($_array as $key => $val) { //output the html/information to the view echo ' <div class="wheel_stuff"> <h1>'.htmlspecialchars($val['wheel_name']).'</h1> <div class="plft"><img src="images/'.htmlspecialchars(urlencode($val['wheel_image']).'" /></div> <div class="prt"> <p><strong>Category : </strong>'.htmlspecialchars($val['wheel_category']).'</p> <p><strong>Info : </strong>'.htmlspecialchars($val['wheel_info']).'</p> <div style="clear:both"></div> </div> <div style="clear:both"></div> </div> '; } } } } } //to call the function getWheelsByCar($car_id);
  5. well, i converted it all to the stream functions as you suggested, still no magic. finally get a response in the debug console here is the new code including all functions. it was hard to find replacements for all the socket functions, and i'm sure that i made a billion errors: // //php websocket server with tls // require_once __DIR__ . '/../models/config.php'; $host = 'openex.info'; $port = '8888'; $admin = array("admin", "superadmin"); $null = NULL; $socket_key = fetchkey('0x33'); $context = stream_context_create(); stream_context_set_option($context, 'ssl', 'local_cert', $ssl_cert); stream_context_set_option($context, 'ssl', 'passphrase', $ssl_pass); stream_context_set_option($context, 'ssl', 'allow_self_signed', false); stream_context_set_option($context, 'ssl', 'verify_peer', true); $socket = stream_socket_server('ssl://'.$host.':'.$port, $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context); $clients = array($socket); while(true) { $changed = $clients; stream_select($changed, $null, $null, 0, 10); if (in_array($socket, $changed)) { $socket_new = stream_socket_accept($socket); $clients[] = $socket_new; $header = fread($socket_new, 1024); perform_handshaking2($header, $socket_new, $host, $port); $peer = stream_socket_get_name($socket_new, true); $found_socket = array_search($socket, $changed); sendOldMessages2($peer); unset($changed[$found_socket]); } foreach ($changed as $changed_socket) { while(fread($changed_socket, $buf, 1024, 0) >= 1) { $received_text = unmask($buf); $msg = json_decode($received_text); $msg_type = @$msg->type; $write_key = @$msg->writekey; if($msg_type == 'chatmsg' && $write_key == $socket_key) { $user_name = @$msg->name; $user_message = @$msg->message; $user_color = @$msg->color; if(in_array($user_name,$admin)) { if (strpos($user_message,'./ban') !== false) { newBan2($user_message); break 2; } if (strpos($user_message,'./unban') !== false) { unBan2($user_message); break 2; } } if(usernameExists($user_name)) { if($user_name == $null || $user_message == $null) { break 2; }else{ if(!isBant2($user_name)) { newMessage2($user_name,$user_message,$user_color); break 2; }else{ cooldown2($user_name); } } } } } if($msg_type == 'alert' && $write_key == $socket_key) { $recipient = @$msg->user; $alert = @$msg->alert; $response_text = mask(json_encode(array('type'=>'alert', 'user'=>security($recipient), 'alert'=>security($alert)))); send_message2($response_text); } if($msg_type == 'mktdata' && $write_key == $socket_key) { $pair = @$msg->pair; $price = @$msg->price; $response_text = mask(json_encode(array('type'=>'mktdata', 'pair'=>$pair, 'price'=>$price))); send_message2($response_text); } $buf = @fread($changed_socket, 1024, PHP_NORMAL_READ); if ($buf === false) { $found_socket = array_search($changed_socket, $clients); @stream_socket_get_name($changed_socket, true); unset($clients[$found_socket]); } } } fclose($socket); function perform_handshaking2($receved_header,$client_conn, $host, $port) { $headers = array(); $lines = preg_split("/\r\n/", $receved_header); foreach($lines as $line) { $line = chop($line); if(preg_match('/\A(\S+): (.*)\z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } $secKey = $headers['Sec-WebSocket-Key']; $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); //hand shaking header $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "WebSocket-Origin: $host\r\n" . "WebSocket-Location: wss://$host:$port/socket/server2.php\r\n". "Sec-WebSocket-Accept:$secAccept\r\n\r\n"; fwrite($client_conn,$upgrade,strlen($upgrade)); } function send_message2($msg) { global $clients; foreach($clients as $changed_socket) { @fwrite($changed_socket,$msg); } return true; } function send_message_single_client2($msg,$client) { @fwrite($client,$msg); return true; } function newBan2($user_message) { global $mysqli; $command = explode(" ", $user_message); if(count($command) >= 2) { $toban = $command[1]; if(!empty($toban)) { if(usernameExists($toban)) { $begin = time(); if(isset($command[2])) { switch ($command[2]) { case '10m' : $length = 10 * 60; $duration = '10 minutes'; break; case '30m' : $length = 30 * 60; $duration = '30 minutes'; break; case '1h' : $length = 60 * 60; $duration = '1 hour'; break; case '1d' : $length = 24 * 60 * 60; $duration = '1 day'; break; case '1w' : $length = 7 * 24 * 60 * 60; $duration = '1 week'; break; default : return; } }else{ $length = 5 * 60; $duration = '5 minutes'; } $end = $begin + $length; $stmt = $mysqli->prepare("INSERT INTO uc_chat_bans (username,starttime,endtime,duration) VALUES (?,?,?,?)"); $stmt->bind_param('siis',$toban,$begin,$end,$duration); $stmt->execute(); $stmt->close(); $ban_nme = 'System'; $ban_msg = '** '.security($toban).' has been banned from chat for '.security($duration).'**'; $ban_col = '000000'; $ban_now = time(); $stmt = $mysqli->prepare("INSERT INTO uc_chat_msg (username,message,color,timestamp) VALUES (?,?,?,?);"); $stmt->bind_param('sssi',$ban_nme,$ban_msg,$ban_col,$ban_now); $stmt->execute(); $stmt->close(); $response_text = mask(json_encode(array('type'=>'userban', 'toban'=>$toban, 'bantime'=>$duration))); send_message2($response_text); //send data } } } } function unBan2($user_message) { global $mysqli; $command = explode(" ", $user_message); $tounban = $command[1]; $stmt = $mysqli->prepare("DELETE FROM uc_chat_bans WHERE username = ?"); $stmt->bind_param('s',$tounban); $stmt->execute(); $stmt->close(); } function isBant2($name) { $user111 = $user000 = null; global $mysqli; $time = time(); $stmt = $mysqli->prepare("SELECT username FROM uc_chat_bans WHERE endtime > ? AND username = ?"); $stmt->bind_param('is',$time,$name); $stmt->execute(); $stmt->bind_result($user000); while($stmt->fetch()) { $user111 = $user000; } if($user111 == $name) { $stmt->close(); return true; }else{ $stmt->close(); return false; } } function sendOldMessages2($socket_new) { global $mysqli; $query = $mysqli->query("SELECT * FROM (SELECT * FROM uc_chat_msg WHERE `hidden`='0' ORDER BY `id` DESC LIMIT 100) as last100 ORDER BY id"); while($row = $query->fetch_assoc()) { $response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>security($row["username"]), 'message'=>security($row["message"]), 'color'=>security($row["color"]),'timestamp'=>security($row["timestamp"])))); send_message_single_client2($response_text, $socket_new);//send old messages to the new client } $query->close(); } function newMessage2($user_name,$user_message,$user_color) { global $mysqli; $now = time(); $stmt = $mysqli->prepare("INSERT INTO uc_chat_msg (username,message,color,timestamp) VALUES (?,?,?,?);"); $stmt->bind_param('sssi',$user_name,$user_message,$user_color,$now); $stmt->execute(); $stmt->close(); $response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>security($user_name), 'message'=>security($user_message), 'color'=>security($user_color), 'timestamp'=>$now))); send_message($response_text); } function cooldown2($user_name) { $response_text = mask(json_encode(array('type'=>'cooldown', 'user'=>security($user_name)))); send_message($response_text); //send data }
  6. I am in development stages of a website. this website is primarily in php. today, i decided i reached a point in development where it was time to move everything to TLS, and not suprisingly the websocket connection is being refused and i'm not sure why. The only error i get is Here is the handshaking function: function perform_handshaking($receved_header,$client_conn, $host, $port) { $headers = array(); $lines = preg_split("/\r\n/", $receved_header); foreach($lines as $line) { $line = chop($line); if(preg_match('/\A(\S+): (.*)\z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } $secKey = $headers['Sec-WebSocket-Key']; $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); //hand shaking header $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "WebSocket-Origin: $host\r\n" . "WebSocket-Location: wss://$host:$port/socket/server.php\r\n". "Sec-WebSocket-Accept:$secAccept\r\n\r\n"; socket_write($client_conn,$upgrade,strlen($upgrade)); } Here is the server // //socket server // require_once __DIR__ . '/../models/config.php'; $host = 'www.example'; $port = 8888; $admin = array("admin", "superadmin"); $null = NULL; $socket_key = fetchkey('0x33'); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($socket, 0, $port); socket_listen($socket); $clients = array($socket); while (true) { $changed = $clients; socket_select($changed, $null, $null, 0, 10); if (in_array($socket, $changed)) { $socket_new = socket_accept($socket); $clients[] = $socket_new; $header = socket_read($socket_new, 1024); perform_handshaking($header, $socket_new, $host, $port); socket_getpeername($socket_new, $ip); $found_socket = array_search($socket, $changed); sendOldMessages($socket_new); unset($changed[$found_socket]); } foreach ($changed as $changed_socket) { while(socket_recv($changed_socket, $buf, 1024, 0) >= 1) { $received_text = unmask($buf); $msg = json_decode($received_text); $msg_type = @$msg->type; $write_key = @$msg->writekey; if($msg_type == 'chatmsg' && $write_key == $socket_key) { $user_name = @$msg->name; $user_message = @$msg->message; $user_color = @$msg->color; if(in_array($user_name,$admin)) { if (strpos($user_message,'./ban') !== false) { newBan($user_message); break 2; } if (strpos($user_message,'./unban') !== false) { unBan($user_message); break 2; } } if(usernameExists($user_name)) { if($user_name == $null || $user_message == $null) { break 2; }else{ if(!isBant($user_name)) { newMessage($user_name,$user_message,$user_color); break 2; }else{ cooldown($user_name); } } } } } if($msg_type == 'alert' && $write_key == $socket_key) { $recipient = @$msg->user; $alert = @$msg->alert; $response_text = mask(json_encode(array('type'=>'alert', 'user'=>security($recipient), 'alert'=>security($alert)))); send_message($response_text); } if($msg_type == 'mktdata' && $write_key == $socket_key) { $pair = @$msg->pair; $price = @$msg->price; $response_text = mask(json_encode(array('type'=>'mktdata', 'pair'=>$pair, 'price'=>$price))); send_message($response_text); } $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ); if ($buf === false) { $found_socket = array_search($changed_socket, $clients); @socket_getpeername($changed_socket, $ip); unset($clients[$found_socket]); } } } socket_close($sock); From what i can gather, i somehow need to give this server script access to my ssl certificate so it can decode the post request(this is my basic understanding of how tls works, could be wrong, correct me if i am please.) . Now, i am at a total loss as to what i should try next, and there is quiet a shortage of information on this subject related to php atleast. Some other information to note: chat messages are posted via ajax to a file, sendmsg.php that also must establish a connection to this socket server and broadcast the posted message. likewise, a cronjob runs to get new alert messages and market price statistics and connects and broadcasts the information to the server in basically the same way as sendmsg.php does. Any questions are welcome, and any advice is appreciated. i may drop some btc to anyone who is able to help me fix this and move on to the next challenge thanks, Garrett
  7. oh, so array rand only selects the key. that's counter intuitive imo. thanks requinix
  8. the point was there is no reason to set an extra session for an admin, let alone rely on this for authentication.
  9. There's an error in your sql query, so $query = false because there was an error. also i think you should use post instead of get. also you are using insecure method of communication with the database. code is wide open to sql injection. my suggestion would be to read up on mysqli or pdo and learn to use them. they are a bit more difficult to get comfortable with but alot better. I myself prefer mysqli but most people use PDO
  10. Looks like i posted this in the wrong forum. My apologies to the mods, my mistake.
  11. I'm not sure why but i'm having problem with array rand. I made the following script to test out a real time price update over websockets, to see how it looks visually when the prices are updating and debug/fine tune the client side of the price updates. so i decided i'd use array rand to select a value at random and insert it into the two test markets last_price field. the problem is, for some reason it is inserting the numeric key instead of the value. this is the first time i've used array rand, and i was wondering if someone could explain to me what i did wrong here. thanks require_once __DIR__ . '/models/config.php'; for($i = 0; $i < 20; $i++) { $prices = array('0.00321252','0.00223252','0.00121252','0.00301272','0.00091252','0.00001252','0.00005252','0.00007252'); $price1 = array_rand($prices); $price2 = array_rand($prices); $coin1 = 'TST-BTC'; $coin2 = 'TST-LTC'; global $mysqli; $stmt = $mysqli->prepare("UPDATE uc_market_data SET last_price = ? WHERE pair = ?"); $stmt->bind_param('ss',$price1,$coin1); $stmt->execute(); $stmt->close(); $stmt = $mysqli->prepare("UPDATE uc_market_data SET last_price = ? WHERE pair = ?"); $stmt->bind_param('ss',$price2,$coin2); $stmt->execute(); $stmt->close(); sleep(1); }
  12. I'm not sure if i'm allowed to post a link to the devshed forums, but here's a pretty authorative post on the subject from Jacques. This should give you a "crash course" look at the subject of sessions in php: http://forums.devshed.com/php-faqs-stickies-167/php-sessions-secure-953373.html
  13. I agree with Jacques. get the info from the db, don't rely on the session for authentication.
  14. r3wt

    HipHop VM

    I've heard alot of people say they wouldnt use it in production, but i don't see why personally. once you get redis setup to handle sessions(requires a hack because session_save_handler is broken) that's half the battle. there are some little bizarre quirks to hhvm, and some corners have been cut, but i feel very excited about the future of php. the competition should make both engines much better.
  15. r3wt

    HipHop VM

    Let's have a show of hands, who is using HHVM as a replacement to PHP? IMO, the zend engine is dead, HHVM is the new hotness. Oh, it blows Node out of the water in benchmarks too.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.