PHP - Set cookie and redirect - php

I am trying to set a cookie and redirect. Using Debian GNU/Linux 6.0 (64 bit) with PHP 5.3.3-7+squeeze19 with Suhosin-Patch (cli) (built: Feb 17 2014 10:10:23) and Apache/2.2.16 (Debian).
For some reason this works:
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
?>
But this does not:
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
header("Location: http://www.example.com");
exit;
?>
Even after several page loads. I've tried adding error reporting to the top of my code, but I don't see any errors when I load the page nor in the Apache log (/var/log/apache2/error.log):
error_reporting(E_ALL);ini_set('display_errors','1');
For some reason whenever I redirect, even using javascript as below, a cookie will not add.
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="1;url=http://www.example.com">
<script type="text/javascript">
window.location.href = "http://www.example.com"
</script>
<title>Page Redirection</title>
</head>
<body>
If you are not redirected, follow <a href='http://www.example.com'>this link</a>!
</body>
</html>
Why does the first example work but not the others?

Use include rather than redirect
This also saves the Browser a round trip HTTP request
<?php
$cookie_name = $_GET['a'];
$cookie_value = $_GET['b'];
setcookie($_GET['a'], $_GET['b'], time() + (86400 * 30), "/"); // 86400 = 1 day
include('/home/user/public_html/index.html');
exit;
?>
While I prefer include over a redirect header, your cookie should work. I have tested and it works just like it should.
In my test I redirected to another domain. The cookie is set in the domain where the PHP script resides.
setcookie('test', 'test', time() + (86400 * 30), "/");
header("Location: http://www.intel.com");
Works just like it is supposed to:

I was also getting this weirdness but with js redirect. Testing with chrome browser on xp.
The way I solved it was to do the cookie setting with injected js using document.cookie =
?>
<script type="text/javascript">
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
setCookie("foo","<?php echo $bar; ?>",30);
window.location = "<?php echo $destination_page; ?>.php";
</script>
<?php
then the problem went away.
It felt like the redirect was causing the php setcookie to fail for some reason...

Related

setcookie is not setting value in browser in PHP

I try to set cookie using below code in PHP but cookie is not displaying when I check using print_r($_COOKIE);
$str_zipcode = "20304";
setcookie("zipcode", $str_zipcode, 2147483647);
Then I try to set cookie using below code in PHP and cookie is displaying when I check using print_r($_COOKIE); But when I refresh browser or close and reopen browser and check cookie value using print_r($_COOKIE); then cookie not displaying and that means. Not sure what is wrong I am doing in this code.
$str_zipcode = "20304";
$_COOKIE['zipcode'] = $str_zipcode;
Below are my laptop configuration.
PHP 7
Ubuntu 16.0
Mozilla Firefox 80.0.1
EDIT #1
I checked in mobile's chrome browser too and it's behaving same as I mentioned above for my laptop.
the last parameter for cookie is its expiration date :
eg:
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
}

How to store $_POST data to $_COOKIE in moodle php

I was using the moodle and was not able to get the data of $_POST to $_COOKIE please help me out my code is given below.
<?php
$something = $_POST['UserType'];
$cookie_name = $something;
setcookie(cookie_name, $cookie_name, time() + (86400 * 30), "/");
?>
Than on another page I did something like this stated below.
<?php
$hello = $_COOKIE['cookie_name'];
echo $hello;
?>
But I didn't received any cookie stored in the browser's cookie.
<?php
$something = $_POST['UserType'];
$cookie_name = $something;
setcookie($cookie_name, $cookie_name, time() + (86400 * 30), "/");
?>
I have done this and strangely it worked.. Thank you all..

PHP cookie setting but not recognizing

Bear with me. Over the years I've begun to understand that I'm terrible at explaining myself.
I have a site with a page full of Spotify download links. On their first visit, people need to fill out a contact form to capture their email before being able to download. After that, they can download as many playlists as they want, forever.
When they click on the link the first time, a popup window opens the form.
After filling it out, the form redirects them to a new URL that sets the cookie (../playlists-for-events/?download=true). It also sets a variable so that the page doesn't need to be reloaded to download.
Now that the cookie is set, the playlists can be downloaded on any visit to the page (../playlists-for-events).
The cookie is setting as it's supposed to, but the PHP I've written isn't working.
The cookie
<?php $cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);
if(isset($_GET['download']) && $_GET['download'] == 'true'){
setcookie($cookie_name, $cookie_value, $date_of_expiry, '/',null,false,true);
$_COOKIE['spotify-download'] = 'allow';
} ?>
And the PHP that basically says "if the cookie isn't set, open the popup, else, start the download"
<?php if(!isset($_COOKIE['spotify-download'])) { ?>
<script type="text/javascript">function zforms_open_window(...)></script><a></a>
<?php } else { ?>
<?php } ?>
Help?
I've tested your code and it works fine, but the cookie can not be read until it is set. i.e. User redirected to /?download=true to set the cookie, it then needs to reload the page or go somewhere else that can now read the cookie.
<?php
$cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);
if( isset( $_GET['download'] ) && $_GET['download'] === 'true' ){
setcookie($cookie_name, $cookie_value, $date_of_expiry);
$_COOKIE[$cookie_name] = $cookie_value;
}
if( isset( $_COOKIE[$cookie_name] ) && $_COOKIE[$cookie_name] === $cookie_value) {
echo "You have access!";
} else {
echo "Access denied.";
}

