How do you set a php cookie with multiple values? - php

I want to create a php cookie that stores the username and the userid. Or is it better to just use one to get the other?

If you're only looking to store two values, it may just be easier to concatenate them and store it as such:
setcookie("acookie", $username . "," . $userid);
And to retrieve the information later,
if(isset($_COOKIE["acookie"])){
$pieces = explode(",", $_COOKIE["acookie"]);
$username = $pieces[0];
$userid = $pieces[1];
}
Cheers,
~Berserkguard

<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
?>
http://php.net/manual/en/function.setcookie.php

You can use an array for example
<?php
// the array that will be used
// in the example
$array = array(
'name1' => 'value1',
'name2' => 'value2',
'name3' => 'value3'
);
// build the cookie from an array into
// one single string
function build_cookie($var_array) {
$out = '';
if (is_array($var_array)) {
foreach ($var_array as $index => $data) {
$out .= ($data != "") ? $index . "=" . $data . "|" : "";
}
}
return rtrim($out, "|");
}
// make the func to break the cookie
// down into an array
function break_cookie($cookie_string) {
$array = explode("|", $cookie_string);
foreach ($array as $i => $stuff) {
$stuff = explode("=", $stuff);
$array[$stuff[0]] = $stuff[1];
unset($array[$i]);
}
return $array;
}
// then set the cookie once the array
// has been through build_cookie func
$cookie_value = build_cookie($array);
setcookie('cookie_name', $cookie_value, time() + (86400 * 30), "/");
// get array from cookie by using the
// break_cookie func
if (isset($_COOKIE['cookie_name'])) {
$new_array = break_cookie($_COOKIE['cookie_name']);
var_dump($new_array);
}
?>
Hope this answer help you out

I know it's an old thread, but this might save a future me some headache. The best way I believe would be to serialize/unserialize the data.
setcookie('BlueMonster', serialize($cookiedata);
$arCookie = unserialize($_COOKIE['BlueMonster']);
(hijacked from https://www.brainbell.com/tutorials/php/Saving_Multiple_Data_In_One_Cookie.htm since it was far more complete than I would have thrown together in 5 mins)
<?php
require_once 'stripCookieSlashes.inc.php';
function setCookieData($arr) {
$cookiedata = getAllCookieData();
if ($cookiedata == null) {
$cookiedata = array();
}
foreach ($arr as $name => $value) {
$cookiedata[$name] = $value;
}
setcookie('cookiedata',
serialize($cookiedata),
time() + 30*24*60*60);
}
function getAllCookieData() {
if (isset($_COOKIE['cookiedata'])) {
$formdata = $_COOKIE['cookiedata'];
if ($formdata != '') {
return unserialize($formdata);
} else {
return array();
}
} else {
return null;
}
}
function getCookieData($name) {
$cookiedata = getAllCookieData();
if ($cookiedata != null &&
isset($cookiedata[$name])) {
return $cookiedata[$name];
}
}
return '';
}
?>

Related

Find array with a specific data string and return another data string it has

I have this JSON(Cant change it)
every array in bbData contains["Username","ID","Age"]
{"bbData":[
["Peter","/id/5423","42.4"],
["Bob","/id/5355","32.1"],
["Dolan","/id/5113","22.6"]
]]}
I know an id for a user, let's say "/id/5423".
How can i then make PHP find the array with that id and return the age data which lays in the same array?
PHP >= 5.5.0
$data = json_decode($myJsonString);
$searchId = "/id/5355";
$key = array_search($searchId, array_column($data->bbData, 1));
if ($key === false) {
$found = $searchId, ' not found';
} else {
$found = $data->bbData[$key];
}
var_dump($found);
EDIT
For earlier versions of PHP, replace
$key = array_search($searchId, array_column($data->bbData, 1));
with
$key = array_search(
$searchId,
array_map(
function($value) {
return $value[1];
},
$data->bbData
)
);
Decode the array into PHP first -
$users = json_decode($jsonString,true);
Then (there will be a better way of doing this with array_search), but this will suffice for you -
$knownUserId = 123;
$userDetails = false;
foreach($users AS $user) {
if($user[1] == '/id/'.$knownUserId) {
$userDetails = $user;
break;
}
}
You now have the user details in $userDetails

replace any specific character in array key

$array['a:b']['c:d'] = 'test';
$array['a:b']['e:f']= 'abc';
I need output like below. array can have multiple level . Its comes with api so we do not know where colon come.
$array['ab']['cd'] = 'test';
$array['ab']['ef']= 'abc';
(untested code) but the idea should be correct if want to remove ':' from keys:
function clean_keys(&$array)
{
// it's bad to modify the array being iterated on, so we do this in 2 steps:
// find the affected keys first
// then move then in a second loop
$to_move = array();
forach($array as $key => $value) {
if (strpos($key, ':') >= 0) {
$target_key = str_replace(':','', $key);
if (array_key_exists($target_key, $array)) {
throw new Exception('Key conflict detected: ' . $key . ' -> ' . $target_key);
}
array_push($to_move, array(
"old_key" => $key,
"new_key" => $target_key
));
}
// recursive descent
if (is_array($value)) {
clean_keys($array[$key]);
}
}
foreach($to_move as $map) {
$array[$map["new_key"]] = $array[$map["old_key"]];
unset($array[$map["old_key"]]);
}
}
try this:
$array=array();
$array[str_replace(':','','a:b')][str_replace(':','','c:d')]="test";
print_r($array);
This seems like the simplest and most performant approach:
foreach ($array as $key => $val) {
$newArray[str_replace($search, $replace, $key)] = $val;
}

Echo a value from an array based on function parameters

