Solved

Using PHP/CURL with Cookies

Posted on 2009-05-06
11
4,055 Views
Last Modified: 2013-12-12
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
Comment
Question by:blainehilton
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 3
11 Comments
 
LVL 2

Expert Comment

by:lavinpj1
ID: 24320967
There's not a whole lot we can do without being able to see the context that this code works in.

Phil
0
 
LVL 4

Expert Comment

by:aconrad
ID: 24321565
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
 
LVL 4

Expert Comment

by:aconrad
ID: 24321594
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
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
LVL 1

Author Comment

by:blainehilton
ID: 24321618
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
 
LVL 2

Accepted Solution

by:
lavinpj1 earned 250 total points
ID: 24321695
Surely the session would be maintained anyway by the user's client passing the ID in the cookie?

Phil
0
 
LVL 1

Author Comment

by:blainehilton
ID: 24321723
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
 
LVL 1

Author Comment

by:blainehilton
ID: 24321735
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
 
LVL 2

Expert Comment

by:lavinpj1
ID: 24321757
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
 
LVL 1

Author Comment

by:blainehilton
ID: 24321797
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
 
LVL 2

Expert Comment

by:lavinpj1
ID: 24321829
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
 
LVL 4

Assisted Solution

by:aconrad
aconrad earned 250 total points
ID: 24321837
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

Business Impact of IT Communications

What are the business impacts of how well businesses communicate during an IT incident? Targeting, speed, and transparency all matter. Find out more in this infographic.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction A frequently used term in Object-Oriented design is "SOLID" which is a mnemonic acronym that covers five principles of OO design.  These principles do not stand alone; there is interplay among them.  And they are not laws, merely princ…
What is Node.js? Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question