PHP cURL没有存储会话cookie ...如何解决这个问题?

时间:2010-06-24 14:25:10

标签: php cookies post curl session

我正在上课与我们公司的API沟通...... 我正在使用curl发布数据并在json中检索响应。 在代码的最后部分(课后),我将用户登录到服务器(它给出了真实),但是当我尝试再次使用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 个答案:

答案 0 :(得分:5)

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

所以你必须做这样的事情:

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