如何使用php代码启动会话

时间:2018-04-06 15:06:47

标签: php session curl session-cookies

我想向server发送请求。我正在使用此代码

$data=[..];

$header=[
"Accept-language: en-US,en;q=0.5",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection: keep-alive",
"Host: www.rvvi.cz",
"Referer: https://www.rvvi.cz/riv?s=rozsirene-vyhledavani",
"Upgrade-Insecure_Requests:1",
"User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/2010",
"Cookie: PHPSESSID=4ck9tc3vm4prgfubnjvutilgd2",
"Content-type: application/x-www-form-urlencoded"
 ];

$url = "https://www.rvvi.cz/riv";
$query = http_build_query($data);
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST,strlen($query));
curl_setopt($ch,CURLOPT_POSTFIELDS,$query);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$page=curl_exec($ch);
echo($page);

但问题在于标题中的PHPSESSID。要访问它,我必须使用我的浏览器手动转到此服务器(这可能会启动我的SESSION),复制PHPSESSID并将其粘贴到我的脚本中。但是,我想自动制作这个脚本。我需要在不使用浏览器或复制内容的情况下从我的服务器激活它们。 有什么办法可以用我的PHP代码开始这个会话吗?

1 个答案:

答案 0 :(得分:1)

$curl = curl_init( 'https://httpbin.org/post' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array( 'field1' => 'some data', 'field2' => 'some more data' ) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $curl );
curl_close( $curl );