I need to be able to echo a value from a private property in one of my classes if a method is called within the class. It's a little tricky to explain so let me demostrate and hopefully someone can fill in the blank for me :)
<?php
class test {
private $array['teachers']['classes'][23] = "John";
public function __construct($required_array) {
$this->array['teachers']['classes'][23] = "John";
$this->array['students'][444] = "Mary";
$this->echo_array($required_array);
}
public function echo_array($array) {
// Echo the value from the private $this->array;
// remembering that the array I pass can have either
// 1 - 1000 possible array values which needs to be
// appended to the search.
}
}
// Getting the teacher:
$test = new test(array('teachers','classes',23));
// Getting the student:
$test = new test(array('students',444));
?>
Is this possible?
$tmp = $this->array;
foreach ($array as $key) {
$tmp = $tmp[$key];
}
// $tmp === 'John'
return $tmp; // never echo values but only return them
An other approach to get value;
class Foo {
private $error = false,
$stack = array(
'teachers' => array(
'classes' => array(
23 => 'John',
24 => 'Jack',
)
)
);
public function getValue() {
$query = func_get_args();
$stack = $this->stack;
$result = null;
foreach ($query as $i) {
if (!isset($stack[$i])) {
$result = null;
break;
}
$stack = $stack[$i];
$result = $stack;
}
if (null !== $result) {
return $result;
}
// Optional
// trigger_error("$teacher -> $class -> $number not found `test` class", E_USER_NOTICE);
// or
$this->error = true;
}
public function isError() {
return $this->error;
}
}
$foo = new Foo();
$val = $foo->getValue('teachers', 'classes', 24); // Jack
// $val = $foo->getValue('teachers', 'classes'); // array: John, Jack
// $val = $foo->getValue('teachers', 'classes', 25); // error
if (!$foo->isError()) {
print_r($val);
} else {
print 'Value not found!';
}

Saving post values in a session array

I want to save values send via POST in a session array:
$reply = array('thread_id', 'reply_content');
$_POST['thread_id'] = 2; # test it
$_SESSION['reply'] = array();
foreach ($reply as $key)
{
if (in_array($key, $_POST))
{
$_SESSION['reply'][$key] = $_POST[$key];
}
}
var_dump($_SESSION['reply']);
For example I want to check if the keys 'thread_id' and 'thread_content' are send in post, if they are then I want to save them in a session array called reply, using the same keys.
So for example if 'thread_id' is send via POST:
$_POST['thread_id'] = 'blah';
Then this should get saved in a session called 'reply', using the same key:
$_SESSION['reply']['thread_id'] = 'blah';
How can this be done?
In general, your approach looks valid, but I'm going to guess that you may not be calling session_start(), which is necessary to persist session data.
session_start();
if(!$_SESSION['POST']) $_SESSION['POST'] = array();
foreach ($_POST as $key => $value) {
$_SESSION['POST'][$key] = $value;
}
var_dump($_SESSION['POST']);
in_array($needle, $haystack) checks whether $needle is a value in $haystack and not a key. Use array_key_exists or isset instead:
foreach ($reply as $key)
{
if (array_key_exists($key, $_POST))
{
$_SESSION['reply'][$key] = $_POST[$key];
}
}
Or:
$_SESSION['reply'] = array_merge($_SESSION['reply'], array_intersect_key($_POST, array_flip($reply)));
Use this
$reply = array('thread_id', 'reply_content');
$_POST['thread_id'] = 2; # test it
$_SESSION['reply'] = array();
foreach ($reply as $key)
{
if (isset($_POST[$key]))
{
$_SESSION['reply'][$key] = $_POST[$key];
}
}

Turning off multidimensional arrays via POST in PHP

Is there a way to turn off the PHP functionality for Submitting a multidimensional array via POST with php?
So that submission of <input type="text" name="variable[0][1]" value="..." /> produces a $_POST like so...
array (
["variable[0][1]"] => "...",
)
NOT like so:
array (
["variable"] => array(
[0] => array (
[1] => "..."
),
),
)
I'm thinking/hoping an obscure PHP.ini directive or something... ?
No, but nothing stops you from fetching the query string (through $_SERVER['QUERY_STRING']) and parsing it manually. For instance:
$myGET = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $v) {
if (preg_match('/^([^=])+(?:=(.*))?$/', $v, $matches)) {
$myGET[urldecode($matches[1])] = urldecode($matches[2]);
}
}
I should think not. What exactly are you trying to do?
You could use variable(0)(1) or variable_0_1 as names for example.
Don't believe you can do that. I also don't understand why you'd need to. But this should work:
$_POST['variable'] = array(array('abc','def'),array('ddd','ggg'));
print_r(flatPost('variable'));
function flatPost($var)
{
return enforceString($_POST[$var], $var);
}
function enforceString($data, $preKey = '')
{
if(!is_array($data))
{
return array($preKey . $data);
}
$newData = array();
foreach($data as $key => &$value)
{
$element = enforceString($value, $preKey . '[' . $key . ']');
$newData = array_merge($newData, $element);
}
return $newData;
}
It's a little over the top, but if necessary you could manually parse the request body.
<?php
if(!empty($_POST) && $_SERVER['CONTENT_TYPE'] == 'application/x-www-form-urlencoded') {
$_post = array();
$queryString = file_get_contents('php://input'); // read the request body
$queryString = explode('&', $queryString); // since the request body is a query string, split it on '&'
// and you have key-value pairs, delimited by '='
foreach($queryString as $param) {
$params = explode('=', $param);
if(array_key_exists(0, $params)) {
$params[0] = urldecode($params[0]);
}
if(array_key_exists(1, $params)) {
$params[1] = urldecode($params[1]);
}
else {
$params[1] = urldecode('');
}
$_post[$params[0]] = $params[1];
}
$_POST = $_post;
}
?>

Categories