• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4122
  • Last Modified:

Using PHP/CURL with Cookies

I need to access a web page and pass a PHPSESSID from an existing session.

I have tried it two ways (see code).

Both of these work perfectly in their own script.  However when I put either of these code segments into my main page it dies.  Basicially with #1 using file_get_contents(), I get no error message, it just times out, and after 120 seconds the rest of the page loads.

With #2 CURL I get a CURL error 28, Operation timed out after 5 seconds with 0 bytes received.

I know for sure that the page loads as it loads when these snippits run by itself, as well as it runs when I go into the command line and open it with lynx and/or wget.

The main page seems valid, it works except for pulling in the string from the external page.  The main page is fairly complex in that it does have set a session, it uses a lot of javascript/AJAX type code, as well as PHP/DB type stuff as well.

I need this answered by tomorrow, or I'm going to have to start over from scratch with a different approach.

The solution needs to make this code work in my main page.

Please let me know if I can provide any other info.

Also this is being ran on a PHP5 based system running Red Hat/Apache/Plesk.  Open basedir is turned off, and allow_url_fopen is enabled.  Again the scripts above work in isolation, but not from within the main page.

Thanks in advance for any assistance
-----1----------
$phpsessionID	= 'ahnvr6hr1veh6rru4brjm3aj45' ;
$url		= 'http://website/directory/file.php?ID=XXXX&second=YYYY' ;
$opts = array(
		'http' => array(
			'method' => 'GET',
			'header' => 'Cookie: PHPSESSID='.$phpsessionID
		)
	);
$context	= stream_context_create($opts);
$string		= file_get_contents($url, 0, $context);
 
 
-------2-----------
$phpsessionID	= 'ahnvr6hr1veh6rru4brjm3aj45' ;
$url		= 'http://website/directory/file.php?ID=XXXX&second=YYYY' ;
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch,CURLOPT_COOKIE,'PHPSESSID='.$phpsessionID);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$outputA = curl_exec($ch);
curl_close($ch);
 
$string	= $outputA ;

Open in new window

0
blainehilton
Asked:
blainehilton
  • 4
  • 4
  • 3
2 Solutions
 
lavinpj1Commented:
There's not a whole lot we can do without being able to see the context that this code works in.

Phil
0
 
aconradCommented:
Use Firefox's LiveHeaders extension to get a good set of headers.
https://addons.mozilla.org/en-US/firefox/addon/3829


