Php curl saving session

I am creating an application that deletes data from the site, formats it as needed, and displays it to the user. Now the site does not allow cross-site script requests, so I use PHP curl to retrieve the page.

  • In the browser, the site gives you a cookie on your first visit, asking you to log in, and in subsequent requests you will receive the actual page requested.

  • With PHP curl, the site will just give me a page asking me to log in. And, I suppose, give my PHP server a cookie.

How can I save this cookie and present it on subsequent requests?

+4
source share
3 answers

use multiple setopts to set a cookie.

Example:

$ch=curl_init(); curl_setopt($ch, CURLOPT_COOKIEFILE, "c:/cookies/cookie.txt"); curl_setopt($ch, CURLOPT_COOKIEJAR, "-"); 
+5
source

I changed the nabab code, tried it, and it worked perfectly as I wanted:

  $loginData = array('username'=>'myuser', 'password'=>'mypassword'); $postData = array('url'=>'http://stackoverflow.com'); $loginURL = "http://stackoverflow.com/login.php"; $addURL = "http://stackoverflow.com/addUrl.php"; $curl_options = array( CURLOPT_RETURNTRANSFER => true, /* return web page */ CURLOPT_HEADER => false, /* don't return headers */ CURLOPT_FOLLOWLOCATION => true, /* follow redirects */ CURLOPT_ENCODING => "", /* handle all encodings */ CURLOPT_AUTOREFERER => true, /* set referer on redirect */ CURLOPT_CONNECTTIMEOUT => 120, /* timeout on connect */ CURLOPT_TIMEOUT => 120, /* timeout on response */ CURLOPT_MAXREDIRS => 10, /* stop after 10 redirects */ CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0 ); $cookie = "cookie.txt"; if ( $ch = curl_init() ) { curl_setopt_array($ch,$curl_options); if ( $cookie ) { curl_setopt($ch,CURLOPT_COOKIEJAR,$cookie); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_URL, $loginURL); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($loginData) ); $r = curl_exec($ch); curl_setopt($ch, CURLOPT_URL, $addURL); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData) ); $r = curl_exec($ch); } curl_close($ch); } 
+3
source

You must use a cookie. This is how I do it (I am returning an array with html content and encoding, which may be useful for cleaning):

 $curl_options = array( CURLOPT_RETURNTRANSFER => true, /* return web page */ CURLOPT_HEADER => false, /* don't return headers */ CURLOPT_FOLLOWLOCATION => true, /* follow redirects */ CURLOPT_ENCODING => "", /* handle all encodings */ CURLOPT_AUTOREFERER => true, /* set referer on redirect */ CURLOPT_CONNECTTIMEOUT => 120, /* timeout on connect */ CURLOPT_TIMEOUT => 120, /* timeout on response */ CURLOPT_MAXREDIRS => 10, /* stop after 10 redirects */ CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0 ); if ( $ch = curl_init($url) ) { curl_setopt_array($ch,self::$curl_options); if ( $cookie ) curl_setopt($ch,CURLOPT_COOKIEJAR,$cookie); $r = curl_exec($ch); curl_close($ch); } } 
+1
source

Source: https://habr.com/ru/post/1395355/


All Articles