PHP - Redirect Connection With Sockets???
Hello.
This is a follow up on a previous thread. I'm trying to redirect a socket connection via browser to another script or page but, I'm having a lot of problems trying to do it. I don't know if it can be done. Please guide me to where I can get some input on it. I've google about it and nothing exactly... The socket file looks like this: $host = "172.16.0.3"; $port = "200"; // don't timeout! set_time_limit(0); // create socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP ) or die("Could not create socket\n"); // bind socket to port $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); // start listening for connections $result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); while( true ){ // accept incoming connections // spawn another socket to handle communication $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // read client input $input = socket_read($spawn, 1024) or die("Could not read input\n"); // clean up input string $input = trim($input); // reverse client input and send back $output = strrev($input) . "\n"; header('Location: http://www.cnn.com/'); $output = "hello there.. you're connected"; socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n"); } // close sockets socket_close($spawn); socket_close($socket); ?> I put in the browser's addr bar: http://172.16.0.3:200 and get "hello there.. you're connected"... Can it be done?? Any suggestions? Thanks in advanced for your help. Similar TutorialsHi, I'm building a flash environment for a small scale MMO game, and I need to employ the use of sockets so that users can interact with each other in real time (chat, battle, exploring, etc). I've done quite a bit of Googling, and haven't turned up much useful information. Maybe I'm looking for the wrong thing? Anyway, I have my own server, running Fedora 9 and Apache 2.0. I want to create a PHP "socket server" that runs almost as a process on my server, so that users can connect to it and pass data between each other instantly. I've looked through PHP's manual on the socket functions, and I'm fairly confident that I will be able to work with them just fine as soon as I actually have the socket server working.. So my question is, how exactly would I go about starting this process? I'm messing around on the command line right now and can't seem to get it to work? Thanks, nethnet Ahoy Sailor! So I've just started making a Server Client based application in PHP, First time I've dabble in PHP for about a year so forgive me if I'm slightly rusty. But I get the "Could not accept incoming connection" error when my client try's to connect to my server. How cometh? <?php $host = "127.0.0.1"; $port = 405; set_time_limit(0); // create socket $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); $result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); // Networking area, Creating, Binding & finally listing $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); $out = "0;text\n"; socket_write($spawn, $out, strlen ($out)) or die("Could not write output\n"); ?> ^ Client<?php $addr="127.0.0.1"; $port=405; $timeout=0; $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); $res = socket_connect($socket, $addr, $port); $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); $dat= socket_read($spawn, 1024) or die("Could not read input\n"); echo $dat; ?> Server^ _____________________ Anyone know? See Ya! i have been working to works. but any time i use the method socket_read(); or socket_write(); my apache server gives me an error undefined method pls want could be responsible for this error. i am quite sure of the syntax I recently came across http://forums.phpfre...g-with-sockets/. Sockets? Never heard of them...
I looked at the PHP documentation http://php.net/manua...tro.sockets.php, and it tells how to implement them, but not really what their purpose is.
I then search a bit, and learned about their history http://en.wikipedia....erkeley_sockets, but still not really why they are used.
Okay, sockets are used to connect an application to a given port and IP, and PHP can be set up as either a socket host or socket client? Is this something like a SOAP server/client, but SOAP specifies a given port and protocol? Do sockets not necessarily specify a protocol?
Still a little fuzzy. Can anyone provide examples on where they might be used? BSD Sockets generally relies upon client/server architecture. For TCP communications, one host listens for incoming connection requests. When a request arrives, the server host will accept it, at which point data can be transferred between the hosts. UDP is also allowed to establish a connection, though it is not required. Data can simply be sent to or received from a host. The Sockets API makes use of two mechanisms to deliver data to the application level: ports and sockets. Ports and sockets are one of the most misunderstood concepts in sockets programming. All TCP/IP stacks have 65,536 ports for both TCP and UDP. There is a full compliment of ports for UDP (numbered 0-65535) and another full compliment, with the same numbering scheme, for TCP. The two sets do not overlap. Thus, communication over both TCP and UDP can take place on port 15 (for example) at the same time. A port is not a physical interface - it is a concept that simplifies the concept of Internet communications for humans. Upon receiving a packet, the protocol stack directs it to the specific port. If there is no application listening on that port, the packet is discarded and an error may be returned to the sender. However, applications can create sockets, which allow them to attach to a port. Once an application has created a socket and bound it to a port, data destined to that port will be delivered to the application. This is why the term socket is used - it is the connection mechanism between the outside world (the ports) and the application. A common misunderstanding is that sockets-based systems can only communicate with other sockets-based systems. This is not true. TCP/IP or UDP/IP communications are handled at the port level - the underlying protocols do not care what mechanisms exist above the port. Any Internet host can communicate with any other, be it Berkeley Sockets, WinSock, or anything else. "Sockets" is just an API that allows the programmer to access Internet functionality - it does not modify the manner in which communications occur. Reference: http://wiki.treck.co..._to_BSD_Sockets I am trying to post a feed file to ebay from our site via a PHP script, but I am new to this stuff. I found some instructions he http://pics.ebaystatic.com/aw/pics/pdf/us/file_exchange/File_Exchange_Advanced_Instructions.pdf The most important part of that PDF is: Quote Sample HTTP Post Request POST /path/to/upload/script HTTP/1.0 Connection: Keep-Alive User-Agent: My Client App v1.0 Host: https://bulksell.ebay.com/ws/eBayISAPI.dll?FileExchangeUpload Content-type: multipart/form-data; boundary=THIS_STRING_SEPARATES Content-Length: 256 --THIS_STRING_SEPARATES Content-Disposition: form-data; name="token" 12345678987654321 --THIS_STRING_SEPARATES Content-Disposition: form-data; name="file"; filename="listings.csv" Content-Type: text/csv ... contents of listings.csv ... --THIS_STRING_SEPARATES I tried to implement it using this code: <?php // GET THE FEED FILE $options = array( CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_USERAGENT => "website", CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, CURLOPT_SSL_VERIFYPEER => false, ); $ch = curl_init('https://www.mysite.com/pull_feed.php'); curl_setopt_array( $ch, $options ); $contents = curl_exec( $ch ); curl_close( $ch ); //----------------------------------------------------// //OPEN THE CONNECTION $conn = fsockopen('https://bulksell.ebay.com/ws/eBayISAPI.dll?FileExchangeProgrammaticDownload', 80); // START THE REQUEST fputs($conn, "POST ".$_SERVER['PATH_INFO']." HTTP/1.0"); fputs($conn, "Connection: Keep-Alive"); fputs($conn, "User-Agent: My Client App v1.0"); fputs($conn, "Host:"); fputs($conn, "https://bulksell.ebay.com/ws/eBayISAPI.dll?FileExchangeUpload"); fputs($conn, "Content-type: multipart/form-data;"); fputs($conn, "boundary=THIS_STRING_SEPARATES"); fputs($conn, "Content-Length: ".strlen($contents)); fputs($conn, "--THIS_STRING_SEPARATES"); fputs($conn, "Content-Disposition: form-data; name=\"token\""); fputs($conn, "MY_KEY_IS_HERE_000000000000000000000000"); fputs($conn, "--THIS_STRING_SEPARATES"); fputs($conn, "Content-Disposition: form-data; name=\"file\";"); fputs($conn, "filename=\"listings.csv\""); fputs($conn, "Content-Type: text/csv"); // SEND THE FILE fputs($conn, $contents); // END THE REQUEST fputs($conn, "--THIS_STRING_SEPARATES"); // GET THE RESULT while(!feof($conn)) { echo fgets($conn, 128); } // CLOSE CONNECTION fclose($conn); ?> UPDATE: I accidently had error reporting off. Whoops. It is giving me this error: Quote Warning: fsockopen() [function.fsockopen]: unable to connect to https://bulksell.ebay.com/ws/eBayISAPI.dll?FileExchangeProgrammaticDownload:80 (Unable to find the socket transport "https" - did you forget to enable it when you configured PHP?) in C:\home\imafs\public_html\funad\ebay\send_feed.php on line 27 Followed by more errors resulting from that one. I have server #1 that host a php page with a form. I have server #2 that has a VPN connection to #1. I want the user to fill out the form on server #1 and on submit the data is sent to server #2 where it is processed and then an email is sent from server #2 with a confirmation. I do not want the user to be sent to the server#2 though. They can be sent to a thank you page. Can anyone enlighten me with the best function to use in this case or if it is even possible? THANKS Everyone! I have a PHP application that runs as a daemon. the daemon uses fsockopen to connect to an external server. When the daemon is terminated, for instance during a reboot, it looks like the connections to the remote server are persistent. The admin of the remote server tells me that he sees some of these connections for days after a daemon instance on my server has dies. My first thought was to use a linux/unix signal to tell the daemon to close the connections before it dies, but I haven't found a way to do that yet. The daemon seems to respond only to a sig-kill. In a perfect world I'd discover a way for the daemon to always run a function before it shuts down - within the function I'd close the open connections. I'd be very appreciative if someone could point me at either a way to cause a function to execute upon receipt of a sigkill or else a way to cause the daemon to recognise and act on some other less aggressive signal. Thanks I'm having issues working with sockets in PHP, I'm hoping someone can help.
I'm making an application in which I need to open my own socket connections. There are two specific features that I need:
I need to set a timeout for the connection attempt.
I need these connections to come from a custom IP address, and by that I mean that my server has more than one IP, and I need the socket connection to use an IP that is not the server's default internet connection port.
There are (as far as I know) two ways to open a socket connection. Both techniques meet a requirement and miss a requirement.
Option 1: I can use the function fsockopen( ) to open the connection. This function works great and let's me set a timeout for the connection itself. It's solid and reliable. However it has, as far as I can tell, no way to set the connection to come from a custom IP. All connections using this function come from the server's default IP address.
Option 2: The socket_create( ) / socket_connect( ) family of functions. These functions have a lot more options, they let you do a lot more. I can easily bind the socket to my server's secondary IP address so socket connections will come from it. HOWEVER as far as I can tell, these family of functions lack a connection timeout. You can set timeout for reads and timeouts for writes. But there doesn't seem to be a way to set a timeout for initiating the connection itself. Even setting the "default_socket_timeout" parameter doesn't have any effect on the connection time.
This type of question is a bit more technical than most PHP questions. But I'm hoping someone out there knows a way I can open sockets while meeting both of my two requirements. It's entirely possible that it is not possible, I know. But hopefully it can be done.
One thought I had was a way of using the second option, and wrapping the whole socket_connect( ) function inside of another function that sets a timeout, and would kill the socket_connect( ) function once the timeout was met. However, I don't know of any such system in PHP, this was only a concept theory.
How I open my sockets using fsockopen( ):
$sock = @fsockopen($ip,$port,$errno,$errstr,$timeout); Hi, im trying to learn about socket in PHP but unfortunatly not getting anywhere fast. The main issue is, the reason i want to learn about them is for use on a project where i will be connecting to a server, not actually being one. So although i am interested in the server part, its not essential. But to test my php socket code, i need something to connect to for debugging? So i have tried to create (from tutorials) a php server but not had any luck at all, can anyone advise me on where to start here? I basically want a way to send a command from a php file over TCP/IP, but for now just want it to bounce back or get a response, is there any test servers out there or do i have to create one? I have my own windows web server running here next to me for all my testing. Thanks Andy my current code: $host="127.0.0.1"; $port=7777; $timeout=5; $sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ; if (!is_resource($sk)) { exit("connection fail: ".$errnum." ".$errstr) ; } else { fputs($sk, "idkxd") ; $dati="" ; while (!feof($sk)) { $dati.= fgets($sk, 256); } } fclose($sk); echo($dati); The problem is that when I send data to the server, I never get a response. I do not believe that this is a server side problem as it works through a c# application and as well as when I turn the application off. This is what happens when I do not shut the server off: 1. I run the Server 2. I run the php script 3. Data is sent from PHP 4. Server Responds 5. PHP never gets the response A slightly different way that it does respond to php: 1. I run the Server 2. I run the php script 3. Data is sent from PHP 4. Server Responds 5. I turn off the server application 6. PHP receives data from the server... Please help, I am kind of new with php sockets. I'm trying to use sockets to see if I can connect to a chatroom. I got it started but not sure where to go from here. Code: [Select] <? $host = "79.99.135.253"; $port = 6667; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $data = "NICK OpenZelda"; $data .= chr(13); $data .= 'USER whoever "thegaminguniverse.com" "irc.thegaminguniverse.nl" :OZ Website'; $data .= chr(13); socket_connect($socket, $host, $port); socket_sendto($socket, $data, strlen($data), 0,$host,$port); socket_recv($socket, $buffer, 1024, 0); echo $buffer; ?> I managed to receive one message. However I know for a fact there were two messages sent back. So how do I set it up to keep receiving messages? I'm trying to put together a script that redirects visitors based on their IP, user agent and/or referral url. Basically I want the script to scan these three factors from the visitor, if any of them turn out to match my redirect-requirement it redirects the user. I know the code is horribly coded, I'm incredibly new to the php-scene and consider myself a complete noob. As you can see I want redirected visitors to go to google.com and un-redirected to msn.com(examples). Really thankful for all the help I can get! Right now nothing works, any suggestions? <?php function redirect($page) { Header( "HTTP/1.1 301 Moved Permanently" ); header('Location: ' . $page); exit; } $referrals=array('pitchingit.org','referral2'); $badAgents = array("useragent1", "useragent2"); $deny = array("78.105.191..*","100.101.103..*"); if (in_array($_SERVER['HTTP_REFERER'], $referrals, FALSE)) { header("Location: http://www.google.com"); } else { header("Location: http://www.msn.com"); } if(in_array($_SERVER['HTTP_USER_AGENT'],$badAgents)) { redirect("http://www.google.com/"); exit(); } $add=$_SERVER['REMOTE_ADDR']; foreach ($deny as $ip) { if (preg_match("^.$add.*^",$ip)) { redirect("http://www.google.com"); } } redirect("http://www.msn.com"); ?> How can one re-direct a visitor, without using a header re-direct? I'd like a page to show up, then after about 5 seconds I need the visitor sent to another page. How can I do this? Hi All, I have a landing page that I use, but often my sql database is too busy or gets overwhelmed and then the landing page just stalls and traffic is lost. Here it is: Code: [Select] <?php //ini_set("display_errors",1); if(!$src) $src = $q; define("__EXEC_", 1); include("config.php"); include("custom.php"); function lsp_visit_find($__val, &$__uid) { global $u; global $db; $l_campaign = array("campaign_id"=>"", "url"=>"", "cost"=>"0.00", "name"=>"-", "ad_keyword"=>"", "mapped_keyword"=>""); $l_visit = array(); $q = $_GET['q']; $src = $_GET['src']; // for STAGE #1 (visit definition): get cost, ad keyword, mapped keyword. $l_campaign['name'] = "info"; $l_campaign['mapped_keyword'] = "$q"; $l_campaign['ad_keyword'] = "$src"; $l_campaign['cost'] = ".02"; // get referer (campaign URL). if no campaign found, - create it! if (!empty($l_campaign['name'])) { $r = mysql_query("select campaign_id,name from campaign where name='$l_campaign[name]'"); if (!mysql_affected_rows($db)) { $r = mysql_query("insert into campaign(name,cost, creation_date,last_update_date) values('$l_campaign[name]',$l_campaign[cost], unix_timestamp(),unix_timestamp())"); $l_campaign['campaign_id'] = mysql_insert_id($db); } else { $w = mysql_fetch_assoc($r); $l_campaign = array_merge($l_campaign,$w); } } // check, whether we had visits from this IP for this keywords within 2 minutes. // if we have one, get its ID, otherwise - create new! $visit_id=""; if (!empty($l_campaign['ad_keyword']) && !empty($l_campaign['mapped_keyword']) ) { $ip = get_real_ip(); $r = mysql_query("select visit_id,uid,campaign_id,ad_keyword,mapped_keyword from visit where ip='$ip' and ad_keyword='$l_campaign[ad_keyword]' and mapped_keyword='$l_campaign[mapped_keyword]' and currtime>=from_unixtime(".(time()-120).") limit 1"); if (!mysql_affected_rows()) { $__uid = md5($ip.time().$l_campaign['campaign_id']); $x = mysql_query("insert into visit(ip,uid,cost,currtime,campaign_id,ad_keyword,mapped_keyword) values('$ip','$__uid',$l_campaign[cost],now(),$l_campaign[campaign_id],'$l_campaign[ad_keyword]','$l_campaign[mapped_keyword]')"); $visit_id = mysql_insert_id($db); } else { $l_visit = mysql_fetch_assoc($r); $visit_id = $l_visit['visit_id']; $__uid = $l_visit['uid']; } return $visit_id; } } $db = mysql_connect(__CFG_HOSTNAME, __CFG_USERNAME, __CFG_PASSWORD); mysql_select_db(__CFG_DATABASE, $db); $u = isset($_GET['u'])? $_GET['u'] : 2; $uid = ""; $visit_id = lsp_visit_find($_REQUEST['l'], $uid); if (!empty($visit_id)) { setcookie("x_uid", base64_encode($visit_id."QQ".$uid), time() + 3600); } global $q; mysql_close($db); $q = $_GET['q']; $src = $_GET['src']; header("Location: http://www.mydomain.com/search/?q=$q"); exit(); ?> My question is how do I code it so that if after 5 seconds or so, or the connection can't be made, it just terminates the connection and auto loads the header redirect at the bottom of the page? Thanks! Fatal error: Call to undefined function mysql_connect() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\connect\index.php on line 10 Hallo I am beginner and starting to learn php I got this message when I want to connect with server. Can I get some suggestion what to do? Thanks Hi Guys, need a little help and drawn a blank. The code that is not working is below $result = $conn->query("SELECT * FROM MK_migration_details WHERE mig_bid='".$_SESSION['bid']."'"); I can confirm theĀ $_SESSION['bid'] is working as echo's out on another part of the page. and the above $result works when i manually type the search criteria like below. $result = $conn->query("SELECT * FROM MK_migration_details WHERE mig_bid='300101'"); Basically no result turn up on the page. Any ideas or advise how I can diagnose? HI fellow programmers, Can i connect a textbox to a field in the MySql using the id of the text box? If yes, can u show me a small example. Thanks RAM Hi! I got the following problem... I have a SQL 2005 Server in a VPN. For security reasons,internet access to the database server is only possible for VPN members. Now i want to connect to the openvpn Server from my webserver in order to connect to the database for some webreports. How can i achieve this using php? thanks Is there a way to instantiate a PDO object using an already existing database connection? Or does PDO detect an already opened connection and use it? The existing connection is a persistant connection. |