After struggling for half a day, I finally manage to get reCAPTCHA to work by converting this function:
function _recaptcha_http_post($host, $path, $data, $port = 80) {
$req = _recaptcha_qsencode ($data);
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($req) . "\r\n";
$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
$http_request .= "\r\n";
$http_request .= $req;
$response = "";
if( false == ( $fs = #fsockopen($host, $port, $errno, $errstr, 10) ) ) {
die ("Could not open socket");
}
fwrite($fs, $http_request);
while ( !feof($fs) )
$response .= fgets($fs, 1160); // One TCP-IP packet
fclose($fs);
$response = explode("\r\n\r\n", $response, 2);
return $response;
}
to:
function _recaptcha_http_post($host, $path, $data, $port = 80) {
$req = _recaptcha_qsencode ($data);
$request = curl_init("http://".$host.$path);
curl_setopt($request, CURLOPT_USERAGENT, "reCAPTCHA/PHP");
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $req);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
return $response;
}
Basically, I am interested to find out why curl works while fsockopen fails with "Could not open socket". Thanks.
In addition: Sockets Support is enabled.
I might be wrong, but you use $port = 80 in fsockopen() while in cURL case this variable is not used at all. I had same problem when tried to connect to SSL via port 80 instead of port 443; as far as I know, cURL checks SSL by default and connects accordingly.
Also, try running cURL with CURLOPT_VERBOSE to see what it does.
What is in $errno and $errstr inside if(false === ...)? So, what does it output if you change to
if( false == ( $fs = #fsockopen($host, $port, $errno, $errstr, 10) ) ) {
die ("Could not open socket, error: " . $errstr);
}
Googling for your error leads to wonder if your /etc/resolv.conf is readable by PHP. Do ls -lah /etc/resolv.conf in the bash to see if it is readable. You will get something like:
myserver:~ myname$ ls -lah /ets/resolv.conf
lrwxr-xr-x 1 root wheel 20B 16 mrt 2011 /etc/resolv.conf
^ if there is an 'r' here it is readable. if you have '-' here, it is not.
If it is not readable, try doing in the bash: chmod 644 /etc/resolv.conf to make it readable.
Woah,
if( false == ( $fs = #fsockopen($host, $port, $errno, $errstr, 10) ) ) {
die ("Could not open socket");
}
That doesn't make any sense surely. Try:
$fs = fsockopen($host, $port, $errno, $errstr, 10); // # ignores errors
if(!$fs) die ("Could not open Socket");
Also Skype also blocks port 80 sometimes.
Related
I'm trying to connect to an API using PHP Sockets.
I've tried it in many ways, but I can't get it working. I know there is other answers, but no one works. I really can't achieve it. I'm trying it at least two days.
Here is the error:
php_network_getaddresses: getaddrinfo failed: Name or service not known
Code (Sockets - It does not work):
var $url = 'api.site.com.br/';
public function getUsers(){
$path = "users/?accesstoken=c24f506fe265488435858925096bc4ad7ba0";
$packet= "GET {$path} HTTP/1.1\r\n";
$packet .= "Host: {$url}\r\n";
$packet .= "Connection: close\r\n";
if (!($socket = fsockopen($this->url,80,$err_no,$err_str))){
die( "\n Connection Failed. $err_no - $err_str \n");
}
fwrite($socket, $packet);
return stream_get_contents($socket);
}
Code (Curl - It Works!):
public function getUsers2(){
$path = "users/?accesstoken=c24f506fe265488435858925096bc4ad7ba0";
$method = 'GET';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url . $path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);
return $output;
}
I can't give to you the correct URL, but the URL is working with Curl, so it should work with sockets.
I solved it by doing the following:
public function getUsers(){
$path = "users/?accesstoken=c24f506fe265488435858925096bc4ad7ba0";
$fp = fsockopen($this->url, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /{$path} HTTP/1.1\r\n";
$out .= "Host: {$this->url}\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
}
Connecting to a host via socket is not connecting to a URL.
Wrong: api.site.com.br/
Wrong: http://api.site.com.br/
Wrong: https//api.site.com.br/api/
Right: api.site.com.br
You connect to a host. This can be a domainname or an IP. Neither of those has a slash in it.
i have been working on a scraper tool that rips google search results and then crawls the results websites looking to match specific items.
I'm having an issue with cURL though. I have come accross a site that is causing curl to go into an infinite loop.
website in question.
http://www.darellyelectrical.com/
when i open up my packet sniffer and look through tcp http packets ive found the same request is being sent over and over again.
i can not pinpoint the reason why, I have no trouble with any other websites.
I have tried setting the following curl options
curl_setopt($this->sessions[$key], CURLOPT_TIMEOUT, $timeout);
curl_setopt($this->sessions[$key], CURLOPT_MAXREDIRS, 2);
curl_setopt($this->sessions[$key], CURLOPT_CONNECTTIMEOUT, 1);
be great if someone could test that url with curl and let me know if the issue persists.
thanks
EDIT**
function sck_send()
{
$host = "www.darellyelectrical.com";
$path = "";
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /".$path." HTTP/1.1\r\n";
$out .= "Host: ".$host."\r\n";
$out .= "Connection: Close\r\n\r\n";
$data = "";
fwrite($fp, $out);
while (!feof($fp))
{
$data .= fgets($fp, 128);
}
fclose($fp);
echo $data;
}
}
sck_send();
this will produce the loop same as curl.
That server needs the User-Agent header to be included or it does not respond. PHP's curl doesn't set this by default and it wouldn't be included in a socket request unless you specify it. The code below works for me:
<?php
function sck_send() {
$host = "www.darellyelectrical.com";
$path = "";
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /".$path." HTTP/1.1\r\n";
$out .= "Host: ".$host."\r\n";
$out .= "User-Agent: Mozilla/5.0 \r\n";
$out .= "Connection: Close\r\n\r\n";
$data = "";
fwrite($fp, $out);
while (!feof($fp)) {
$data .= fgets($fp, 128);
}
fclose($fp);
echo $data;
}
}
sck_send();
After trying all night without any success, this is the code that I have should work but not working:
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://api.keynote.com/keynote/',
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
// Close request to clear up some resources
curl_close($curl);
echo $resp;
?>
The error that I am getting is this:
Error: "Failed connect to api.keynote.com:80; No error" - Code: 7
On the server, I can manually bring up this url with any browser without any problems.
How do I make php connec to internet?
The thing is that fsockopen is used for opening socks (i.e connect to the specified port on the specified host/IP).
When you try to open sock to the host "http://google.com" it is like running "ping http://google.com" - you will get an error - as there is no such host "http://"
What you shout do is use http_get or curl
<?php
$response = http_get("http://www.example.com/", array("timeout"=>1), $info);
print_r($info);
?>
or remove the "http://"
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
I am totally new to php. I had 2 pages let A.php and B.php want to run Page B while I am at Page A.For that I had created a Socket Connection and able to run The Page B but problem is that when I send an array of objects to page B.page A send only the First object listed in the array and other values of the array were nothing
here is my some code
in A.php
$arr = array("message" => $pushData,
"messageType" => $messageType,
"displayGroupID" => $displayGroupID,
"db"=>$db);
$fp1 = $this->JobStartAsync('localhost', 'B.php', $arr);
$r1 = $this->JobPollAsync($fp1);
function JobStartAsync($server, $url, $data, $port=80,$conn_timeout=10, $rw_timeout=86400)
{
$errno = '';
$errstr = '';
$data = http_build_query($data);
set_time_limit(0);
$fp = fsockopen($server, $port, $errno, $errstr, $conn_timeout);
if (!$fp)
{
echo "$errstr ($errno)<br />\n";
return false;
}
$out = "POST $url HTTP/1.1\r\n";
$out .= "Host: $server\r\n";
$out .= "Content-type: application/x-www-form-urlencoded\r\n";
$out .= "Content-length: ". strlen($data) ."\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= "$data";
stream_set_blocking($fp, false);
stream_set_timeout($fp, $rw_timeout);
fwrite($fp, $out);
//fwrite($fp, $data);
return $fp;
}
function JobPollAsync(&$fp)
{
if ($fp === false)
return false;
if (feof($fp))
{
fclose($fp);
$fp = false;
return false;
}
return fread($fp, 10000);
}
IN B.php
fileWrite ($_POST['displayGroupID'],$_POST['message'],$_POST['messageType']);
it get only "message" as it is listed as 1st element in array
Take a look at CURL. This is what you need and everyone else uses.
ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
For async variation take a look at a similar question answered before - How do I make an asynchronous GET request in PHP?
SOLVED: Issue was in Content-type. Should have been
Content-Type: application/x-www-form-urlencoded
Helping link: http://www.bradino.com/php/empty-post-array/
I cannot seem to get POST data to send. I've combed over this method for a while now and each time I run a test, the $_POST array is empty.
$output = new SimpleXMLElement($xml);
$params = "method=updateOrder&xml=".$output;
$response = Rest::Post("example.com", 80, "/resource/path.php", $params);
Above is another method I call statically which creates the HttpRequest with the desired method. Below is the method that gets sub-called and passed the same data but including the method name. IE: POST.
private static function httpRequest($host, $port, $method, $path, $params)
{
//Check method
if(empty($method))
$method = "GET";
$method = strtoupper($method);
//Port
if(empty($port))
$port = 80;
//Build Querystring
$data = "";
if(!empty($params) && $method == "GET")
foreach($params as $name => $value)
{
$data .= $name . "=" . urlencode($value) . "&";
}
if($method == "GET" && !empty($data))
$path .= "?" . $data;
//connection
$socket = fsockopen($host, $port);
if(!$socket)
die("Socket failed, no connection.");
//Write Data and headers to stream
fputs($socket, $method ." ". $path . " HTTP/1.1\r\n");
fputs($socket, "Host: " . $host . "\r\n");
if($method === "POST")
{
fputs($socket, "Content-type: text/xml\r\n");
fputs($socket, "Content-length: " . strlen($params) . "\r\n");
}
fputs($socket, "Connection: close\r\n\r\n");
//Write body
if($method === "POST")
fputs($socket, $params);
//Gets headers
$responseHeader = "";
do
{
$responseHeader .= fgets($socket, 1024);
}
while(strpos($responseHeader, "\r\n\r\n") === false);
//Gets body
$responseBody = "";
while(!feof($socket))
$responseBody .= fgets($socket, 1024);
//Done & return
fclose($socket);
return array(0=>$responseHeader, 1=>$responseBody);
}
You should consider using the built-in cURL library.
function httpRequest($host, $port = 80, $method = 'GET', $path = '/', $params = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if ( ! empty($port) )
curl_setopt($ch, CURLOPT_PORT, $port);
if ( ! empty($method) && $method == 'POST' )
{
curl_setopt($ch, CURLOPT_URL, $host . ( ! empty($path) ? $path : '/' ));
curl_setopt($ch, CURLOPT_POST, TRUE);
if ( ! empty($params) )
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
else
curl_setopt($ch, CURLOPT_URL, $host . ( ! empty($path) ? $path : '/' ) . ( ! empty($params) ? '?' . $params : null ));
$result = curl_exec($ch);
curl_close($ch);
return explode("\r\n\r\n", $result, 2);
}
The function above will return an array containing the headers and the body.
Does this help?
Change
fputs($socket, "Content-type: text/xml\r\n");
to
fputs($socket, "Content-type: application/x-www-form-urlencoded\r\n");