Let’s suppose I‘ve set cookie in PHP, like so:
cookie_name = "USER_PRODUCT".rand(0,9999);
$cookie_value = $name;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
echo "Successs";
And I display those cookie data like this:
<?php foreach ($_COOKIE as $key=>$val) { ?>
<div class="row col-sm-4 productDiv" data-id="myProduct_<?=$i?>" style="margin: 0px;">
<div class="alert alert-info mydiv"><?=$val?></div>
</div>
<?php } ?>
Now on another page I need to display all cookies whose name starts with USER_PRODUCT. Is it possible in PHP or is there another way?
This is a solution without the explode.
<?php
foreach ($_COOKIE as $key=>$val) {
if (substr($key, 0, 12) == "USER_PRODUCT") {
echo $key . " - " . $val . "<br>";
}
}
Assuming your page 1 code is as follow
$name="topupStackoverflow";
$cookie_name = "USER_PRODUCT".rand(0,9999);
$cookie_value = $name;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
echo "Successs";
you can do this for page 2 (or any other application where the user_product can be located at any position)
$stringn="USER_PRODUCT";
foreach($_COOKIE as $cookie => $taste){
if(stristr($cookie,$stringn)!=false){
echo $cookie." = = >>".$taste."<br>";
}
}
Related
I am very new to php and this is the first time i use cookies. I am trying to create a cookie which will save user navigation inside my website. I have one page called Home, and one page called Feedback.
Problems:
When loading the webpage for the first time, php shows this error (ErrorException
Undefined index: nav_history). When page is refreshed it works properly, showing the pages name (Home or Feedback)
When navigating from Home to Feedback (or vice versa, but lets take Home to Feedback for example) the page will print Home (when it should print Feedback) and then if i refresh this page, Feedback is added below Home. I want it to show Feedback on the first try.
Code for home:
<?php
if (isset($_COOKIE['nav_history'])) {
$cookie_values = $_COOKIE["nav_history"];
$cookie_values .= "Home<br>";
setcookie("nav_history", $cookie_values, time() + (86400 * 30), "/");
} elseif (!isset($_COOKIE["nav_history"])) {
setcookie("nav_history", "Home<br>", time() + (86400 * 30), "/");
}
echo $_COOKIE['nav_history'];
?>
Code for feedback page
<?php
if (isset($_COOKIE['nav_history'])) {
$cookie_values = $_COOKIE["nav_history"];
$cookie_values .= "Feedback<br>";
setcookie("nav_history", $cookie_values, time() + (86400 * 30), "/");
} elseif (!isset($_COOKIE["nav_history"])) {
setcookie("nav_history", "Feedback<br>", time() + (86400 * 30), "/");
}
echo $_COOKIE['nav_history'];
?>
I have this feeling both problem scenarios can be fixed with the same change in code. Sorry if my explaining is not that clear.
<?php
if (isset($_COOKIE['nav_history'])) {
$cookie_values = $_COOKIE["nav_history"];
$cookie_values .= "Feedback<br>";
setcookie("nav_history", $cookie_values, time() + (86400 * 30), "/");
} elseif (!isset($_COOKIE["nav_history"])) {
setcookie("nav_history", "Feedback<br>", time() + (86400 * 30), "/");
}
echo $cookie_values ?? ''; //this line had to be changed.
?>
I have a website that has multiple locations and each location has their own set of information. When a user visits the main corp page, the location information will not display. When the user then goes to a location page I have a cookie being set.
$location_address = get_field('location_address','options');
$location_city = get_field('location_city','options');
$location_state = get_field('location_state','options');
$location_zip_code = get_field('location_zip_code','options');
$location_phone_number = get_field('location_phone_number','options');
// cookie will expire when the browser close
setcookie("locationAddress",$location_address);
setcookie("locationCity",$location_city);
setcookie("locationState",$location_state);
setcookie("locationZipcode",$location_zip_code);
setcookie("locationPhone",$location_phone_number);
The cookie is showing my location information in the firebug console. However, what is happening is when I go to another location, its grabbing both sets of cookies. I need it to replace the cookie previously set with the new one.
This is my code as well to output the cookie, which seems to be breaking as well:
<div class="top_contact">
<p><?php if(!isset($_COOKIE[$location_address])) { echo "" . $location_address . "";} ?>, <?php if(!isset($_COOKIE[$location_city])) { echo "" . $location_city . "";} ?> <?php if(!isset($_COOKIE[$location_state])) { echo "" . $location_state . "";} ?> <?php if(!isset($_COOKIE[$location_zip_code])) { echo "" . $location_zip_code . "";} ?> | <span class="top_phone"><?php if(!isset($_COOKIE[$location_phone_number])) { echo "" . $location_phone_number . "";} ?></span> </p>
</div>
You should set "path" argument in setcookie.
setcookie("locationAddress",$location_address, 0, "/");
setcookie("locationCity",$location_city, 0, "/");
setcookie("locationState",$location_state, 0, "/");
setcookie("locationZipcode",$location_zip_code, 0, "/");
setcookie("locationPhone",$location_phone_number, 0, "/");
If I were you I would probably try and set the path for the cookies.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
also, I spotted a few commas in your code and I fixed the spaghetti code.
<?php
echo '<div class="top_contact"><p>';
if(!isset($_COOKIE[$location_address]))
{
echo $location_address;
}
if(!isset($_COOKIE[$location_city]))
{
echo $location_city;
}
if(!isset($_COOKIE[$location_state]))
{
echo $location_state;
}
if(!isset($_COOKIE[$location_zip_code]))
{
echo $location_zip_code;
}
echo '<span class="top_phone">';
if(!isset($_COOKIE[$location_phone_number]))
{
echo $location_phone_number;
}
echo '</span> </p> </div>';
?>
I have this cookie on set
$id = "1"
$password = "test";
$cookie_name = "megamitch_server_status";
$cookie_time = (3600 * 24 * 30); // 30 days
setcookie ($cookie_name, 'usr='.$id.'&hash='.$password, time() + $cookie_time);
how I can get the value of usr inside that cookie name "megamitch_server_status"?
any help, ideas, suggestions would be greatly appreciated. Thank you!
This should work for you :
(Here I just use preg_match_all() to extract the data)
<?php
preg_match_all("/usr=(.*)&hash=(.*)/", $_COOKIE["megamitch_server_status"], $matches);
echo "usr: " . $matches[1][0];
echo "hash: " . $matches[2][0];
?>
output:
usr: 1
hash: test
OR if you want you can store your cookies like this:
setcookie ($cookie_name . "[usr]", $id, time() + $cookie_time);
setcookie ($cookie_name . "[hash]", $password, time() + $cookie_time);
And then you can access them like this:
echo $_COOKIE["megamitch_server_status"]["usr"];
echo $_COOKIE["megamitch_server_status"]["hash"];
I'm doing a while() and in it I use a function to display a prettier "time since posted", but for some reason, all of the results end up in the same "time passed" (the last result) when echoing it out
only the time will become the same, not the other content. Here's my code, trimmed down a bit:
<?php
$result = $db->query("SELECT * FROM $dbboardname WHERE replyto = '' AND hidden = '' ORDER BY bump ASC LIMIT $pagenum, 20") OR die($db->error);
while($rowaaa = $result->fetch_assoc()){
$id = $rowaaa['id'];
$textcontent = $rowaaa['textcontent'];
$imageurl = $rowaaa['imageurl'];
$name = $rowaaa['nameyes'];
$timestamps = $rowaaa['timestamp'];
$timestamps = time_passed($timestamps);
$tripcode = $rowaaa['tripcode'];
?>
<div class="post-index" data-postid="<?php echo($id); ?>" name="<?php echo($id); ?>" id="<?php echo($id); ?>">
<div class="image-container-index">
<?php if(!empty($imageurl)){ ?>
<img src="<?php echo($imageurl); ?>" alt="image <?php echo($id); ?>" />
<?php }else{
?>
<img src="/images/noimage.png" alt="no image" />
<?php
}
?>
</div>
<div class="post-info">
<span class="post-info-left">
#<?php echo($id); ?> by <?php if (!empty($name)){
echo(substr($name, 0, 8));
}else{
echo("norseman");
}
?>
</span>
<span class="post-info-right">
<?php echo($timestamps); ?>
</span>
<div class="clear"></div>
</div>
<div class="post-preview">
<?php echo(substr($textcontent, 0, 150)); ?>
</div>
</div>
<?php
}
?>
<div class="clear"></div>
And here is the time_passed() function:
function time_passed($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
So my guess is that for every new "while", it edits all of the timestamps. I just don't know how to fix this, considering the string is inside an while() statement.
EDIT:
I noticed my timestamp updated because I altered the bump row on every post each time a new thread was posted, this way all the timestamps were updated. I fixed the timestamp row now.
It looks like your time_passed routine is expecting a datetime - not a timestamp, perhaps that is the error.
function time_passed($datetime, $full = false) {
Try to change this line:
$ago = new DateTime($datetime);
to this:
$ago = new DateTime(date('r',$datetime));
I hope that helps.
Let's try this again ... since they are all coming out the same, it sounds like the value you are passing to the function is wrong then - try putting a a test around the timestamp assignment:
$timestamps = $rowaaa['timestamp'];
echo "Made |$timestamps| from |{$rowaaa['timestamp']}<br/>\n";
$timestamps = time_passed($timestamps);
echo "Now timestamps is |$timestamps| from time_passed() function<br/>\n";
If they are all the same, the problem is in your data.
You can also show the entire content of the array by doing this:
echo "Full Details<pre>\n".print_r($rowaaa,1)."\n</pre>\n";
I Cant login for some reazon, every time i open with
the testing file password exist, i have put an echo-test and mark it, but the code allways runs the else and not the if.
the kernel-login-logout.php is this:
<?php
$formusername = $_GET["username"];
$formpasswd = $_GET["passwd"];
$passwdget = file_get_contents( "users/$formusername/passwd/thepasswd.txt" );
if ($formpasswd == $passwdget)
{
setcookie("libusername", $formusername,time() + (86400 * 7));
setcookie("libpasswd", $formpasswd,time() + (86400 * 7));
}
else
{
echo ("Password not found<br>");
}
?>
<?php echo ($passwdget); ?><br>
<?php echo ($formpasswd); ?>
the url:
kernel-login-logout.php?username=userdokimi&passwd=testpasswd&login=Login
the output:
Password not found
testpasswd
testpasswd
You have code like this:
if A
if B
else C
That else applies to the if B, NOT the if A.
I think you meant this:
if A
elseif B
else C
Try this:
<?php echo "'$passwdget'",strlen($passwdget); ?><br>
<?php echo "'$formpasswd'",strlen($formpasswd); ?>
to confirm that one or both of those variables don't have some invisible characters glued on to them, making them not equal.
You have a password stored in plain text (and visible in a Query String) -- that's very insecure, but we'll let that pass for the moment.
Don't assume the keys "logout", "passwd" and "username" will always be set.
You are also missing an else there.
if (isset($_GET['passwd']) && $_GET["passwd"] == $passwdget)
{
setcookie("libusername", $username,time() + (86400 * 7));
setcookie("libpasswd", $passwd,time() + (86400 * 7));
}
else if (isset($_GET['logout']) && $_GET["logout"] == "Logout")
{
setcookie("libusername", null,time() + (86400 * 7));
setcookie("libpasswd", null,time() + (86400 * 7));
}
else
{
echo ("<br>Password not found");
}