Then in your script use
CURLINFO_HEADER_OUT -- for headers sent
and
CURLOPT_HEADER -- for headers received
( http://www.php.net/manual/en/function.curl-getinfo.php )

This way you can print the headers your script does/gets.
Check the diference with the good ones and see whats going on ...
0
 
aconradCommented:
also, plesk's php may be blocked from loading sites, command line wget lynx can still work ...
try running
php yourscript.php
from the command line see if it still works...
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
blainehiltonAuthor Commented:
lavinpj1, I didn't explain it clearly.  Probably because I wasn't sure myself.  I've made some other tests though and if I remove just the session_start() call it works.

The main page has a call to session_start() to maintain a users session as they must be logged in to view page.

If I remove session_start() it works.

However I do need to maintain the users session, and pull data from another page.

How would I do this?
0
 
lavinpj1Commented:
Surely the session would be maintained anyway by the user's client passing the ID in the cookie?

Phil
0
 
blainehiltonAuthor Commented:
I just tried it with commenting out the cookie line, and it loads, but it does not load the data that is associated with the session.  So no the session data that the USER receives is not carried over to the call made by the SERVER.


Maybe I'm going about this all wrong?  The idea is I'm keeping in a php session variable an array of items in a list.  Thats all fine and dandy, the fun comes when I have a list that I want you to be able to add things to and it would update the list using AJAX.  That part works fine too, the problem is that the javascript needs to be able to read the PHP data somehow.

So that's where the separate script that just returns the data as a string comes into play.

Just wanted to give the backstory.....
0
 
blainehiltonAuthor Commented:
aconrad, I can run the scripts above as long as session_start() is not called before hand.  However the problem is session_start() MUST be called to make the rest of the page work properly.

As for not working with Plesk I can run the script, just not with session_start().

Also I could not get the headers to display.  I even looked it up in the PHP manual and read an entry that said you also must add curl_setopt($handle, CURLINFO_HEADER_OUT, true); but no luck.

I have LiveHeaders installed, but its hard for me to read properly because I'm not use to it and I have a lot of other plugins and stuff happening so there is a lot going through there.

Any other ideas?
0
 
lavinpj1Commented:
Am I right in thinking you wish to maintain a session across servers? If so, I do not see why you would need to discover the session ID. Can it not be passed as part of a url/post data etc.?

Phil
0
 
blainehiltonAuthor Commented:
Both pages are actually in the same server.  The problem is more related to how do I pull data.....

lavinpj1, I think you are onto something!

I simply did an implode() in PHP and it put the needed data into my javascript!



Just in case I needed to do this though, how would I be able to do a CURL call with a session, inside of a page with another session?
0
 
lavinpj1Commented:
If they are on the same server, site1.com/page.php can have a link to site2.com/page2.php?sessid=<id here>.

page2.php on site2.com can then do session_start($_GET['sessid']);

The CURL call should just be a case of passing the PHPSESSID cookie with the ID.

Phil
0
 
aconradCommented:
If your script is on server A and uses a PHPSESSID of a page from server B,
the script from server A cannot read whats inside the session data of "PHPSESSID" from server B.

AJAX doesnt require you to send session id if the page you're calling with ajax is in the same path
as the page from where the ajax is runned (session cookie stays with ajax requests)
(see attached example)


php >= 5.1.3 has CURLINFO_HEADER_OUT




<?php
session_start();
 
if (isset($_GET['ajax'])) 
{
	echo 'Session-name: ['.$_SESSION['name'].']';
	die();
}
 
$_SESSION['name']='somethignhere';
 
?>
 
 
<a href="#" onclick="doajax();">test</a>
 
 
 
<script>
 
function doajax() {
	ajax_request('testajax.php?ajax=1','GET','','checkresponse');
}
 
function checkresponse()
{
  var cucu;
  var iserr = false;
  if (xmlhttp.readyState==4)
  {
    if (xmlhttp.status==200)
    {
      var resp = xmlhttp.responseText;
	  alert(resp);
 
    }
    else
    {
      alert("Problem retrieving data:" + xmlhttp.statusText)
    }
  }
  else
  {
    
  }
}
 
 
 
 
/**
* XML HTTP Request. Works with in cinjuction with the specified myfunc function which checks if the request was succesfull
*
* @param string $url
* @param POST-or-GET $method
* @param urlencoded-string $data
* @param string $myfunc
*/
function ajax_request(url,method,data,myfunc)
{
 
  if (window.XMLHttpRequest)
  {
    xmlhttp=new XMLHttpRequest()
    if (method=="GET")
    {
      xmlhttp.onreadystatechange=eval(myfunc)
      xmlhttp.open("GET",url,true)
      xmlhttp.send(null)
    }
    if (method=="POST")
    {
      xmlhttp.onreadystatechange=eval(myfunc)
      xmlhttp.open("POST", url, true);
      xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xmlhttp.send(data)
    }
  }
  // code for IE
  else if (window.ActiveXObject)
  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    if (xmlhttp)
    {
      if (method=="GET")
      {
        xmlhttp.onreadystatechange=eval(myfunc)
        xmlhttp.open("GET",url,true)
        xmlhttp.send()
      }
      if (method=="POST")
      {
        xmlhttp.onreadystatechange=eval(myfunc)
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlhttp.send(data)
      }
    }
  }
}
 
 
</script>

Open in new window

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now