Set cookie with curl php

Имеется сайт с определенными данными, который в личном кабинете пользователя выводятся в модальном окне (ajax). В личный кабинет соответственно попадаем после авторизации. В js скриптах я нашел путь к PHP файлу, с которого выводятся данные через ajax.

Теперь я первым делом curl прохожу авторизацию (успешно):

function send_post_get_cookie($URL='', $PostData=Array(), $cookie='') < if (strlen($URL)<=0) return false; $ua = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.13) Gecko/20101203 MRA 5.7 (build 03796) Firefox/3.6.13'; $ch = curl_init($URL); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_USERAGENT, $ua); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $PostData); if (strlen($cookie)>0) curl_setopt($ch, CURLOPT_COOKIE, $cookie); $result = curl_exec($ch); curl_close($ch); $lines = explode("\n", $result); for ($i=0, $cnt=count($lines); $i

Далее пытаюсь curl + post отправить сессию и post данные на этот самый PHP файл (например https://site.ru/js/dannye.php) но как не стараюсь — пишет что сессия устарела или-же 400 bad request.

function open($URL='', $cook='') < $ua = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.13) Gecko/20101203 MRA 5.7 (build 03796) Firefox/3.6.13'; $ch = curl_init($URL); curl_setopt($ch, CURLOPT_USERAGENT, $ua); curl_setopt($ch, CURLOPT_COOKIE, $cook); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'page'=>'1' )); $answer = curl_exec($ch); curl_close ($ch); return $answer; >

Запускаю все это дело таким образом:

$cookie = send_post_get_cookie('https://site.ru/login.php', array( 'user'=>'test@test.ru', 'password'=>'12345' )); open('https://site.ru/js/dannye.php',$cookie);

Но постоянно пишет что сессия истекла, как только не пробовал. В чем моя ошибка?

. LOGIN Request Headers: POST /login.php HTTP/1.1 Host: sitename.ru Connection: keep-alive Content-Length: 72 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 Origin: https://sitename.ru Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 OPR/70.0.3728.106 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Sec-Fetch-Site: same-origin Sec-Fetch-Mode: navigate Sec-Fetch-User: ?1 Sec-Fetch-Dest: document Referer: https://sitename.ru/login.php Accept-Encoding: gzip, deflate, br Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7 Cookie: PHPSESSID=i99n3d2s6v1oibcsdp4vpa9rs2; skin=1 . MODAL Request Headers: Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7 Connection: keep-alive Content-Length: 81 Content-Type: application/x-www-form-urlencoded Cookie: skin=1; PHPSESSID=i99n3d2s6v1oibcsdp4vpa9rs2; skin=1 Host: sitename.ru Method: POST /js/dannye.php HTTP/1.1 Origin: https://sitename.ru Referer: https://sitename.ru/main.php Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 OPR/70.0.3728.106

Источник

PHP CURL With Cookies (Simple Examples)

Welcome to a tutorial on how to do PHP CURL calls with cookies. Need to do a server-to-server call that involves cookies? Well yes, CURL is fully capable of handling that with a few small tweaks.

To do a PHP CURL call with cookies, we use CURLOPT_COOKIEJAR to specify where to save the cookie after the call ends, and CURLOPT_COOKIEFILE to specify which cookie file to send to the remote server.

  • $cookie = «COOKIE.TXT»;
  • $ch = curl_init();
  • curl_setopt($ch, CURLOPT_URL, «HTTP://SITE.COM»);
  • curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
  • curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
  • curl_exec($ch);
  • curl_close($ch);

That covers the basics, but read on for more examples!

TLDR – QUICK SLIDES

PHP CURL With Cookies

TABLE OF CONTENTS

PHP CURL COOKIES

All right, let us now get into the examples of handling cookies with PHP CURL.

1A) LOCAL SERVER CURL CALL

This is just a “slightly improved” version of the introduction snippet to output the exchange results between the local and remote servers.

1B) DUMMY REMOTE SERVER

On the dummy remote server – We simply output the received cookie and send a header to set the Test cookie to the current timestamp.

