storing multiple values of a variable in cookie and comparing - php

How can i store multiple values for a variable in cookie using php, for example
$id = 1,2,4,5
Then how can i compare the stored values with a variable? for example, $new_id=4, i want to check if $new_id value exists in the stored values of $id in cookie.
Thanks for help and have a nice day.

You can store arbitrary strings in cookie elements, so a serialized array should work. Example:
// To store:
$ids = array(1, 2, 3, 4);
setcookie('ids', serialize($ids));
// To retrieve:
$serialized = $_COOKIE['ids'];
$ids = unserialize($serialized);
// sanity check: $ids needs to be an array.
assert(is_array($ids));
// Now let's check:
if (in_array(4, $ids)) {
// Yes, it's here.
}
A few caveats though:
The cookie is completely in the hands of the client, and cookie values should never be trusted. Treat them just like you would treat query string parameters or POST data.
Cookies offer very limited storage (IIRC, the standard gives you 4096 bytes to work with).
With these in mind, it might be a better idea to store the array in $_SESSION instead - this will give you virtually unlimited storage, and the only way for the client application to fiddle with the values is through your code.

Try with following snippet.
// do Stuff to retrieve value of $id from cookie.
// explode variable to array
$idArr = explode(',' , $id);
// check existence of new_id in cookie variable.
if(in_array($new_id , $idArr)){
// new_id exist in cookie variable
}
Hope this will help
Thanks!
Hussain.

to use the multiple value you can use the array and then to store it you can serialize ( and unserialize) the array.
To create array: $array = array(1,2,3,4);
To compare: if (in_array(2,$array)) echo "Yep";
To serialize the data to be stored: $store = serialize($array);
Ten you will be able to create the cookie with $store data and then use unserialize($store) to reconvert data in array.
Serialize Manual

Store array in cookie and then compare them

Here is one out of many solutions (syntax may contain errors):
// Create an array with the values you want to store in the cookie
$id = array(1, 2, 3, 4);
// Create cookie
set_cookie('id', implode(',', $id));
// Get cookie
$id = explode(',', $_COOKIE['id']);
// Test value
if(in_array($newId, $id) === true) {
// Value is in the array
}
Restrictions:
The values stored in $id cannot include commas, choose another separator if you need to store commas

Related

How to store a php array inside a cookie?

I'm trying to create a php to do list using cookies, however am struggling to store the cookie inside an array so that I can add more than one cookie.
When I submit the form, a cookie is added, but when I go to add another the first one is replaced.
I want to store the cookie in a variable, push it to an array then save it to the end of the list rather than replace the current cookie.
Here is the code I have so far:
if (isset($_POST['submit'])) {
$task = htmlentities($_POST['task']);
$tasks = array ();
if(isset($_COOKIE[$task])) {
array_push($tasks, $task);
echo $_COOKIE[$task];
} else {
}
setcookie('task', $task, time() + 3600);
header('Location: index.php');
}
I'm not sure on exactly where I'm going wrong, would anyone be able to help?
When you store a cookie with the same name, it gets overwritten. You also seem to be storing the individual task and not the array. If you would like to store the array safely, you can attempt to store it as JSON.
It would look like this:
if (isset($_POST['submit'])) {
$task = htmlentities($_POST['task']);
//Check if the cookie exists already and decode it if so, otherwise pass a new array
$tasks = !empty($_COOKIE['tasks']) ? json_decode($_COOKIE['tasks']) : [];
//if(isset($_COOKIE[$task])) {
array_push($tasks, $task);
// echo $_COOKIE[$task];
//}
$encodedTasks = json_encode($tasks);
setcookie('task', $encodedTasks, time() + 3600);
header('Location: index.php');
}
You seem to be checking if the value of the post variable is a key in your array rather than using the 'tasks' key as you set in your setcookie. You do not need to see if the array exists again as you passed either the decoded array or the empty array as 'task'
There are a few things wrong with your code. First of all, you cannot story an array in a cookie, only strings. Whay you can do is transform your cookie to JSON when setting it, and when you are getting it decode it. Also, when pushing to you array, the array you are pushing to is reset on every request. To get around this, first get you data from the cookie. Something like this is what I would use:
const COOKIE_NAME = 'tasks';
$tasks = ['one', 'two'];
setcookie(COOKIE_NAME, json_encode($tasks));
$newTask = 'another task';
if (isset($_COOKIE[COOKIE_NAME])) {
$tasks = json_decode($_COOKIE[COOKIE_NAME], true);
array_push($tasks, $newTask);
setcookie(COOKIE_NAME, json_encode($tasks));
}
var_dump(json_decode($_COOKIE[COOKIE_NAME], true)); // Every request after the first time a cookie is set "another task" is added to the cookie.

