Reading a cookie that contains an array - php

I have a cookie set in the format:
{"necessary":true,"functional":true,"advertising":false,"performance":true,"lastConsentReset":null}
or as it is in the dev console in Chrome:
%7B%22necessary%22%3Atrue%2C%22functional%22%3Atrue%2C%22advertising%22%3Afalse%2C%22performance%22%3Atrue%2C%22lastConsentReset%22%3Anull%7D
I would like to use PHP to read this cookie and return the value of the key "advertising".
I have looked around to try and find a solution but they all just show how to read a cookie with just one piece of data like this:
return $_COOKIE[ 'somecookie' ];
I imagine I need some sort of loop to search the array I just don't know how to do it.
Any help greatly appreciated!
thanks.

Its JSON and URL encoded, just reverse it:
echo json_decode(urldecode($_COOKIE['somecookie']))->advertising; // nothing as its false

Related

Azure Functions with PHP

I'm trying out Azure Functions using PHP.
Getting the request information is not working for me.
I've not been able to find any documentation at all with the information of how to use Azure Functions with PHP code.
According to the only couple of examples, it seems that in order to retrieve the input information you need to first get the content of the req variable (or whatever name you assign in the function configuration).
That has the path of the file containing the request information (in theory).
$input_path = getenv('req');
So far, if I check the content of it, I get something like this:
D:\local\Temp\Functions\Binding\e2b6e195-02f7-481b-a279-eef6f82bc7b4\req
If I check if the file exists it says true, but the file size is 0.
Do anyone knows what to do here? Anyone with an example? Does anyone know where the documentation is?
Thanks
Ok, unfortunately there's pretty limited documentation out there for php as you have discovered.
At present, looking at the code might be the best doc. Here is the InitializeHttpRequestEnvironmentVariables function that adds request metadata to the environment for the script languages (node, powershell, php, python).
Important environment variables are:
REQ_ORIGINAL_URL
REQ_METHOD
REQ_QUERY
REQ_QUERY_<queryname>
REQ_HEADERS_<headername>
REQ_PARAMS_<paramname>
I'm assuming you've made a GET request, in which case there is no content (req is an empty file), but you will see that these other environment variables contain request data. If you were to make a POST request with a body then req would have data.
here is a full example parsing a GET request in PHP with an Azure Function :)
https://www.lieben.nu/liebensraum/2017/08/parsing-a-get-request-in-php-with-an-azure-function/
snippet from source:
<?php
//retrieve original GET string
$getReqString = getenv('REQ_QUERY');
//remove the ? for the parse_str function
$getReqString = substr($getReqString,1,strlen($getReqString));
//convert the GET string to an array
$parsedRequest = array();
parse_str($getReqString,$parsedRequest);
//show contents of the new array
print_r($parsedRequest);
//show the value of a GET variable
echo $parsedRequest["code"];
?>

CodeIgniter Session syntax

Can someone quickly help me out with CodeIgniter's syntax. I need to access an array I stored in the session's userdata and I cant figure out the proper syntax.
<?php echo $this->session->userdata['user_session']['first_name']; ?>
gives me this error:
Fatal error: Cannot use object of type stdClass as array
All of the answers given in this Question dont work:
Access array variable in session (CodeIgniter)
This is how you get session data:
echo $this->session->userdata('first_name');
Been a while since I've worked in Codeigniter, but if I can remember correctly, when you store an array like you've stated, you'd call it like this:
$this->session->userdata("user_session")['first_name'];
Let me know if that works?
Or you can store that data to a variable, and call the array that way. Like such:
$data = array("bar" => "the_value");
$this->session->set_userdata("foo", $data);
$foo = $this->session->userdata("foo");
echo $foo["bar"]; //Outputs the_value
Let me know if that helped.
However, just to let you know.. Normally, storing the session data goes as follows:
$this->session->set_userdata("first_name", "value");
Really no need to go and set your own array inside of userdata, because that's generally what the userdata array is for.
I found the proper syntax. Well, at least one way to go about it. #Matt GrubB was the closest and put me on the right track.
$temp_session = $this->session->userdata('user_session');
echo $temp_session->first_name;
Since userdata is an object full of info created when I query my database, the easiest way to access the data is to take it and put it in another temporary array. You then have to stab it. I kept stumbling by trying to do $this->temp_session->first_name or something of the like.

PHP 'QUERY_STRING' not returning anything

I'm using the following in my php code:
$file="query.txt";
$f=fopen($file,'a');
fwrite($f,"Query String:".$_SERVER['QUERY_STRING']."\n");
fclose($f);
It never returns anything. I'm simply trying to record the queried url when someone visits (i.e. http://example.com/index.php?q=string. Other $_SERVER fields seem to work just fine, it only seems to be the query string that doesn't work. Maybe there's something I need to setup in my .htaccess?
I'm hoping someone has an answer to how to get this to information to show.
This solved the problem:
$_SERVER['REDIRECT_QUERY_STRING']
solution from https://stackoverflow.com/a/11618256/1125006

Get "score" from JSON array

I got a response from the reddit API where the statistics from a link is made into a array. However, I can't figure out how to get the score-value from the response.
My current code:
http://pastebin.com/mH7udEKD
The response I get:
http://pastebin.com/N5smhxry
Should give you the score value:
$json_output['data']['children'][0]['data']['score']
it seems the only way to reach it is $json_result["data"]["children"][0]["data"]["score"].. are you sure this is the way to pull what you want from the API?
Just look at the response. Looks like this should do it:
$json_output['data']['children'][0]['data']['score']

Pull value from PHP Cookie Array

I am doing some modifications for a site built primarily in ASP. However, the mods will be in PHP as the site is being moved over to that language.
When the user signs in, they are assigned cookies that look lkie so:
("mycook")("id")=23
("mycook")("pref")="HTML"
("mycook")("job")="janitor"
Now in asp, these can be referenced as:
request.cookies("mycook")("pref")
which would respond as "HTML"
Is there a similar syntax is PHP that anyone is aware of?
This doesn't seem to work:
echo $_COOKIE['mycook']['pref'];
echo $_COOKIE["mycook"]["pref"];
I saw a solution that uses a For Each -> , and I can see how that would work. But it just seems a bit of overkill (to loop through all the values just to print the one I am looking for) and I was wondering if anyone had any ideas?
Thanks in advance for your help.
In your example, your cookies will be stored as the following string in the "mycook" cookie:
["mycook"]=>string(27) "pref=HTML&job=janitor&id=23"
So to access you will need echo $_COOKIE['mycook'] then translate the url encoded string into something more useful.
parse_str($_COOKIE['mycook'], $mycook);
echo $mycook['pref'];
If you don't need to have second level cookies, just assigning as:
Response.Cookies("id")=23
Response.Cookies("pref")="HTML"
Response.Cookies("job")="janitor"
Will allow you to access the cookies in PHP with just:
echo $_COOKIE['pref'];
here is a few link that will help:
http://www.tizag.com/phpT/phpcookies.php
http://php.net/manual/en/function.setcookie.php

Categories