PHP cURL 没有存储会话 cookie...如何解决这个问题?
Posted
技术标签:
【中文标题】PHP cURL 没有存储会话 cookie...如何解决这个问题?【英文标题】:PHP cURL isn't storing the session cookie... How to fix this? 【发布时间】:2011-03-07 20:28:17 【问题描述】:我正在创建一个类来与我们公司的 API 进行通信... 我正在使用 curl 发布数据并检索 json 中的响应。 在代码的最后一部分(在课程之后),我将用户登录到服务器(它给出了 true),但是当我尝试使用 curl 再次连接时,他说我没有登录! 我已经进行了谷歌搜索并添加了 curl_setopt($ch,CURLOPT_COOKIE,$this->Session_Cookie); 行。
谁能告诉我这个?
提前致谢;)
if(!class_exists("Microdual"))
class Microdual
// No caso de a sessão não estar iniciada, iniciar aqui a sessão
################
################
################
################ Iniciar funcoes privadas ################
private function Extra_LoadSession($varname,$otherwise)
return (!empty($_SESSION[$this->Session_Prefix . $varname])) ? $_SESSION[$this->Session_Prefix . $varname] : $otherwise;
private function Extra_SaveSession($varname,$value)
$_SESSION[$this->Session_Prefix . $varname] = $value;
return true;
/**
* $this->API_Comunicate() "Comunicar comandos com os servidores Microdual (enviar e receber)"
*
* @param data array "Colocar as variaveis que deseja passar à plataforma (Ver Lista completa de variaveis no Inicio)"
*
* @return array or void (false)
*/
private function API_Comunicate($_data)
// Converter o array em string (serialize)
$data = array();
while(list($n,$v) = each($_data))
$data[] = "$n=$v";
$data = implode('&', $data);
// format --> test1=a&test2=b etc.
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$this->Geral_URLAPI);
curl_setopt($ch,CURLOPT_POST,count($_data));
curl_setopt($ch,CURLOPT_COOKIE,$this->Session_Cookie);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$content = curl_exec($ch);
curl_close($ch);
if(($content !== false) && (!empty($content)))
return json_decode($content, true);
else
return false;
################
################
################
################ Iniciar funcoes Públicas ################
public function Debug_VarDump($varname)
$string = "<pre>";
$string .= var_dump($varname);
$string .= "</pre>";
return $string;
exit;
/**
* $this->IsLogged() "Verificar se está autenticado no servidor (primeiro localmente, e depois liga ao servidor)"
*
* @return void
*/
public function IsLogged()
if($logged) return true;
$logged = $this->Extra_LoadSession("Login_Logged",false);
if($logged)
return true;
else
// Conectar ao servidor
$dados = $this->API_Comunicate(array());
if($dados!==false)
if(!empty($dados['auth']['logged']))
return $dados['auth']['logged'];
else
return false;
else
return false;
/**
* $this->Login() "Executar o Login nos servidores Microdual"
*
* @param username string "Colocar aqui o nome de utilizador da sua conta em www.microdual.com"
* @param password string "Colocar aqui a password da sua conta em www.microdual.com"
*
* @return void
*/
public function Login($username,$password)
if(empty($username) || empty($password)) return false;
if($this->IsLogged()) return true;
$receive = $this->API_Comunicate(array(
"type" => "auth",
"action" => "add",
"auth_username" => $username,
"auth_password" => $password
));
if($receive["auth"]["status"] && $receive["auth"]["logged"])
$this->Extra_SaveSession("Login_Logged",true);
$this->Login_Logged = true;
return true;
else
return false;
/**
* $this->SMS_Send() "Executar o Login nos servidores Microdual"
*
* @param number string "Colocar aqui o numero do telemovel para enviar sms"
*
* @return void
*/
public function SMS_Send($number,$msg)
// Guardar apenas os numeros
$number = preg_replace("/[^0-9]/", "", $number);
$msg = trim($msg);
$receive = $this->API_Comunicate(array(
"type" => "sms",
"action" => "add",
"sms_to" => $number,
"sms_msg" => $msg
));
return $receive;
################
################
################
################ Iniciar variaveis da class ################
private $Session_Prefix;
private $Session_Cookie;
private $Geral_URLAPI;
private $Login_Logged;
################
################
################
################ Iniciar dados da class ################
function __construct()
$this->Session_Prefix = "MYCMSAPI_";
$this->Session_Cookie = "phpSESSID=".$_COOKIE['PHPSESSID']."; path=/";
$this->Geral_URLAPI = "http://www.MYCOMPANY.com/MyapiURL";
$this->Login_Logged = $this->Extra_LoadSession("Login_Logged",false);
$Microdual = new Microdual();
if($Microdual->Login("usernamehere","password"))
$Microdual->Debug_VarDump($Microdual->SMS_Send("93211254","Teste Test Hi :)"));
else
echo "Login com erro";
【问题讨论】:
【参考方案1】:CURLOPT_COOKIE
选项用于使用 CURL 发送特定 cookie。您正在寻找的选项是 CURLOPT_COOKIEFILE
和 CURLOPT_COOKIEJAR
,它们指定了保存和加载 cookie 的文件。
所以你必须这样做:
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
【讨论】:
它没有用!该文件是否放在脚本的同一文件夹中? 怎么不工作?选项值只是您要存储 cookie 的路径。每当您想使用这些 cookie 时,您只需要使用这样的文件即可。如果它不存在,PHP 将创建它。 在这里询问之前我已经尝试过 CURLOPT_COOKIEJAR 和 CURLOPT_COOKIEFILE。但现在它起作用了,CURLOPT_COOKIESESSION 是真的,它在每个连接中启动一个新的 cookie 会话。谢谢;)以上是关于PHP cURL 没有存储会话 cookie...如何解决这个问题?的主要内容,如果未能解决你的问题,请参考以下文章