In PHP how to get time/date when cookie was set/created? - php

How to get the cookie's birthday/time in PHP?
The cookie itself contains other data, so was wondering if there is a way to get the exact date and h:m:s when it was created without having to create a second cookie just to hold that information?
I searched but too much interference with the other keywords: set, time, cookie, date that's showing answers, but not to this question.

What you can do is to create an array, serialize that array to a string and store the serialized string inside the cookie:
$mycookieArray = array('cookiedata'=>'some data','creationTime'=>new DateTime());
$mycookiedata = serialize($mycookieArray);
Then, everytime you want to load the correct you have to unserialize the array from the cookiedata:
$mycookieArray = unserialize($mycookiedata);

Related

Create session variable from mysql column parameter

I am trying to create a php session variable which should reference "language":"ENG" (and more specifically ENG) within the table column params.
Example: Originally I've been using a "userLanguage" column and created my php session variable like this:
$_SESSION['userLanguage'] = $result[0]['userLanguage'];
Since "language":"ENG" is only one part of the field's value ({"admin_style":"","admin_language":"","language":"ENG","editor":"","helpsite":"","timezone":""}), this obv. doesn't work anymore. Is there an easy way to pull ENG from language? Help would be much appreciated.
Simply run a json_decode() on the field value.
$params = json_decode($result[0]['params']);
if(isset($params->language)){
$_SESSION['userLanguage'] = $params->language;
}

Base64 decode not giving value in php

I have a post value from a form, which contains an array. This value is first serialized and then base64 encoded before it is put in a session.
Now on the page where the data is needed, when i print_r to screen, i can see the value stored in the session as
YToxOntpOjA7czo1OiIzNTAwMCI7fQ==
Which is actually 35000.
But on this page where i am supposed to retrieve the data from the session, i am able to get the value from the session and store in a variable
$screeningamountt = $_SESSION['SCREENINGAMOUNT'];
But when i try to first unserialize and base64 decode the varaible to get the data which is supposed to be 35000, I get an empty variable. Noting prints to screen.
$screeningamount = base64_decode(unserialize($screeningamountt));
I can't figure out whats happening. Any help to figuring whats going on is much appreciated.
If you serialize it first then base64 encode it you need to unencode it then unserialize.
Last in, first out.
$screeningamount = unserialize(base64_decode($screeningamountt));

How we can store the momentjs time to PHP variable?

Is it possible to save the momentjs time to PHP variable and use that variable in PHP, One way is to use ajax to send the current time on some event. So is any other best way for this ?
I would start by passing the variable to your PHP file by whatever means you find practical ($_POST, $_GET, $_COOKIE, etc). Ensure that you use a consistent format for the date
moment(yourDate).format('MM/DD/YYYY').toISOString();
Then use a date library in PHP to parse the date into a new date object you can then manipulate
$js_date = $_REQUEST['youDate'];
$date = DateTime::createFromFormat(DateTime::DATE_ATOM, $js_date);
You should now have a PHP variable containing a DateTime object called $date.

PHP: How to receive JSON array from iPad app

Disclaimer: I am fairly new to using json.
I am trying to use php to receive json data from an iPAd application. I know how to convert json to an array in php, but how do I actually receive it and store it into a variable so it can be decoded?
Here are a couple examples that I have tried based on google and stackoverflow searches.
$json_request = #file_get_contents('php://input');
$array = json_decode($json_request);
AND ALSO
$array = json_decode($_POST['data'], true);
Any suggestions?
You have the basic idea already.
you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.
if(isset($_POST['data'])){
$array = json_decode(stripslashes($_POST['data']),true);
//$array now holds an associative array
}//Data Exists
It also would not be a bad idea before you start working with the array to test that the call to json_decode() was successful by ensuring that $array isn't null before use.
If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.
if($array){ // Or (!is_null($array)) Or (is_array($array)) could be used
//Process individual information here
//Without trust
if(isset($array['Firstname'])){
$CustomerId = $array['Firstname'];
}//Firstname exists
}//$array is valid
I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.
In the above example $_POST['data'] indicates that what ever called the PHP script did so passing the JSON string using the post method in a variable identified as data.
You could check more generically to allow flexibility in the sending method by using the $_REQUEST variable, or if you know it is coming as via the get method you can check $_GET. $_REQUEST holds all incoming parameters from both get and post.
If you don't know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in $_REQUEST trying to decode each one and use the one that successfully decoded (if any). [Note: I'm not encouraging this]

