PHP file_get_contents doesn't retrieve cookies - php

I've read some topics about this problem..and some people says to use cURL (althought I don't know how..)
I have two files, index.php and response.php.
index.php
/* After the body tag, in the middle of screen */
<?php echo file_get_contents('http://localhost/football/classes/response.php?type=clients'); ?>
This code was working perfectly until I realize that I need to retrieve the same info, but with cookies, when the page loads.
My old response.php file was this:
switch($_REQUEST['type']){
case 'clients':
$content = $load->clients();
echo $content;
break;
}
But now I need to do the same code but with a parameter, inside the function clients(). This parameter is a cookie.
switch($_REQUEST['type']){
case 'clients':
$display = 0;
if(isset($_COOKIE['display'])){
$display = 1;
}
$content = $load->clients($display);
echo $content;
break;
}
I do always receive $display = 0; because PHP doesn't detect the cookie. Although, this cookie is initialized in Chrome Cookies. Even if I do var_dump($_COOKIE); I still don't receive nothing.
I know that this problem is because of file_get_contents() How can I solve this problem?
Thanks.
Edit: Tried the #Martin solution, without success. file_get_contents receive cookies
<?php
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init ("http://localhost/football/index.php");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
$ch = curl_init ("http://localhost/football/classes/response.php?type=clients");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
echo $output;
?>
The page keeps on looping and doesn't stop. It shows nothing.

The super global $_COOKIE only contains the cookies that your visitor sent to your Web server when it requested your page, it will never contain the cookies that another server may send to your application when it loads another page.
But you can still retrieves all the response headers using $http_response_header.
More info in the PHP doc : $http_response_header

Related

Want to use cURL instead of SimpleXML_load_file()

Using below script I can parse API data successfully.
$xml_report_daily=simplexml_load_file("https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25");
foreach ($xml_report_daily as $report_daily):
$trans_id=$report_daily->TRANSID;
$trans_id=$report_daily->MID;
$trans_id=$report_daily->EXT;
$trans_id=$report_daily->USER;
endforeach;
XML data are something like this:
<DATABASE>
<RECORD>
<TRANSID>1348818</TRANSID>
<MID/>
<EXT>0</EXT>
<USER>00012345</USER>
</RECORD>
.
.
.
so on...
</DATABASE>
But I want to use cURL instead of simplexml_load_file. So I used below script but it is not giving any result data.
$url = "https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
$xml = curl_exec($ch);
echo $xml;
Please let me know what I am missing or doing wrong.
Thank you,
Ok, here is my complete answer and hope it will be useful to others.
I used 2 methods to read XML data from specific link.
Method# 1 : Using simplexml_load_file() - allow_url_fopen should be ON on hosting server for this method to work. This method is working fine both on my local as well as actual server.
$xml_report_daily=simplexml_load_file("https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25");
foreach ($xml_report_daily as $report_daily):
$trans_id=$report_daily->TRANSID;
$m_id=$report_daily->MID;
$ext_id=$report_daily->EXT;
$user_id=$report_daily->USER;
echo $trans_id." ".$m_id." ".$ext_id." ".$user_id."<br/>";
endforeach;
Method# 2 : Using cURL - After doing as suggested here, now this method too is working fine both on my local as well as actual server.
$url = "https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
$xml = curl_exec($ch);
$xml_report_daily = simplexml_load_string($xml);
foreach ($xml_report_daily as $report_daily):
$trans_id=$report_daily->TRANSID;
$m_id=$report_daily->MID;
$ext_id=$report_daily->EXT;
$user_id=$report_daily->USER;
echo $trans_id." ".$m_id." ".$ext_id." ".$user_id."<br/>";
endforeach;
When using cURL, I was getting no result data so paul-crovella suggested me to check error. so I used below script and I found that I was trying to acess https (SSL certificate) data as also mentioned by Raffy Cortez
if(curl_exec($ch) === false)
{ echo 'Curl error: ' . curl_error($ch); }
else
{ echo 'Operation completed without any errors'; }
To resolve this https (SSL certificate) related issue, here is very very helpful link and you can use any of methods mentioned there as per your necessity.
HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK
Thank you,
You are calling https URL in your cURL, you need to use
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Get last available URL

I am using an API to get the users profile picture. The call looks something like this
https://familysearch.org/platform/tree/persons/{$rid}/portrait?access_token={$_SESSION['fs-session']}&default=https://eternalreminder.com/dev/graphics/{$default_gender}_default.svg
This link only works for about an hour because the user's session token expires then. I was wondering if there was any way to retrieve the last returned returned URL, which would be the direct link to the image, so I could store that in a database.
I have tried Google but I don't really know where to start.
Thanks in advance!
I was able to solve my own problem. It was doing a redirect to get the image and I just needed that URL. Here is my code that helped me get there.
$url="http://libero-news.it.feedsportal.com/c/34068/f/618095/s/2e34796f/l/0L0Sliberoquotidiano0Bit0Cnews0C12735670CI0Esaggi0Eper0Ele0Eriforme0Ecostituzionali0EChiaccherano0Ee0Eascoltano0Bhtml/story01.htm";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch); // $a will contain all headers
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
// Uncomment to see all headers
/*
echo "<pre>";
print_r($a);echo"<br>";
echo "</pre>";
*/
echo $url; // Voila

