使用 php cUrl 发送会话变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7508438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:50:06  来源:igfitidea点击:

send session var with php cUrl

phpsessionscriptingcurl

提问by Christopher

Am trying to send data between scripts within my application.

我正在尝试在我的应用程序中的脚本之间发送数据。

Problem is session id is not responding.

问题是会话 ID 没有响应。

Script 1 is...

脚本 1 是...

 <?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...

myScript.php 是...

      <?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.

但是 myScript.php 无法正常访问会话数据。

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

有解决办法吗?可能的原因是什么?

Thanks

谢谢

回答by drew010

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

在脚本 1 中,CURLOPT_COOKIE如果您自己跟踪响应中的会话 ID,则可以使用。

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.

如果要向 myscript.php 发出多个请求以创建会话,我认为您不需要或不希望脚本 1 中的 session_start 。

Use this in script 1:

在脚本 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.

然后像往常一样提出您的要求。当请求完成时,由 myscript.php 设置的任何 cookie 都将保存到 cookie jar 文件中,在发送请求之前,将检查 cookiefile 是否有要发送的 cookie。

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

您可以从 curl 请求手动跟踪 php 会话 cookie 并使用CURLOPT_COOKIE

回答by Louis

I believe you're looking for CURLOPT_COOKIE

我相信您正在寻找CURLOPT_COOKIE

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

回答by Mostafa -T

回答by Mubin

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

您错过了使用 post 的一个选项参数。请添加这个,它应该可以工作: curl_setopt($ch, CURLOPT_POST, true);