Php cookies to json

micsoftvn / extract-cookies.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

function extractCookies ( $ string )
$ cookies = array ();
$ lines = explode(«\n», $ string );
// iterate over lines
foreach ( $ lines as $ line )
// we only care for valid cookie def lines
if (isset( $ line [ 0 ]) && substr_count( $ line , «\t») == 6 )
// get tokens in an array
$ tokens = explode(«\t», $ line );
// trim the tokens
$ tokens = array_map( ‘trim’ , $ tokens );
$ cookie = array ();
// Extract the data
$ cookie [ ‘domain’ ] = $ tokens [ 0 ];
$ cookie [ ‘flag’ ] = ( bool ) $ tokens [ 1 ];
$ cookie [ ‘path’ ] = $ tokens [ 2 ];
$ cookie [ ‘secure’ ] = ( bool ) $ tokens [ 3 ];
// Convert date to a readable format
$ cookie [ ‘expiration’ ] = date( ‘Y-m-d h:i:s’ , $ tokens [ 4 ]);
$ cookie [ ‘name’ ] = $ tokens [ 5 ];
$ cookie [ ‘value’ ] = $ tokens [ 6 ];
// Record the cookie.
$ cookies [] = $ cookie ;
>
>
return $ cookies ;
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Источник

dvlden / extract-cookies.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

function extractCookies ( $ string )
$ cookies = array ();
$ lines = explode(«\n», $ string );
// iterate over lines
foreach ( $ lines as $ line )
// we only care for valid cookie def lines
if (isset( $ line [ 0 ]) && substr_count( $ line , «\t») == 6 )
// get tokens in an array
$ tokens = explode(«\t», $ line );
// trim the tokens
$ tokens = array_map( ‘trim’ , $ tokens );
$ cookie = array ();
// Extract the data
$ cookie [ ‘domain’ ] = $ tokens [ 0 ];
$ cookie [ ‘flag’ ] = ( bool ) $ tokens [ 1 ];
$ cookie [ ‘path’ ] = $ tokens [ 2 ];
$ cookie [ ‘secure’ ] = ( bool ) $ tokens [ 3 ];
// Convert date to a readable format
$ cookie [ ‘expiration’ ] = date( ‘Y-m-d h:i:s’ , $ tokens [ 4 ]);
$ cookie [ ‘name’ ] = $ tokens [ 5 ];
$ cookie [ ‘value’ ] = $ tokens [ 6 ];
// Record the cookie.
$ cookies [] = $ cookie ;
>
>
return $ cookies ;
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Источник

Имеется сайт с определенными данными, который в личном кабинете пользователя выводятся в модальном окне (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 php cookies data showing json data

In this case, you need remove escaped quotes: See stripslashes Solution 1: you need to add the second parameter of json_encode as (some constants need PHP 5.3) also, you’ll need since it seems is on Solution 2: You’re probably a victim of magic quotes. Last line should simply be: EDIT: But this line does not make much sense, it should not be there at all. should be used to display values in a human-readable form and — without a second argument explicitly set to — its return value does not make much sense.

Compressing the data doesn’t seem like such a great idea. Rather, I’d keep it in a database and only store the database entry’s ID in a cookie. That would also prevent people from tampering with the data, albeit tampering with the ID will still be possible. Using sessions would be better and eliminate this.

However, if you insist on storing the data in a cookie, you can compress the data using either gzcompress() , gzdeflate() or gzencode() . These all offer compression. gzdeflate() would be the best choice for your problem, seeing that it is most space-efficient.

$compressedJSON = gzdeflate($json, 9); setcookie('json', $compressedJSON); 
$compressedJSON = $_COOKIE['json']; $json = gzinflate($compressedJSON); 

Keep in mind that even if the compression will be enough for your data to stay within the 4K limit, you might eventually exceed that, should the amount of JSON data you need stored grow.

I still suggest you use a database instead.

If your information is that large, you may want to look into using local storage instead. Not all browsers support local storage, but all modern ones do. If your cookie is too large, you run the risk of getting 431 http error.

So you don’t have size issues, and don’t have to pass a large cookie with every request, you should just store a unique ID in the cookie. Then you can retrieve the large data object from memcache, mysql, or any other server side storage using the unique ID. No sessions required.

$sJSON = json_encode($sSomeJSONData); setcookie('json', $sJSON); 
$sJSON = json_decode($_COOKIE['json']); 

Go with Kristian’s answer for using gzip or a database it makes the most sense. BUT if you can’t use a database you could build the session manually.

All a session is, technically, is a text file stored outside the web-tree containing data. You could duplicate that process using something like uniqid() to generate a «session name».

Create a text file, in a given directory, using that «session name» as the file name and store the «session name» in your cookie.

Then simply use serialize() , unserialize() and file_put_contents() , file_get_contents() to transfer your data between your program and your text file, using the data in the cookie to find the text file.

It would need some sanity checks and hijacking prevention but the principle is sound.

Storing PHP arrays in cookies, To store the array values in cookie, first you need to convert them to string, so here is some options. Storing cookies as JSON.

In this case, you need remove escaped quotes:

$cookie_exampleData = stripslashes($_COOKIE['exmaple_data']); 

PHP parse json array with cookies and set all cookies from it, You need json_decode() . $thecookies = json_decode($mysqlCookies); foreach($thecookies as $name => $value) < setcookie($name, $value,

you need to add the second parameter of json_encode as (some constants need PHP 5.3)

json_encode($data, JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); 

also, you’ll need json_decode(stripslashes($json)) since it seems magic_quotes_gpc is on

You’re probably a victim of magic quotes.
Make sure they’re turned off.

Displaying JSON data with PHP, Update. $json_string = file_get_contents(«http://api.wunderground.com/api/7ec5f6510a4656df/geolookup/forecast/q/40121.json»); $parsed_json

Last line should simply be:

setcookie('desire', json_encode($desire), time() + 604800); 

EDIT: But this line

 $desire = json_decode(print_r($desire)) 

does not make much sense, it should not be there at all. print_r should be used to display values in a human-readable form and — without a second argument explicitly set to true — its return value does not make much sense.

EDIT #2: Complete cleaned up solution

'; // Unsetting element with index 0. // Beware! 0 may not always be the first available index. // If removing of the first element is desired, regardless its index, array_shift($desire) should be used instead. unset($desire[0]); // Value of $desire after unset(). print_r($desire); echo '
'; // Save the new $desire value in the cooke. setcookie('desire', json_encode($desire), time() + 604800); ?>

Storing a 3kb json in cookies, as a file on server or in the database, This is why sessions exist in all modern Web frameworks. You shouldn’t store «data» in cookies — just a session key. Keep the data on the server

Источник

Читайте также:  Python language server install
Оцените статью