Wednesday, May 29, 2013

How to retrieve PHP's $_SESSION from a page called by cURL

Code for the page where you do cURL:
 <?php  
 $ch = curl_init();  
 curl_setopt($ch, CURLOPT_URL,"url of the page");   // The URL to fetch
 curl_setopt($ch, CURLOPT_POST, 1);   // Do a regular HTTP POST
 curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var3=value3");   // The full data to post in a HTTP "POST" operation
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);   // Return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. 
 $curl_response = curl_exec ($ch);   // Perform a cURL session
 curl_close ($ch);    // Close a cURL session
 $response = json_decode($curl_response);   // Returns the value encoded in json
 session_start();  
 foreach($response as $key => $val) $_SESSION[$key] = $val;  
 var_dump($_SESSION);  
 ?>  


Code for the page you call via cURL:
 <?php  
 session_start();  
 /* If you are working on a page that will connect to a database then:  
  * - put all require or include statements  
  * - db connection instantiation  
  * - script to process the $_POST variables  
  * - assign $_SESSION variables  
  */  
 echo json_encode($_SESSION);   // Returns the JSON representation of a value
 ?>  

No comments:

Post a Comment