1C) WHAT WILL HAPPEN

  • On the first run –
    • The remote server will not show any cookie values since it is a new connection.
    • The remote server then responds with a set-cookie Test = NOW back to the local server.
    • The local server saves Test = NOW to the cookie.txt file.
    • The local server reads cookie.txt and sends it to the remote server.
    • The remote server now displays the timestamp of the previous visit.
    • Then sends set-cookie Test = NOW back to the local server.
    • The local server updates Test = NOW in the cookie.txt file.

    2) MANUALLY SETTING COOKIES

    • The local server will read from cookie.txt , append keyA=valueA; keyB=valueB , and send these to the remote server.
    • The remote server will now show the cookie values of Test, keyA, keyB .
    • Take note of the response part – The remote server only states set-cookie Test = NOW . So the local server will only update Test in cookie.txt ; keyA keyB will not be saved.

    3) FLUSHING & CLEARING COOKIES

    // (C) FORCE NEW SESSION // CURLOPT_COOKIESESSION - FORCE NEW COOKIE SESSION, IGNORE LAST curl_setopt($ch, CURLOPT_COOKIESESSION, true); // CURLOPT_COOKIELIST // "ALL" ERASES ALL COOKIES IN MEMORY. // "SESS" ERASES ALL SESSION COOKIES HELD IN MEMORY. // "FLUSH" WRITES COOKIES TO CURLOPT_COOKIEJAR. // "RELOAD" RELOAD COOKIES FROM CURLOPT_COOKIEFILE. curl_setopt($ch, CURLOPT_COOKIELIST, "ALL");

    Lastly, just a quick mention – If you need to clear or empty the cookies, use the CURLOPT_COOKIESESSION or CURLOPT_COOKIELIST options to do it.

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

    INFOGRAPHIC CHEAT SHEET

    THE END

    Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    Leave a Comment Cancel Reply

    Breakthrough Javascript

    Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

    Socials

    About Me

    W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

    Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

    Источник

    PHP cURL Part 6(Cookies saving and sending)

    So far, we’ve learned the following features of PHP cURL in this series of articles.

    In this article, we’ll learn how to perform save & send cookies using PHP cURL. Sometimes websites use cookies to save user-specific information and then use those saved cookies to load resources for users. So, in this case, we can’t access website resources directly. We first need to get cookies from that site and then we’ll send those cookies in our upcoming cURL requests. Following is a very basic example for cookies.

    $cookie_jar = tempnam('/tmp','coo'); // getting cookies $curl = curl_init('http://httpbin.org/cookies/set?site=coderanks'); curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl); //sending cookies $curl = curl_init('http://httpbin.org/cookies'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); curl_close($curl); echo '
    ',$response; 

    Response:

    Explanation:

    In the above script, we've performed the following three steps.

    1. Creating a temporary file to save cookies
    2. Getting cookies and saving in the file(created in the first step)
    3. Using cookies(saved in the second step) for a new curl request.

    Let's discuss each step in details with code.

    Creating a temporary file to save cookies

    We need to save cookies somewhere for future use, so for this, we're going to create a temporary file. This step can be with the following piece of code.

    $cookie_jar = tempnam('/tmp','coo');

    tempnam is a built-in PHP function that is used to create a unique empty file. Its first parameter is file path(default is System's directory) and the second parameter is the prefix of the file. So it will create a file in C:\Windows\Temp with a unique name prefixed with coo and will return its full path. Here is an example file created by tempname.

    Getting cookies and saving in the file

    Temporary file created in the first step will be empty. Now, in this step, we'll get cookies from URL and will save them in that file. Following piece of code will help us to do that.

    // getting cookies $curl = curl_init('http://httpbin.org/cookies/set?site=coderanks'); curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl); curl_close($curl);

    Following options are already discussed in previous parts. Here is a simple detail for both options.

    1. CURLOPT_RETURNTRANSFER: used to direct cURL to not display response(default) but return after execution.
    2. CURLOPT_SSL_VERIFYPEER: used to enable or disable SSL.

    CURLOPT_COOKIEJAR

    This option is used to set the cookies file, which will be used by the cURL to save automatically parsed cookies.

    So after executing the above script, there will be some text in that file, similar to below one.

    # Netscape HTTP Cookie File # https://curl.haxx.se/docs/http-cookies.html # This file was generated by libcurl! Edit at your own risk. httpbin.org FALSE / FALSE 0 site coderanks 

    Using cookies for a curl request

    Now we've cookies saved in a file, we can use that file to send cookies for any cURL request. here is the script for sending cookies.

    //sending cookies $curl = curl_init('http://httpbin.org/cookies'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); curl_close($curl); echo '
    ',$response; 

    CURLOPT_COOKIEFILE is used to set the cookies file to attach cookies in the cURL request. Here is the response to this request.

    Note: Normal sites don't return cookies when you send them. We've used Httpbin.org for the testing purpose of this article to show you that how actually cookies saved and passed. In the real-life example, you'll pass cookies and get the site resources after executing, not cookies.

    That's all for this part of the article.

    Источник

    Читайте также:  Можно ли удалять java с компьютера
Оцените статью