0

curl 経由でログインし、今後の呼び出しのために Cookie とセッション情報を維持したいと考えています。同じディレクトリに Cookie テキスト ファイルを作成し、 CURLOPT_COOKIEJAR 、 CURLOPT_COOKIEFILE を使用して CUL で Cookie を維持します。ログインAPIを呼び出そうとすると、古いCookieが取得され、以前のユーザー情報が表示されます。さまざまなユーザー Cookie を維持し、通常のブラウザー ハンドルのようにセッションを維持する必要があります。どうやってするか。誰もがそれを行うためのアイデアを提供します.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_HEADER,0); // TRUE to include the header in the output.    
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // it will follow with server redirects  
curl_setopt($ch,CURLOPT_AUTOREFERER,1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//ssl certificate verifyer
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);  //ssl certificate host

// Set the location of and send the cookies
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/cookies.txt");

    curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookies.txt");

curl_setopt( $ch, CURLOPT_COOKIESESSION, true );    

$result = curl_exec($ch); //execute curl and store data in result
4

1 に答える 1

0

変更できます

dirname(__FILE__) . "/cookies.txt"

のようなものに

dirname(__FILE__) . '/user_cookies/' . $username . '.txt'

無効な文字が含まれないように、その行のユーザー名をサニタイズする必要があります。

また、/user_cookies/ パーミッションを 777 などに設定します。

これにより、ユーザーが Cookie を持っているかどうかを確認する必要がなくなります。そうでない場合は、ファイルが作成されます。ユーザーがそれらを持っている場合、既存のファイル コンテンツが使用されます。

Cookie をデータベースに保存することもできますが、それはより複雑です。

于 2012-11-20T17:42:28.947 に答える