使被调用的url处理客户端cookie而不是调用者cookie


Make the called url deal with client cookie not caller cookie

我正在制作一个处理API的应用程序

所以我试图调用API使用cURL和问题是,api将处理服务器cookie做这个curl调用而不是客户端cookie谁使用应用程序…

例如:客户端已经登录到api,但是当我检查客户端是否通过curl调用登录时,API响应你没有经过认证

那么我如何使API处理客户端cookie或将客户端的cookie传递给API呢?

您需要使用一个cookie文件,如下所示:

        # Set the cookiefile name, which will allow us to store the cookie and present it later for all requests that require it...
        $cookiefile = tempnam("/tmp", "cookies");
        $agent     = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
        # Set the user name and password values
        $user      = $argv[1];
        $password      = $argv[2];
        # The API url, to do the login
        $url = "https://some_site.com/login.php?WID=$user&PW=$password";
        # Initialise CURL
        $ch = curl_init();
        # Set all the various options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_userAGENT, $agent);
        curl_setopt($ch, CURLOPT_POST, 0); // set POST method
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_userPWD, $user.":".$password);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        # Execute the first CURL request to perform the login...
        $results = curl_exec($ch);
        # Setup our next request...
        $job_id_number      = $argv[3];
        $url = "https://some_site.com/request.php?task=add&taskID=$job_id_number";
        # We do not have to initialise CURL again, however we do need to adjust our URL option for the second request...
        curl_setopt($ch, CURLOPT_URL, $url);
        #Remember to use the same cookiefile as above  
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        # Execute the second CURL call  to perform the action (using the cookie we retrieved from earlier)
        $results = curl_exec($ch);
        echo "$results";

您应该查看API的文档。可能文档描述了一种授权客户端的方法。

这样它将不起作用,因为cookie是在客户端(在浏览器中)设置的,而不是在服务器上。因此,当您进行cURl调用时,cookie数据不会包含在请求中。通过Javascript调用API可以工作,因为这是客户端发送的请求(带有所需的cookie)