fsockopen, cURL, and file_get_contents are slow - php

I have no clue why... But all the methods I listed in the title are slow. They take about 10 seconds, yet when I visit the sites, they load immediately. Here is one of my codes that uses file_get_conents:
<?php
$search = $_GET['search'];
$postdata = http_build_query(
array(
'searchnode' => '' . $search . ''
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Connection: close',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://google.com', false, $context);
echo $result;
?>
This code is just an example of what I use. But even using this code, it loads slow. I am using "Connection: close" also. Is this possibly a problem with the PHP config, or something else? I am using CentOS with cPanel + WHM. I do have shell and root access.

It could be that the DNS on your server is slow, try this:
replace
$result = file_get_contents('http://google.com', false, $context);
with
$ip = gethostbyname('google.com');
$result = file_get_contents("http://$ip", false, $context);

Related

PHP: Using file_get_contents to access an API - Empty Response

Sorry for the messy code in advance. I want to write a code which returns me infos from the official Blizzard API, which I can then print out on my homepage. The code doesn't throw any errors but it doesn't print out something either. For Starters:
I would also prefer using CURL, but my homepage is on a Wordpress Hosting Site and I don't know how to install the CURL Library that way
allow_furl_open is on
$url = "https://eu.battle.net/oauth/token";
$data = array('grant_type' => 'client_credentials');
//HTTP options
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array ('Content-type: multipart/form-data', 'Authorization: Basic ' .
base64_encode("$client_id:$client_pass")),
'content' => json_encode($data)
)
);
//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
$accessToken = $json['access_token'];
$tokenURL = "https://us.api.blizzard.com/data/wow/token/?namespace=dynamic-eu";
$opts2 = array('http' =>
array(
'method' => 'POST',
'header' => array('Content-type: multipart/form-data', 'Authorization: Bearer ' . $accessToken),
)
);
$context2 = stream_context_create($opts2);
$json2 = file_get_contents($tokenURL,false,$context2);
$result2 = json_decode($json2, true);
$tokenprice = $result2['price'];
echo "<p>Tokenpreis:" .$tokenprice. "</p>";
I didn't add the $client_id and $client_pass into the code snippet, but this exists obviously. I used this PHP CURL Snippet as template. And this is a short explanation on blizzard's site on how is this supposed to work:
Anyone got any ideas what went wrong? I am really out of ideas here and would love anyone who could help.
Thanks in advance
Based on the curl example from the linked API docs, the content type should be application/x-www-form-urlencoded, and so for the initial request to https://eu.battle.net/oauth/token you should be able to follow the example here.
In your case this will look something like:
$url = 'https://eu.battle.net/oauth/token';
$data = array('grant_type' => 'client_credentials');
$opts = array(
'http' => array(
'method' => 'POST',
'header' => array (
'Content-type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode("$client_id:$client_pass")
),
'content' => http_build_query($data)
)
);
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
Also, in your code you are storing the raw result from the initial request in $json, then the decoded array in $result, but attempting to get the access_token from the initial request, instead of the decoded array.

file_get_contents not working sometimes?

I have a simple file_get_contents using basic http auth:
$opts = array(
'http' => array(
'timeout' => 15,
'header' => array("Authorization: Basic "
. base64_encode("$user:$pwd"))
)
);
$context = stream_context_create($opts);
$data = file_get_contents($url, false, $context);
When I run this inside one PHP box, it arrives without the Authorization header. When I run it in another box, the header arrives.
What kind of info do I need to look for in order to find the cause?

PHP POST API call

Trying to make a POST API call and I get the error file_get_contents(http://api.turfgame.com/v4/users): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request. API info can be found at http://api.turfgame.com
<?php
$data = array("name" => "DIProgan");
$url = 'http://api.turfgame.com/v4/users';
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
var_dump($response);
?>
Using XAMPP & PHP 5.4.4. I tried using "requests for PHP" since I liked the Python version of it but it just complains about not finding hook functions. People seem to hate cURL and from the little I need it seemed easier without it. Maybe not. Help?
It seems like you have just created an array where you have put your parameter. It should be stored within an object first.

PHP file_get_contents different behaviour for the same domain

I've a probably really silly question about file_get_contents, I want to retrieve content on a website and this works properly when I serve to the below code:
$file = file_get_contents( $dataSourceURL, false, $context );
$dataSourceURL = 'http://somedomain.com', but when I'm serving a specific page of this website like $dataSourceURL = 'http://somedomain.com/c-4-hookah-coals-hookah-charcoal.html' it returns nothing.
Does anybody know something about this issue?
UPDATE
I know we can pass GET params using the below code:
$getdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $getdata
)
);
$context = stream_context_create($opts);
but than... is there a simple way to resolve this kind of url query 'c-4-hookah-coals-hookah-charcoal.html' ?
file_get_contents works like unix wget, so you can try simply:
echo file_get_contents('http://www.hookah-shisha.com/c-4-hookah-coals-hookah-charcoal.html');

posting json data with curl and failing

I have this function here:
public static function call($action, array $args)
{
$post_args = array(
'action' => $action,
'args' => $args
);
$stream = json_encode($post_args);
$headers = array(
'Content-type: application/json',
'Accept: application/json',
'Expect:'
);
$userpwd = self::$_user.':'.sha1(sha1(self::$_pass));
$ch = curl_init();
$args = array(
CURLOPT_URL => self::$_url,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $stream,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userpwd
);
curl_setopt_array($ch, $args);
$res = curl_exec($ch);
$data = json_decode($res, true);
if (isset($data) === TRUE
&& empty($data) === FALSE
) {
$res = $data;
}
return $res;
}//end call()
and at the URL where I'm posting, I'm just doing:
echo file_get_contents('php://input');
but getting nothing, even though I do post data. What could be the problem? I'm at a dead end.
Also, why do I need CURLOPT_FOLLOWLOCATION set to TRUE when I'm just posting to a simple virtual host URL on my local machine, not doing any redirects.
EDIT:
tried redoing it with fopen like so:
public static function call($action, array $args)
{
$post_args = array(
'action' => $action,
'args' => $args
);
$stream = json_encode($post_args);
$userpwd = self::$_user.':'.sha1(sha1(self::$_pass));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => array(
"Authorization: Basic ".base64_encode($userpwd),
"Content-type: application/json"
),
'content' => $stream
)
);
$context = stream_context_create($opts);
$res = '';
$fp = fopen(self::$_url, 'r', false, $context);
if($fp){
while (!feof($fp)){
$res .= fread($fp, 128);
}
}
return $res;
}//end call()
no success. The connection works with curl and with fopen, since I pass the status along with result (which is just the php://input stream). Any ideas?
Can you be sure about that curl_exec function ends successfully. Also, why don't you use fopen for this purpose. I have written a JSON RPC client and server. I'm sending requests with fopen, and it works perfect.
$httpRequestOptions =
array(
'http'=>array(
'method'=>'POST',
'header'=>'Content-type: application/json',
'content'=>$requestJSON
)
);
$context = stream_context_create($httpRequestOptions);
// send request
if($fileHandler = #fopen($serverURL, 'r', false, $context)){
I'm not writing the rest. You can use this code I have written.
Found out the problem.
I was calling http://localhost/api, since I thought that it would load the index.php automatically, and then I was going to change the default file name for the folder.
The problem was that I didn't add index.php at the end - I should've called http://localhost/api/index.php.
This way it worked with cURL and with fopen.
Any ideas how to call the API without revealing the filename?

Categories