how do you enable php to enable to make http calls - php

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);
}
?>

Related

PHP Socket Connection to an API

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.

How to make a HTTP request to a REST service in PHP?

I was wondering if anyone could help me understand how I would go about getting the JSON back using this information? Should I use cURL or fsockopen?
GET /market/10000002/orders/buy/?type=https://api-sisi.testeveonline.com/types/683/ HTTP/1.1
Host: https://api-sisi.testeveonline.com
Authorization: Bearer jKVB8oaN9qboU5kQG4sWSoWxzSUaFkQaUyeisy8jWU3apRfYSgYsKpZGNbLh41xXEzuy-NDBX1FohEdEadaukQ2
Accept: application/vnd.ccp.eve.MarketOrderCollection-v1+json
I have tried doing this, but I have no clue whether or not this is a feasible way of doing it?
$fp = fsockopen("api.eveonline.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /market/10000002/orders/buy/? type=https://api.eveonline.com/types/683/ HTTP/1.1\r\n";
$out .= "Host: https://api.eveonline.com\r\n";
$out .= "Authorization: Bearer ".auth."\r\n\r\n";
$out .= "Accept: application/vnd.ccp.eve.MarketOrderCollection-v1+json\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
Thanks
EDIT 1:
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Host: https://api.eveonline.com\r\n".
"Authorization: Bearer ".auth."\r\n".
"Accept: application/vnd.ccp.eve.MarketOrderCollection-v1+json\r\n"
)
);
$context = stream_context_create($opts);
$url = 'https://api.eveonline.com/';
$result = file_get_contents($url, false, $context);
This was my next attempt that I am still working on.
fsockopen is really not a good option for HTTP requests as you have to take care of everything yourself (such as compression, chunking, etc.). cURL sure is an option, but my favourite is just file_get_contents. You need to have allow_url_fopen set to On in the config, but that's not really a security risk and the function itself is very capable.

php curl hanging and infinite loop

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();

Downloading File from remote server using php script without fopen

Scenario : I have a c# .net web page. I want the user to be able to download a file placed on a remote server from a link on my page. However while downloading there should be minimum load on my server. Hence i tried creating a HttpWebRequest instance, passed the download.php path
e.g.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://servername/download.php");
myHttpWebRequest.Headers.Add
("Content-disposition", "attachment;filename=XXX.pdf");
myHttpWebRequest.ContentType = "application/pdf";
Passed the httprequest object in the session; however while reading the httpwebresponse on another page the contenttype is reset to "text/html".
Also the php file readers the headers and uses a readfile command to download the file. It gives the following error. Warning: readfile() [function.readfile]: URL file-access is disabled in the server configuration in
I don't entirely understand the scenario, but on PHP side, if fopen() URL access is disabled, your next port of call should be the curl family of functions. (Or, of course, activate URL access using the allow_url_fopen php.ini option but it sounds like you can't do that.)
The text/html header is probably due to the download failing.
A very rudimentary example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch); // $result will contain the contents of the request
curl_close($ch);
?>
You can get around allow_url_fopen restrictions by using fsockopen. Here's a (rudimentary) implementation:
function fsock_get_contents($url) {
$fp = fsockopen($url, 80, $errno, $errstr, 20);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
return false;
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: " . parse_url($url, PHP_URL_HOST) . "\r\n";
$out .= "Connection: Close\r\n\r\n";
$contents = '';
fwrite($fp, $out);
while (!feof($fp)) {
$contents .= fgets($fp, 128);
} fclose($fp);
return $contents;
}
}
echo fsock_get_contents('www.google.com');

PHP How To Send Raw HTTP Packet

I want to send a raw http packet to a webserver and recieve its response but i cant find out a way to do it. im inexperianced with sockets and every link i find uses sockets to send udp packets. any help would be great.
Take a look at this simple example from the fsockopen manual page:
<?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);
}
?>
The connection to the server is established with fsockpen. $out holds the HTTP request that’s then send with frwite. The HTTP response is then read with fgets.
If all you want to do is perform a GET request and receive the body of the response, most of the file functions support using urls:
<?php
$html = file_get_contents('http://google.com');
?>
<?php
$fh = fopen('http://google.com', 'r');
while (!feof($fh)) {
$html .= fread($fh);
}
fclose($fh);
?>
For more than simple GETs, use curl (you have to compile it into php). With curl you can do POST and HEAD requests, as well as set various headers.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://google.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($ch);
?>
cURL is easier than implementing client side HTTP. All you have to do is set a few options and cURL handles the rest.
$curl = curl_init($URL);
curl_setopt_array($curl,
array(
CURLOPT_USERAGENT => 'Mozilla/5.0 (PLAYSTATION 3; 2.00)',
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => 'User:Password',
CURLOPT_RETURNTRANSFER => True,
CURLOPT_FOLLOWLOCATION => True
// set CURLOPT_HEADER to True if you want headers in the result.
)
);
$result = curl_exec($curl);
If you need to set a header that cURL doesn't support, use the CURLOPT_HTTPHEADER option, passing an array of additional headers. Set CURLOPT_HEADERFUNCTION to a callback if you need to parse headers. Read the docs for curl_setopt for more options.

Categories