Log in

View Full Version : php socket send receive like curl



ggalan
10-15-2012, 07:14 PM
can anyone help me better understand socket connections please
if i have a socket connection like so

$address = gethostbyname('**.***.**.***');
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_bind($socket, $address, '8000');

How can i have a particular file read this socket and how would i be able to pass strings or variables?
The concept i have is like cUrl.
In the example below i have the receive as receive.php
with $_GET variables

send:

$url = "http://mydomain.com/process.php?var=1";
$ch = curl_init($url);
curl_exec ($ch);
curl_close ($ch);

receive:

$var= $_GET['var'];

traq
10-16-2012, 12:29 AM
Are you on the sending or receiving end?
Is there some reason you don't want to use cURL? You could also use fsockopen() (http://php.net/fsockopen) to do this kind of thing; I find it much easier, personally.

ggalan
10-16-2012, 12:57 AM
i wanted to set up both send and receive, this is to communicate with a different server on AWS.
would fsockopen() work the same way as tcp, when communicating with other servers?

traq
10-16-2012, 01:54 AM
yeah, you literally write the HTTP request and then send it to the target page. PayPal does this with some of their APIs.

The receiving page sends the response as normal (no fancy whatevers, just echo it).

example:
<?php

# untested, but similar to working scripts I've made in the past

$connection = fsockopen("example.com", 80, $errno, $errstr, 30);
if (!$connection) { print "$errstr ($errno)<br />\n"; }
else {
$request = "GET /process.php?var=somevalue HTTP/1.1\r\n";
$request .= "Host: example.com\r\n\r\n";
fputs( $connection,$request );
while( !feof( $connection ) ){
print fgets($fp, 128);
}
fclose($fp);
}