PHP cURL不存储会话cookie ...如何解决这个问题? [英] PHP cURL isn't storing the session cookie... How to fix this?

查看:178
本文介绍了PHP cURL不存储会话cookie ...如何解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个类与我们公司的API ...
我使用curl发布数据和检索响应在json。
在代码的最后部分(在类之后),我将用户登录到服务器(它给出true),但是当我尝试再次连接curl时,他说我不记录!
我已经做了google搜索,并添加了 curl_setopt($ ch,CURLOPT_COOKIE,$ this-> Session_Cookie); 行。



有人可以给我点亮吗?



提前感谢;)

  if(!class_exists(Microdual)){
class Microdual {

// No caso de asessãonãoestar iniciada,iniciar aqui asessão


################
###############
# ###############
################ Iniciar funcoes privadas ############ ####

私人函数Extra_LoadSession($ varname,$ otherwise){
return(!empty($ _ SESSION [$ this-> Session_Prefix。$ varname]))? $ _SESSION [$ this-> Session_Prefix。 $ varname]:$ otherwise;
}
私有函数Extra_SaveSession($ varname,$ value){
$ _SESSION [$ this-> Session_Prefix。 $ varname] = $ value;
return true;
}

/ **
* $ this-> API_Comunicate()Combio comandos com os servidores Microdual(enviar e receber)
*
* @param data arrayColocar as variaveis que deseja passaràplataforma(Ver Lista completa de variaveis no Inicio)
*
* @return数组或void(false)
* /
private function API_Comunicate($ _ data){

//转换器o数组em字符串(序列化)
$ 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()
* $ bmsgctxt $ b * @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 stringcolocar aqui o nome de utilizador da sua conta em www.microdual.com
* @param password stringColocar 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数字字符串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 {
echoLogin com erro;
}


解决方案

CURLOPT_COOKIE 选项用于使用CURL发送特定的Cookie。您要查找的选项是 CURLOPT_COOKIEFILE CURLOPT_COOKIEJAR ,它们指定要保存和加载Cookie的文件。 p>

所以你必须这样做:

  curl_setopt $ ch,CURLOPT_COOKIEJAR,'cookies.txt'); 
curl_setopt($ ch,CURLOPT_COOKIEFILE,'cookies.txt');


I am making a class to comunicate with our company API... I'm using curl to post data and retrieve the response in json. In the last part of the code (after the class), i log the user into the server (it gives true), but when i try to connect again with curl, he says that i'm not logged! I've done a google search already and added the curl_setopt($ch,CURLOPT_COOKIE,$this->Session_Cookie); line.

Can anybody give me a light on this?

Thanks in advance ;)

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";
}

解决方案

The CURLOPT_COOKIE option is for sending a particular cookie using CURL. The options you are looking for are CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR, which specify a file to save and load cookie from.

So you'll have to do something like this:

curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');

这篇关于PHP cURL不存储会话cookie ...如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