Christopher
Christopher

Reputation: 13147

send session var with php cUrl

Am trying to send data between scripts within my application.

Problem is session id is not responding.

Script 1 is...

 <?php 
      session_start();

      $_SESSION['id'] = 1;

      $data = "data to be sent to script";

      $ch = curl_init("http:.../myscript.php");

      $nvp = "&data=$data";

      curl_setopt($ch, CURLOPT_POSTFIELDS, $nvp);

      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

      echo curl_exec($ch);

      ?>

myScript.php is...

      <?php

      session_start();          

      $id = $_SESSION['id'];

      $data = $_POST['data'];

      $result = function idData($id, $data); // returns matching results.


      echo "Session Id = $id <br />";


      echo "Id result = $result <br />";

      ?>

However myScript.php is not able to access the session data as per normal.

Is there a work around for this? What could the possible cause be?

Thanks

Upvotes: 5

Views: 34066

Answers (3)

Imam Mubin
Imam Mubin

Reputation: 294

You miss one option parameter for using post. Please add this one, it should work: curl_setopt($ch, CURLOPT_POST, true);

Upvotes: -2

drew010
drew010

Reputation: 69937

In script 1 you could use CURLOPT_COOKIE if you keep track of the session ID from the response yourself.

I don't think you need or want session_start in script 1 if it is going to be making multiple requests to myscript.php that creates a session.

Use this in script 1:

curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt'); // set cookie file to given file
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt'); // set same file as cookie jar

And then make your request as normal. Any cookies set by myscript.php will be saved to the cookie jar file when the request completes, the cookiefile will be checked for any cookies to be sent prior to sending the request.

You could manually track the php session cookie from the curl request and use CURLOPT_COOKIE as well.

Upvotes: 6

lsl
lsl

Reputation: 4419

I believe you're looking for CURLOPT_COOKIE

curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

Upvotes: 9

Related Questions