2011年10月27日 星期四

【程式】PHP : Curl with Session

今天同事問了一個問題
A.php 用 Curl 去抓 B.php 。
然後 B.php 寫在 Session 的東西,
為什麼 A.php 抓不到 (當然 B.php 也抓不到 A.php 的值),
這是因為 curl 其實產生了另一個 session,
所以就算存了也抓不到。
當然也有解決的方法,就是使用 session_id()
程式如下:
A.php
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function doHttpRequest($url, $args='') {
$ch = curl_init();
//Post Data
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'sid='.session_id());

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

session_start();
$_SESSION['aa']='[A.php]';
session_write_close();

$url = 'http://cw.dev.com/B.php';
echo doHttpRequest($url);

session_id(session_id());
session_start();
var_dump($_SESSION);
B.php
?
1
2
3
4
session_id($_POST['sid']);
session_start();
$_SESSION['bb']='[B.php]';
var_dump($_SESSION);
執行結果:
array 'aa' => string '[A.php]' (length=7) 'bb' => string '[B.php]' (length=7)
array 'aa' => string '[A.php]' (length=7) 'bb' => string '[B.php]' (length=7)

以上,記錄一下…

reference : http://ching119.pixnet.net/blog/post/59676045-%E3%80%90%E7%A8%8B%E5%BC%8F%E3%80%91php-%3A-curl-with-session

沒有留言:

wibiya widget