Multiple Variables into 1 in a URL

I am looking to have a list of arguments passed across in an a URL.
$url['key1']=1;
$url['key2']=2;
$url['key3']=3;
$url['key4']=4;
$url['key5']=5;
$url['key6']=6;
$url['key7']=7;
Please Note I am trying to pass this in the URL in 1 GET variable. I know this would be better done by ?key1=1&key2=2&key3=3...etc but for reasons that are too complicated to try and explain they can't be in this format.
Any suggestions how I can convert this array into something that can be passed as 1 get var in a URL string?
Thanks in advance.
You can use json_encode() or serialize()
$myUrl = 'http://www.example.com/?myKey=' . urlencode(json_encode($url));
or
$myUrl = 'http://www.example.com/?myKey=' . urlencode(serialize($url));
Using json_encode will usually give you a shorter string, but very old PHP version might not have the json_decode function available to decode it again.
The final way would be to create your own custom encoding... it could be as simple a pipe-separated values: key1|1|key2|2|key3|3
This would give you the best option for a short URL, but is the most work.
Try http_build_query:
$url['key1']=1;
$url['key2']=2;
$url['key3']=3;
$url['key4']=4;
$url['key5']=5;
$url['key6']=6;
$url['key7']=7;
echo http_build_query($url);
//echos key1=1&key2=2&key3=3&key...
What it does is converting an array into a query string using the keys and automatically takes care of url-encoding.
EDIT:
Just read your additional requirement that it should be just one variable. So nevermind this answer.
If your problem was the proper encoding though you might want to give this another try.
Hope that helps.
The recommendation to use serialize() is fine. If space is an issue, then use a combination of bzcompress() and serialize().
However, there's a security considering that hasn't been brought up, and that's that the end user (who can see and edit this url) could manipulate the data within it. You may think it's difficult, but most of the PHP-attacking worms in the wild do this to some degree or another.
If letting the user directly manipulate any of the keys or values (or replacing it with an integer, or an object, or anything else), then you should protect your script (and your users) from this attack.
A simple solution is to simply use a shared secret. It can be anything; just so long as it's unique and truly secret (perhaps you should randomly generate it at install-time). Let's say you have in your config file something like this:
define('SECRET', 'unoqetbioqtnioqrntbioqt');
Then, you can digitally sign the serialized data created with: $s=serialize($m) using $k=sha1($s.SECRET) and make the url value $k.$s
Then, before you unserialize() do this:
$v=substr($input,0,40);
$s=substr($input,40);
if ($v != sha1($s.SECRET)) { die("invalid input"); }
$m=unserialize($s);
This way, you know that $m is the same as the original value that you serialized.
If you like, you can use the following drop-in replacements:
define('SECRET','buh9tnb1094tib014'); // make sure you pick something else
function secureserialize($o) {
$s=serialize($o);
return sha1($s.SECRET).$s;
}
function secureunserialize($i) {
$v=substr($i,0,40);$s=substr($i,40);
if ($v!=sha1($s.SECRET)){die("invalid input");}
return unserialize($s);
}
You could serialize them as key-value pairs when constructing the URL, putting the resultant serialized value in a single $_GET variable (e.g. data=sfsdfasdf98sdfasdf), then unserialize the $_GET["data"] variable. You'll need to use urlencode to make sure the resultant serialized values are URL-safe. Make sure you watch out for maximum URL lengths - 2083 characters in IE.
However, unless you really can't use key-value pairs in URLs (per your question), key1=foo&key2=bar... is definitely the way to go.
If you don't mind dropping the key names, you can use
http://example.com?url[]=1&url[]=2&url[]=3
EDIT Keeping the key names:
http://example.com?values[]=1&values[]=2&values[]=3&keys[]=1&keys[]=2&keys[]=3
Then in your PHP script:
$url = array_combine($_GET['keys'], $_GET['values']);
Could you solve your problem by saving the data as a HTML cookie? That way you don't have to modify the URL at all.
If you know the values in advance, you can set them from the server side when you send the user the page with your target link on it.
If you won't know the values until the user fills out a form it can still be done using JavascriptL When the user clicks the form submit you can set multiple cookies by making multiple javascript calls like:
document.cookie = 'key1=test; expires=Mon, 7 Sept 2009 23:47:11 UTC; path=/'
The security model might give you some trouble if you are trying to pass this data from one domain to another though.

Categories