Thursday, October 22, 2009

file_get_contentsのCookie取得のサンプル

$url = "http://hoge.com/";
$data = array();

$data['TITLE'] = "hhh";
$data['NAME'] = "aaa";

$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data),

));
$content = file_get_contents($url, false, stream_context_create($options));


$nLines = count( $http_response_header ); // after file_get_contents
$match = "/Set-Cookie: JSESSIONID=(.+):/";
$cookie = "";
$matches = array();
for ( $i = 0; $i < $nLines; $i++ )
{
$line = $http_response_header[$i];
if (preg_match( $match,$line,$matches))
{
$cookie = $matches[1];
break;
}
}
echo $cookie;

curl Postデータ

$data = array(
'MAX' =>'20',
'NAME' => '田中',
'ADDRESS' => 'test@test.com',
);

$post_words=array();
foreach( $data as $key => $value ){
$post_words[] = $key. "=" .$value;
}
$post_word = implode("&", $post_words);

curl_setopt($ch,CURLOPT_POSTFIELDS,$post_word);

Wednesday, October 21, 2009

curl とCookie

$useragent = 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$cookie_save_file = 'cookie_data';

$url = 'http://example.com/test.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt ($ch,CURLOPT_POST,1);
$post_word = "input=了承";
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_word);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_save_file);// 読み込まれるファイル
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_save_file);// 内容が保存される。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$content = curl_exec($ch);
curl_close($ch);

echo $content;