array_merge before json encode in PHP

$myArray = array();
for($i=0;i<2;$i++){
..
.. //get the content logic here
assign it to array
$myArray["item"]["content"] = $item_content;
}
echo json_encode($myArray);
The above code produced this result:
Which has an error because I didn't merge them.
I tried to merge like this:
$finalJson = array_merge($finalJson, $myArray);
but the output of echo $finalJson is one object instead of 3.
Update:
Your real problem is down to your use of array_merge on an associative array. The behaviour of array_merge is to reassign duplicate keys if they are associative (cf the docs):
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
And because $myArray is clearly using strings as keys, the values in $finalJson are being reassigned. What you need to do is either create unique keys on each iteration, or simply push the values of $myArray onto a numerically indexed $finalJson array (like I showed in my original answer below)
The problem is simply this:
$myArray["item"]["content"] = $item_content;
it's inside the loop, each time reassigning the value of $myArray["item"]["content"], and not adding it to the array. I suspect that what you wanted to do is add this at the bottom of your loop (for each new value of $myArray):
$finalJson[] = $myArray;
Then, on the next iteration, $myArray will be reassigned, and its new value will be appended to the $finalJson variable.
i have a tricky problem.
What i do.
I generate from the System Tables of Databases (DEV ,Test Prod setup) information for Tables, Vies trigger … with PHP and compare the results ti see teh differences with JavaScript.
Also I have a Documentation DB for additional business information which was installed only once on TEST DB.
Therfore I need to connect all four environments to get the data.
I use
if ($flag === 'i')
for information DB and
elseif ($flag === 's')
for system db‘s.
Result is $row_array and $info_array which must be combined and sendet back to Javascript.
$json_response = array_merge($rinfo, $rsql );
echo json_encode($json_response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
I try this merge in a different positions in the program.
First time in
elseif ($flag === 'i') {
result json:
[
{
"0": "ACT",……….
} ][ ]
second time after } //ifelse return also 2 arrays
[{"0":"ACT","1":"Tabelle Akten","2":"hh","3":null,"4":null,"5":"UCC","6":"Y","7":"Reload Data in Test","8":"y","9":"delete all older tha","10":"n","11":" ","12":"y","13":" ","14":"o","15":"y","16":"o","17":"y","18":"y","19":"Diese tabelle speichert die Acten Verweise","20":"Gert Dorn","21":1570254359,"TDESCRIPTION":"n","TTYPE":" ","TREC_ESTIM":"y","TREC_GROWTH":" ","TDOMAIN":"o","TREL_TYPE":"y","TREL_RULES":"o","THOUSEKEEPING":"y","THOUSE_RULES":"y","TCID":"Diese tabelle speichert die Acten Verweise","TCID_RULES":"Gert Dorn","TUSE_UCC":1570254359,"TUSE_DWH":"","TUSE_ODS":"","TUSE_CWF":"","TUSE_IWF":"","TUSE_OWF":"","TUSE_DEP_MANAGER":"","TENTITY_DESCRIPTION":"","TOWNER":""
,"TTIMESTAMP":""**}][{**"0":"ACT","1":"DB2INST1"
,"2":"USERSPACE1","3":null,"4":"2018-11-21 16:43:20.066567","5":"2018-12-07 10:12:10.255759","6":null,"7":"2020-03-26","8":"2018-11-21 16:43:20.343258","9":3,"NAME":"ACT","CREATOR":"DB2INST1","TBSPACE":"USERSPACE1","REMARKS":"","CTIME":"2018-11-21 16:43:20.066567","STATS_TIME":"2018-12-07 10:12:10.255759","STATISTICS_PROFILE":"","LASTUSED":"2020-03-26","ALTER_TIME":"2018-11-21 16:43:20.343258","COLCOUNT":3}]
The program code and result you can download at
http://dmdg.io/dmdg.zip
Hope you can help Kind regards gert
Did you consider using array_push?
array_push is always preferred than myArray[] = $value

php multiple session name or sub-session name?

my script currect have two session called
$_SESSION['mypic']
and
$_SESSION['mypicsrc']
can I combine this two to one session and sub-session?
like this:
$_SESSION['mypic']
$_SESSION['mypic']['src']
the $_SESSION global is an array that will only store strings. If you want to store an array inside a $_SESSION var you have to serialize it first
$data = array( 'src' => '' );
$_SESSION['mypic'] = serialize($data);
then to get it back out you have to deserialize
$data = deserialize($_SESSION['mypic']);
However, you should store your data in a database and then store an id or reference to that particular record in $_SESSION.
Actually, you only have one session there, with the values stored in $_SESSION.
You can change them like any other variable;
$_SESSION['mypic']['src'] = $_SESSION['mypicsrc'];

Why can't I use integers as an index in a PHP $_SESSION array?

Eg:
$_SESSION['1'] = 'username'; // works
$_SESSION[1] = 'username'; //doesnt work
I want to store session array index as array index. So that o/p is :
Array(
[1] => 'username'
)
$_SESSION can only be used as an associative array.
You could do something like this though:
$_SESSION['normal_array'] = array();
$_SESSION['normal_array'][0] = 'index 0';
$_SESSION['normal_array'][1] = 'index 1';
Personally, I'd just stick with the associative array.
$_SESSION['username'] = 'someuser';
Or
$_SESSION['username_id'] = 23;
I suspect this is probably because the $_SESSION array is purely an associative array. Additionally, as the PHP manual puts it:
The keys in the $_SESSION associative
array are subject to the same
limitations as regular variable names
in PHP, i.e. they cannot start with a
number and must start with a letter or
underscore.
Incidentally, have you checked your error log for any NOTICE level errors? (You may have to enable this level.) Attempting to use a numeric key will quite possibly raise an error.
You can also take this approach to save an array dimension:
$_SESSION['form_'.$form_id] = $form_name;
which might look like the following:
$_SESSION['form_21'] = 'Patient Evaluation';
as opposed to:
$_SESSION['form'][21] = 'Patient Evaluation';
which uses another array dimension.

Save PHP array to MySQL?

What is a good way to save an array of data to a single mysql field?
Also once I query for that array in the mysql table, what is a good way to get it back into array form?
Is serialize and unserialize the answer?
There is no good way to store an array into a single field.
You need to examine your relational data and make the appropriate changes to your schema. See example below for a reference to this approach.
If you must save the array into a single field then the serialize() and unserialize() functions will do the trick. But you cannot perform queries on the actual content.
As an alternative to the serialization function there is also json_encode() and json_decode().
Consider the following array
$a = array(
1 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
2 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
);
To save it in the database you need to create a table like this
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
$r = mysql_query(
'DROP TABLE IF EXISTS test');
$r = mysql_query(
'CREATE TABLE test (
id INTEGER UNSIGNED NOT NULL,
a INTEGER UNSIGNED NOT NULL,
b INTEGER UNSIGNED NOT NULL,
c INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (id)
)');
To work with the records you can perform queries such as these (and yes this is an example, beware!)
function getTest() {
$ret = array();
$c = connect();
$query = 'SELECT * FROM test';
$r = mysql_query($query,$c);
while ($o = mysql_fetch_array($r,MYSQL_ASSOC)) {
$ret[array_shift($o)] = $o;
}
mysql_close($c);
return $ret;
}
function putTest($t) {
$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (id,".
implode(',',array_keys($v)).
") VALUES ($k,".
implode(',',$v).
")";
$r = mysql_query($query,$c);
}
mysql_close($c);
}
putTest($a);
$b = getTest();
The connect() function returns a mysql connection resource
function connect() {
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
return $c;
}
Generally, yes, serialize and unserialize are the way to go.
If your data is something simple, though, saving as a comma-delimited string would probably be better for storage space. If you know that your array will just be a list of numbers, for example, then you should use implode/explode. It's the difference between 1,2,3 and a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}.
If not, then serialize and unserialize work for all cases.
Just use the serialize PHP function:
<?php
$myArray = array('1', '2');
$seralizedArray = serialize($myArray);
?>
However, if you are using simple arrays like that you might as well use implode and explode.Use a blank array instead of new.
Serialize/Unserialize array for storage in a DB
Visit http://php.net/manual/en/function.serialize.php
From the PHP Manual:
Look under "Return" on the page
Returns a string containing a byte-stream representation of value that can be stored anywhere.
Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.
Note: If you want to store html into a blob, be sure to base64 encode it or it could break the serialize function.
Example encoding:
$YourSerializedData = base64_encode(serialize($theHTML));
$YourSerializedData is now ready to be stored in blob.
After getting data from blob you need to base64_decode then unserialize
Example decoding:
$theHTML = unserialize(base64_decode($YourSerializedData));
The best way, that I found to myself is save array as data string with separator characters
$array = array("value1", "value2", "value3", "...", "valuen");
$array_data = implode("array_separator", $array);
$query = "INSERT INTO my_tbl_name (id, array_data) VALUES(NULL,'" . $array_data . "');";
You can then search data, stored in your array with simple query
$query = "SELECT * FROM my_tbl_name WHERE array_data LIKE '%value3%'";
use explode() function to convert "array_data" string to array
$array = explode("array_separator", $array_data);
note that this is not working with multidimensional arrays and make sure that your "array_separator" is unique and had not exist in array values.
Be careful !!! if you just will take a form data and put in database, you will be in trap, becous the form data isn't SQL-safe ! you must handle your form value
with mysql_real_escape_string or if you use MySQLi mysqli::real_escape_string
or if value are integer or boolean cast (int) (boolean) on them
$number = (int)$_POST['number'];
$checked = (boolean) $_POST['checked'];
$name = mysql_real_escape_string($db_pt, $_POST['name']);
$email = mysqli_obj->real_escape_string($_POST['email']);
Serialize and unserialize are pretty common for that. You could also use JSON via json_encode and json_decode for a less PHP-specific format.
As mentioned before - If you do not need to search for data within the array, you can use serialize - but this is "php only". So I would recommend to use json_decode / json_encode - not only for performance but also for readability and portability (other languages such as javascript can handle json_encoded data).
Uhh, I don't know why everyone suggests serializing the array.
I say, the best way is to actually fit it into your database schema. I have no idea (and you gave no clues) about the actual semantic meaning of the data in your array, but there are generally two ways of storing sequences like that
create table mydata (
id int not null auto_increment primary key,
field1 int not null,
field2 int not null,
...
fieldN int not null
)
This way you are storing your array in a single row.
create table mydata (
id int not null auto_increment primary key,
...
)
create table myotherdata (
id int not null auto_increment primary key,
mydata_id int not null,
sequence int not null,
data int not null
)
The disadvantage of the first method is, obviously, that if you have many items in your array, working with that table will not be the most elegant thing. It is also impractical (possible, but quite inelegant as well - just make the columns nullable) to work with sequences of variable length.
For the second method, you can have sequences of any length, but of only one type. You can, of course, make that one type varchar or something and serialize the items of your array. Not the best thing to do, but certainly better, than serializing the whole array, right?
Either way, any of this methods gets a clear advantage of being able to access an arbitrary element of the sequence and you don't have to worry about serializing arrays and ugly things like that.
As for getting it back. Well, get the appropriate row/sequence of rows with a query and, well, use a loop.. right?
You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html
I think this is the best solution, and will help you maintain your code more readable by avoiding crazy functions.
I expect this is helpful for you.
Yup, serialize/unserialize is what I've seen the most in many open source projects.
I would suggest using implode/explode with a character that you know will not be contained in any of the individual array items. Then store it in SQL as a string.
you can insert serialized object ( array ) to mysql , example serialize($object) and you can unserize object example unserialize($object)
check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.
$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";
If the values in the array are text values, you will need to add quotes
$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";
mysql_query($conn,$query);
Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.
UPDATE
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_query
PDO::query()
Instead of saving it to the database, save it to a file and then call it later.
What many php apps do (like sugarcrm) is to just use var_export to echo all the data of the array to a file.
This is what I use to save my configurations data:
private function saveConfig() {
file_put_contents($this->_data['pathtocompileddata'],'<?php' . PHP_EOL . '$acs_confdata = ' . var_export($this->_data,true) . ';');
}
I think this is a better way to save your data!

Categories