PHP - Php Sockets Need Some Advise.
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 Similar TutorialsI 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 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 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 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, 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 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. 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! <?php class Action { protected $_request; protected $_response; protected $_model; protected $_view; public function __construct(Request $request, Response $response) { $this->set_request($request)->set_response($response)->set_view($request, $response)->set_model(); // if request requires partial then do this $partial = Partial::singleton(); $view = $this->get_view(); $view->set_partial($partial); $partial->set_view(clone $view); } protected function set_request(Request $request) { $this->_request = $request; return $this; } protected function set_response(Response $response) { $this->_response = $response; return $this; } protected function set_view(Request $request, Response $response) { $this->_view = new View($request, $response); return $this; } public function get_request() { return $this->_request; } public function get_response() { return $this->_response; } public function get_view() { return $this->_view; } public function dispatch($method, $parameters) { if ($this->get_request()->is_dispatched()) { if(method_exists($this, $method)) { call_user_func_array(array($this, $method), $parameters); } else { echo "unable to load method"; } } } public function __get($property) { $property = '_' . $property; if (property_exists($this, $property) && $property !== '$this->_request' && $property !== '$this->_responce') { return $this->$property; } return false; } public function set_model() { $class_name = get_class($this); $model_name = trim($class_name, "_Controller"); $model_name = strtolower($model_name); $property_name = '_' . $model_name; $model_name = Inflection::singularize($model_name); $model_name = ucfirst($model_name); $model_class = $model_name . '_Model'; $this->{$property_name} = new $model_class(); } } <?php class View { protected $_variables = array(); protected $_helpers = array(); public function __construct(Request $request, Response $response) { } public function __set($name, $value) { $this->_variables[$name] = $value; } public function __get($name) { return $this->_variables[$name]; } public function __call($name, $parameters) { $helper = $this->get_helper($name); if (!$helper) { $helper = call_user_func_array(array(new $name(), '__construct'), $parameters); $this->set_helper($name, $helper); } return $helper; } protected function set_helper($helper, $instance) { $this->_helpers[$helper] = $instance; } protected function get_helper($helper) { if (isset($this->_helpers[$helper])) { return $this->_helpers[$helper]; } return false; } public function set_partial(Partial $partial) { if ($partial instanceof Partial) { $this->set_helper('partial', $partial); } } public function render($file) { if (preg_match("/\.html$/i", $file)) { require_once PRIVATE_DIRECTORY . 'application' . DS . 'views' . DS . $file; } } } <?php class Partial { protected $_view; protected $_templates; protected static $_instance = null; public static function singleton() { if (self::$_instance == null) { self::$_instance = new self(); } return self::$_instance; } public function set_view(View $view) { $this->_view = $view; } public function __set($name, $options = array()) { $this->_templates[$name]; $this->_templates[$name]['path'] = $options[0]; $this->_templates[$name]['variables'] = $options[1]; } public function __get($name) { // when $this->paertial()->header; is called in view template // it extracts variables and includes template view render() method $file = $this->_templates[$name]['path']; $variables = $this->_templates[$name]['variables']; } }Hey guys im trying to make alternations to my personal framework by adding a Partial class as a helper to the View class so that I'm able to add partial templates in my bootstrap and load accordingly in my view template like a header and footer. what im after is a bit of advise on the functioning of my Action/View and Partial please (not sure if what im doing is really right although it does work) Basically my Controller will extend my action where a model and view is made for my controller to use. Then my partial class is sent as a helper to my view and a clone of view sent to my partial so that im able to use the view class in my partial to render my header and variables. (is this the correct way? or a good method?) here's my code...like I said any advise would be greatly appreciated... thank you i want to send products to resellers so they can show it to their clients but to show it not on my domain i thought of sending an email with html designed as my product details page BUT the problem here is that the forwarding action by my reseller will ruin the html mailer i thought of using php to pdf any other solutions thanks hi again guys n gals. Ive just pre-built a website that works fine. ive just moved all files to another server and now when i try to login it does nothing , also if i try to signup it gives this error ................. Code: [Select] Warning: gethostbyaddr() [function.gethostbyaddr]: Address is not a valid IPv4 or IPv6 address in /home/content/70/6589670/html/gaming/signup.php on line 87 i have NOT edited the code in anyway so m guessing its a server issue ... or could i be wrong ??? any help welcome , thanks for reading Before I go digging around for code or conversion to unix time stamp, I'm curious how many of you have a birthday entry on a form which is the least hassle for the person filling out the form. For example a text box and they can enter 12/1/1992 or 12/1/92 or 12-1-1992 or three text boxes for month, day and year and if so, require an 01 or a 08 or 4 characters for year. The second method with three boxes would easily convert to a date stamp entry on the other hand if there is a php conversion that would convert any format (12/1/1992, 12/01/92, etc) to a unix time stamp that would make it easier for the person filling out the form. Thanks in advance for any ideas or help. Mike Hello.
I'm in need of help when it comes to page rendering, is it good practice to have own html file for each controller and controller->method OR 1 view file for each controller and then dynamically change content depending on the method?
My structure is like so:
controllers methods
-------------
services-> repair, car glass.....
info-> contact, about me.....
What is the best or good practice to handle the content in the view? The content is always the same.
Thanks in advance.
Hey Ok i'd say i'm pretty average with HTML, CSS and PHP I have my own website - www.leedsmethockey.co.uk and i want to develop a new section... i'll try and explain as best i can i have a database with all the players and their email address... When someone is selected for a match i wish the website to email their email address to let them know... please could someone advice me where i need to start and what sort of code i need to be looking into? Many Thanks Ok. So I just started using prepared statements. One issue I ran into is that after inserting say "abc's" into the table with a prepared statement when I read that row and display it, it shows as abc\'s I have to use stripslashes on the variable before displaying it. I thought that with magic quotes. off this would not be a problem. Am I going to have to strip slashes on all fields now? Is there another way around it? here is my phpinfo for reference magic_quotes_gpc Off Off magic_quotes_runtime Off Off magic_quotes_sybase Off Off And compile options Configure Command './configure' '--host=i686-redhat-linux-gnu' '--build=i686-redhat-linux-gnu' '--target=i386-redhat-linux' '--program-prefix=' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib' '--libexecdir=/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/usr/com' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--cache-file=../config.cache' '--with-libdir=lib' '--with-config-file-path=/etc' '--with-config-file-scan-dir=/etc/php.d' '--disable-debug' '--with-pic' '--disable-rpath' '--without-pear' '--with-bz2' '--with-curl' '--with-exec-dir=/usr/bin' '--with-freetype-dir=/usr' '--with-png-dir=/usr' '--enable-gd-native-ttf' '--without-gdbm' '--with-gettext' '--with-gmp' '--with-iconv' '--with-jpeg-dir=/usr' '--with-openssl' '--with-png' '--with-pspell' '--with-expat-dir=/usr' '--with-pcre-regex=/usr' '--with-zlib' '--with-layout=GNU' '--enable-exif' '--enable-ftp' '--enable-magic-quotes' '--enable-sockets' '--enable-sysvsem' '--enable-sysvshm' '--enable-sysvmsg' '--enable-track-vars' '--enable-trans-sid' '--enable-yp' '--enable-wddx' '--with-kerberos' '--enable-ucd-snmp-hack' '--with-unixODBC=shared,/usr' '--enable-memory-limit' '--enable-shmop' '--enable-calendar' '--enable-dbx' '--enable-dio' '--without-mime-magic' '--without-sqlite' '--with-libxml-dir=/usr' '--with-xml' '--with-mhash=shared' '--with-mcrypt=shared' '--with-apxs2=/usr/sbin/apxs' '--without-mysql' '--without-gd' '--without-odbc' '--disable-dom' '--disable-dba' '--without-unixODBC' '--disable-pdo' '--disable-xmlreader' '--disable-xmlwriter' '--disable-json' Thanks JT |