passing variable to another page when it is called using curl_setopt

I am usig curl_setopt to eval another file from a different server, the link is something like this "http://somewhere.com/index.php?vars=hello"
now in somewhere.com/index.php i need to get the value of vars that was passed using curl, but so far i cant get any values at all.
here is my sample code for your reference this is from the file calling somewhere.com:
$d = "http://somewhere.com/index.php?vars=hello";
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_URL, $d);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, TRUE);
$data1 = curl_exec($ch1);
eval($data1);
curl_close($ch1);
in somewhere.com/index.php i already did print_r($_GET); to view any passed values to the file but it returned nothing.
What is happening in the index.php file with the variable "hello"? When you do a curl post to another page that other page typically will echo out a response and that response is what you evaluate. Can you post your code from index.php so we can see what you are trying to do?
Edit: Also you can use chrome inspector, fiddler or some other network monitor to see if the http request actually is being fired off and to check that you are actually getting a 200 response back.
Edit: I don't know what you are using eval either, just echo the response. If you have an output buffer issue then start buffering before you echo the response like:
ob_start():
echo $data1;
ob_end_clean();
Also if you want to see if you are getting any errors just do this:
if(curl_exec($ch1) === false)
{
echo 'Curl error: ' . curl_error($ch1);
}
else
{
echo $data1;
}
// Close handle
curl_close($ch1);
can't you just use $_GET[]?
i.e.
$variables = $_GET['vars'];

curl_exec() outputting destination contents to page?

I'm using the following code:
$ch = curl_init('www.google.com');
$output = curl_exec($ch);
curl_close($ch);
This is not the first time I've used cURL, and unless I'm mistaken the above code should retrieve the contents of google.com and store it in $output. Correct?
So, why then, does the above code output the contents (in this example the Google homepage) to the page? I'm not echo'ing anything out, but for some reason the curl_exec() function is outputting what it returns to the page.
Am I missing something?
you need to use
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
That will tell curl_exec not to output the results
so change it all to
$ch = curl_init('www.google.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

Unable to exchange Session Data in CURL

I call invoke.php using CURL from curl.php from my localhost. In invoke.php i store some data in session. But when i try to access those session data from curl.php, don't get those session data. How i get those values?
Content of curl.php
`include_once ('session.php');
$handles = array();
$urlArray = array('http://localhost/invoke.php' );
foreach($urlArray as $url){
// create a new single curl handle
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// add this handle to the multi handle
curl_multi_add_handle($mh,$ch);
// put the handles in an array to loop this later on
$handles[] = $ch;
}
// execute the multi handle
$running=null;
do {
curl_multi_exec($mh,$running);
// added a usleep for 0.25 seconds to reduce load
usleep (250000);
} while ($running > 0);
// get the content of the urls (if there is any)
for($i=0;$i
{
// get the content of the handle
// $output.= curl_multi_getcontent($handles[$i]);
// remove the handle from the multi handle
curl_multi_remove_handle($mh,$handles[$i]);
}
echo SessionHandler :: getData('DATA');
`
Content of invoke.php
include_once ('session.php');
echo SessionHandler :: setData('DATA', 'HELLO WORLD');
There are two possible issues:
You can't be sure that both scripts will access same session (have same session id), actually I can bet they have separate sessions. Of course, you could enforce that by sending the session id from invoke.php to curl.php by adding an extra parameter tot the URL and then use that parameter to force the session id in curl.php
Second possible issue is that the session variables are read on session_start (that's when the $_SESSION is populated), but you modify the session content after you start the session (in session.php, I assume), that's why any changes (even if the conditions on 1. will be met), will not reflect into already opened session in invoke.php. I think you should force session to close and restart it.
I had the same issue. This is how I resolved it:
function getContent($url){
$cookiesStr = '';
foreach($_COOKIE as $k => $v){
$cookiesStr.= $k . '=' . $v . '; ';
}#end COOKIE
$cookiesStr = rtrim($cookiesStr, ' ');
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIE, $cookiesStr);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return $string;
}#end getContent
You have to have a tmp cookie jar or it will produce an infinite loop. You have to send cookies or you will not get a result.
I able to solve this problem. I set curl_
setopt($ch, CURLOPT_COOKIE,session_name().'='.session_id());
to use same session id and use php's session_write_close() function to write session data.

Categories