I'm using PHP 5.2.17 to get a remote page, the HTTP requests contains some cookie values but cookies are not delivered to the destination page.
$url = 'http://somesite.com/';
$opts = array(
'http' => array
(
'header' => array("Cookie: field1=value1; field2=value2\r\n")
)
);
$context = stream_context_create($opts);
echo file_get_contents($url, false, $context);
Can you help me find the problem?
Note: I can't use curl.
Thanks.
Are you sure the receiving code is working properly?
I can get your example to work with the receiving page simply echoing:
<?php
echo $_COOKIE['field1'] . '::' . $_COOKIE['field2']; // returns value1::value2
?>
Alternatively, the site could be requiring a user agent (anything). I had this problem earlier in reaching Wikipedia (not restricted by all Mediawiki software; apparently just for the Wikimedia sites). Set the user_agent property inside the 'http' array to whatever value you want. (However, if you do happen to be trying to reach Wikipedia, you might instead try their api.php: http://en.wikipedia.org/w/api.php ; if another Mediawiki site, use the same relative path)
Maybe allow_url_fopen is not enabled, check the value w/ ini_get: ini_get('allow_url_fopen');
You might also do a sanity check by calling file_get_contents() on any old page you know is publicly accessible.
Other than that your example code looks just fine.
Second Option, Socket Connection:
<?php
$fp = fsockopen("somesite.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: somesite.com\r\n";
$out .= "Cookie: field1=value1; field2=value2; path=/; domain=somesite.com;\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
echo PHP_EOL;
$url = 'http://somesite.com/';
$opts = array(
'http' => array
(
'header' => "Cookie: field1=value1; field2=value2\r\n"
)
);
$context = stream_context_create($opts);
file_get_contents($url, false, $context);
Related
I am working on twitter login integration with website. I don't have cURL installed in my server and I am not allowed to install that.
Twitter code is working fine for login. But while using request_token curl is used to send callback URL with that URL and getting the token response. In this same case I want to get the response from that URL without using Curl in PHP. Is it possible?
Curl code now used:
$response = curl_exec($ci);
The above response I need without using Curl.
How to get the response from url without Curl
You don't have to necessarily use cURL, there can be many ways. One of those is:
$response=file_get_contents($ci);
Edit:
You can also use fsockopen, here is an example from PHP.net
<?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);
}
?>
file_get_contents with https hosts works just fine, except for a particular host (test api server from some company - ip whitelisted, can't give you URL to test). This rules out not loaded https modules and other initial setup mistakes.
I have tested with multiple PHP installations, all at v5.3.3, 32bits, Debian 32bits.
The request works with cURL, but only if setting curl_setopt($curl,
CURLOPT_SSL_VERIFYPEER, 0);. However, setting verify_peer"=>false on the context for file_get_contents seems to make no difference.
With file_get_contents, the exact same request (same URL, same XML POST data) fails with SSL: Connection reset by peer:
$arrContextOptions=array(
"http" => array(
"method" => "POST",
"header" =>
"Content-Type: application/xml; charset=utf-8;\r\n".
"Connection: close\r\n",
"ignore_errors" => true,
"timeout" => (float)30.0,
"content" => $strRequestXML,
),
"ssl"=>array(
"allow_self_signed"=>true,
"verify_peer"=>false,
),
);
file_get_contents("https://somedomain:2000/abc/", false, stream_context_create($arrContextOptions));
.
Has anyone encountered this with file_get_contents? Any ideas how to debug?
You missed verify_peer_name. If you set that to false as well, the request works:
$arrContextOptions=array(
"http" => array(
"method" => "POST",
"header" =>
"Content-Type: application/xml; charset=utf-8;\r\n".
"Connection: close\r\n",
"ignore_errors" => true,
"timeout" => (float)30.0,
"content" => $strRequestXML,
),
"ssl"=>array(
"allow_self_signed"=>true,
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
file_get_contents("https://somedomain:2000/abc/", false, stream_context_create($arrContextOptions));
dont' know if this will actually help, but do try removing the SSL options from your option array.
The reason behind this:
according to http://www.php.net/manual/en/context.ssl.php , verify_peer is false by default.
allow_self_signed REQUIRES verify_peer, and is false by default.
From the above, I gather that allow_self_signed probably overrides your setting for verify_peer.
So please try without any option for SSL, or without the allow_self_signed, and let us know if that helped any.
You could try to debug this with Wireshark -- you might get a better idea of what goes wrong, you should see which SSL error occurs.
try this code :
$fp = fsockopen("ssl://somedomain/abc/", 2000 , $ErrNo, $ErrString, 30);
if (!$fp) {
echo "Error No : $ErrNo - $ErrString <br />\n";
} else {
$out = "POST / HTTP/1.1\r\n";
$out .= "Host: somedomain \r\n";
$out .= "Content-Type: application/xml; charset=utf-8;\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
if you don't get error , i think problem (with file_get_contents) is form client php configuration otherwise from server configuration.
only install this
yum install ca-certificates.noarch
Here's my code:
$language = $_GET['soundtype'];
$word = $_GET['sound'];
$word = urlencode($word);
if ($language == 'english') {
$url = "<the first url>";
} else if ($language == 'chinese') {
$url = "<the second url>";
}
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"User-Agent: <my user agent>"
)
);
$context = stream_context_create($opts);
$page = file_get_contents($url, false, $context);
header('Content-Type: audio/mpeg');
echo $page;
But I've found that this runs terribly slow.
Are there any possible methods of optimization?
Note: $url is a remote url.
It's slow because file_get_contents() reads the entire file into $page, PHP waits for the file to be received before outputting the content. So what you're doing is: downloading the entire file on the server side, then outputting it as a single huge string.
file_get_contents() does not support streaming or grabbing offsets of the remote file. An option is to create a raw socket with fsockopen(), do the HTTP request, and read the response in a loop, as you read each chunk, output it to the browser. This will be faster because the file will be streamed.
Example from the Manual:
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
header('Content-Type: audio/mpeg');
$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 above is looping while there is still content available, on each iteration it reads 128 bytes and then outputs it to the browser. The same principle will work for what you're doing. You'll need to make sure that you don't output the response HTTP headers which will be the first few lines, because since you are doing a raw request, you will get the raw response with headers included. If you output the response headers you will end up with a corrupt file.
Instead of downloading the whole file before outputting it, consider streaming it out like this:
$in = fopen($url, 'rb', false, $context);
$out = fopen('php://output', 'wb');
header('Content-Type: video/mpeg');
stream_copy_to_stream($in, $out);
If you're daring, you could even try (but that's definitely experimental):
header('Content-Type: video/mpeg');
copy($url, 'php://output');
Another option is using internal redirects and making your web server proxy the request for you. That would free up PHP to do something else. See also my post regarding X-Sendfile and friends.
As explained by #MrCode, first downloading the file to your server, then passing it on to the client will of course incur a doubled download time. If you want to pass the file on to the client directly, use readfile.
Alternatively, think about if you can't simply redirect the client to the file URL using a header("Location: $url") so the client can get the file directly from the source.
I have a php script that I recently added an array to. The php script checks URL's from the array for a set of text also in the array. Everything works great except the script will not follow redirects or check sub-pages.
I have been told that this is a limitation of fsocketopen and that I need to use CURL.
If this is the case then I require some assistance converting this from using fsocketopen to CURL. Hopefully there is some way to get fsocketopen to follow redirects or at least access sub-pages.
function check($host, $find){
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp){
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host){
$headers = 'From: Set your from address here';
mail('my-email#my-domain.com', 'Website Monitoring', $host.' is down' $headers);
}
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.com' => 'content on second site',
);
//if (!check($host, $find)) alert($host);
foreach ($hostMap as $host => $find){
if( !check( $host, $find ) ){
alert($host);
}
}
unset($host);
unset($find);
Apparently I wasn't clear in my question. I am looking for confirmation that fsocketopen cannot follow redirects or that it cannot go to a sub-page (url.com/subpage).
If this is the case, is CURL my best option and are there any examples I can look at?
When you get the data returned from feof(), you can parse out the redirect information from the headers and create connect to that, but that is kind of annoying and cURL does it on its own.
You should just be able to use
$ch = curl_init($host);
curl_setopt_array($ch, array(
CURLOPT_RETUNTRANSFER => true
, CURLOPT_FOLLOWLOCATION => true
, CURLOPT_HEADER => true
));
$str = curl_exec($ch);
cURL follows redirects by default using the Location: header.
Apologies for newbishness of this question. I'm looking into integrating one website's API into my own website. Here's some quotes from their documentation:
At the moment we only support XML,
when calling our API the HTTP Accept
header content type must be set to
“application/xml”.
The API uses the PUT request method.
I have the XML I want to send, and I have the URL I want to send it to, but how do I go about constructing a suitable HTTP Request in PHP that will also grab the XML that's returned?
Thanks in advance.
You can use file_get_contents and stream_context_create to create a request and read the response. Something like this will do it:
$opts = array(
"http" => array(
"method" => "PUT",
"header" => "Accept: application/xml\r\n",
"content" => $xml
)
);
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
This is actually what worked for me:
$fp = fsockopen("ssl://api.staging.example.com", 443, $errno, $errstr, 30);
if (!$fp)
{
echo "<p>ERROR: $errstr ($errno)</p>";
return false;
}
else
{
$out = "PUT /path/account/ HTTP/1.1\r\n";
$out .= "Host: api.staging.example.com\r\n";
$out .= "Content-type: text/xml\r\n";
$out .= "Accept: application/xml\r\n";
$out .= "Content-length: ".strlen($xml)."\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= $xml;
fwrite($fp, $out);
while (!feof($fp))
{
echo fgets($fp, 125);
}
fclose($fp);
}