session.cookie_secure does not set the secure cookie attribute

I've set session.cookie_secure to 1/true in php.ini and running the following code behind apache or php-fpm+nginx server --
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
After restarting php-fpm/apache, the 'secure' attribute does not appear in the Set-Cookie header. Checked using wget and firefox (developer tools > toggle tools > network)
echo session_get_cookie_params()[secure];
returns 1.
Forcing HTTPS CGI parameter to on/off doesn't make a difference. This change was verified using --
echo $_SERVER['HTTPS'];
This give the same result in RHEL/CentOS/EL 6 (PHP 5.3.3), RHEL/CentOS/EL 7 (PHP 5.4) and Gentoo (PHP 5.6.29)
session.cookie_secure configures the secure flag only for cookies sent by PHP's session extension; i.e. Set-Cookie headers triggered by session_start(), session_regenerate_id() calls.
It does not affect setcookie() or setrawcookie() (nor anything else in PHP that may send cookies to the client) - these functions have their own $secure parameter for that purpose.

Capturing PHP value in session or cookie

I am trying to capture the value of PHP output into a session or cookie so I can call it in other pages. Please see example below
session-page1.php
<?php
session_start();
ob_start();
?>
<!DOCTYPE HTML>
<!--
Strongly Typed 1.1 by HTML5 UP
html5up.net | #n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html lang="en" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml">
<?php $servurl = basename($_SERVER['REQUEST_URI']); ?>
<?php include_once "includes/ghead.php" ?>
<body itemscope itemtype="http://schema.org/CreativeWork" class="upload">
HEAD AND HEADER HTML CODE GOES HERE
<?php
$fpath="upload/myImage.jpg";
$size = getimagesize("$fpath");
$nheight = $size[1];
$nwidth = $size[0];
// Setting sessions
$_SESSION['filepath'] = $fpath;
$_SESSION['nwidth'] = $nwidth;
$_SESSION['nheight'] = $nheight;
session_write_close();
?>
<header>
<h2><?php echo $fpath; ?></h2>
<br> some html code goes here
<br> <a href='session-page2.php'>go to page 2</a>
</header>
<?php echo $_SESSION['filepath']; ?>
</body>
</html>
I want to now get the session values in page 2.
session-page2.php
<?php
session_start();
echo $_SESSION['filepath'].": ".$_SESSION['nwidth']."x".$_SESSION['nheight'];
session_write_close();
?>
The issue is that page1.php is not generating the session. I tried the same thing using cookies and I am not having any luck either.
cookie-page1.php
<?php
ob_start();
session_start();
$fpath="upload/myImage.jpg";
$size = getimagesize("$fpath");
$nheight = $size[1];
$nwidth = $size[0];
// Setting cookies
$cookie_name = 'test_cookie';
$cookie_value = $fpath;
setcookie($cookie_name, $cookie_value, time() + (3600), '/'); // 1 hour (60 minutes * 60 seconds = 3,600 seconds)
$cookie_name2 = 'test_cookie2';
$cookie_value2 = $nwidth;
setcookie($cookie_name2, $cookie_value2, time() + (3600), '/'); // 1 hour (60 minutes * 60 seconds = 3,600 seconds)
$cookie_name3 = 'test_cookie3';
$cookie_value3 = $nheight;
setcookie($cookie_name3, $cookie_value3, time() + (3600), '/'); // 1 hour (60 minutes * 60 seconds = 3,600 seconds)
session_write_close();
ob_end_clean();
?>
I want to now get the cookie values in page 2.
<?php
ob_start();
session_start();
echo $_COOKIE['test_cookie1'].": ".$_COOKIE['test_cookie2']."x".$_COOKIE['test_cookie3'];
session_write_close();
ob_end_clean();
?>
The cookie is not generated and the value is not saved. Can someone tell me what I am doing wrong? The code looks ok and should save the value/output of height/width and filename. Also, if this is not possible in PHP, should I be using Ajax to save the value? if yes, can someone point me in the right direction?
Thank you all in advance for your help!
Test this one, if it's not working there's something wrong with your php installation or configuration. When you click refresh the session value should increase with +1
<?php
session_start();
if (isset($_SESSION['test']))
{
$_SESSION['test'] = $_SESSION['test'] + 1;
}
else
{
$_SESSION['test'] = 1;
}
echo 'Session value = '.$_SESSION['test'].'<br />Refresh';
?>

Categories