I was trying to figure out how isset() and empty() related to setcookie() and $_COOKIE[]. But I came upon a road-block on the way.
Here is my test.php
<?php
//initialize cookie
$expiry = time()+60*60*9000;
setcookie('name1', '4', $expiry, '/', '', '', TRUE);
if (isset ($_COOKIE['name1'])) {
echo 'cookievalue ' . $_COOKIE['name1'];
} else {
echo 'cookie value not set';
}
if (!empty ($_COOKIE['name1'])) {
echo 'cookievalue ' . $_COOKIE['name1'];
} else {
echo 'cookie value empty';
}
?>
Here is my test1.php
<?php
if (isset ($_COOKIE['name1'])) {
echo 'cookievalue ' . $_COOKIE['name1'];
} else {
echo 'cookie value not set';
}
if (!empty ($_COOKIE['name1'])) {
echo 'cookievalue ' . $_COOKIE['name1'];
} else {
echo 'cookie value empty';
}
echo 'cookievalue ' . $_COOKIE['name1'];
?>
When I first load test.php, and then test1.php, everything seems to work fine. That is, test1.php is able to read the $_COOKIE[] variable that was set in test.php via setcookie(). (Although, as expected, test.php had to be refreshed once before cookie values were output in test.php.)
However, if I close the browser, and reopen it, and then just run test1.php, I get an "Undefined Index" notice on name1 in $_COOKIE['name1'].
Why can't test1.php pick up the $_COOKIE variable defined before the browser was closed? The cookie should still be stored in the computer. Why can't it pull up the cookie value from it after closing and reopening the browser?
Answering my own question.
Thanks to #Dagon tried it using a different browser. It works in another browser (Firefox). It wasn't working in my Chrome browser (I suspect I have some anti-cookie extension on Chrome that's deleting the cookie -- or something like that).
You dont need isset() its as simple as
if ($_COOKIE['name1']) {
Related
I'm having problems getting simple session data values to persist after a page redirection. A function checks user data sent via Post and if it matches values in a database it sets session data to the values and redirects to another page:
if ($login_ok) {
//set session data
$_SESSION ['online'] = 1;
$_SESSION ['userid'] = $id;
$_SESSION ['username'] = $name;
//redirect to new page
redirect('start.php');
}
In the new page code the session data is not set. Simple testing returns null values as if the session data wasn't set:
echo 'Session Login Status: ' . $_SESSION ['online'];
echo 'Session UserID: ' . $_SESSION ['userid'];
echo 'Session Username: ' . $_SESSION ['username'];
Replacing the redirect with the above echo statements works correctly. Is the fact that the session data is set and the redirect activated before any page data has loaded mean that the session variables are not assigned?
To ensure an active session is always available, an include file contains this code:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Any idea what the issue is here?
Many thanks,
Kw
Check if the session is set before progress with
if isset($_SESSION ['online']) and
isset($_SESSION ['userid']) and
isset($_SESSION ['username'])
{
echo 'Session Login Status: ' . $_SESSION ['online'];
echo 'Session UserID: ' . $_SESSION ['userid'];
echo 'Session Username: ' . $_SESSION ['username'];
} else {
echo 'Redirect to login or Session expired';
}
Instead of redirect try this
$uid = $_SESSION['USERID'];
if (isset($uid) || $uid != NULL)
{
if (!headers_sent()) {
header('Location:main.php');
exit;
}
else {
?>
<script>window.location = 'main.php';</script>
<?php
}
}
This seems to be a server rather than a code issue. Running the code on a localhost server works correctly. Hope this is helpful to people experiencing similar issues.
Saying that, I have no idea how to set the remote server to allow session data. The server has browser based web administration software called cPanel, any suggestions?
I have an application that works TOTALLY fine on my local server.
It requires two things:
An active $_SESSION so that a number of key data elements are available on every page. (Stuff like user_id, and user_role.)
A couple of "require_once()" calls at the top of my pages, so that I have some constants available and standard messages available and the same header on every page.
Again, on my local server (using php 5.6), this is all fine and dandy.
On my HOST server (also using php 5.6), however, I have a catch-22:
If I call "session_start()" on each of my pages, I get a "headers already sent" warning, due to my use of "require_once()".
If I do NOT call "session_start()" on each of my pages, the $_SESSION variable is empty when it gets to the next page.
The only ideas I have seem very bad:
Don't use sessions and pass all my data in the URL. This seems insecure, clumsy, and like bad practice.
Don't use "require_once()", which seems really stupid as I'll have duplicate code all over the place.
Any ideas about what I should do?
I am on a shared server, so I don't think I can modify the php.ini file. And my host company, who has been very helpful about any other issue, has been totally silent over the past 2 weeks as I've sent them questions about this.
I have created a very simple example that shows the issue. Probably the most informative bit is in the comments for "firstpage.php", specifically the "if" statement under the comment "Under what circumstances is session being started".
Here is the index page (called mytestindex.php).
<?php
// Make sure $_SESSION array is available.
session_start();
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
// Set SESSION variable for later use on other pages
$_SESSION['emp_id'] = 100;
echo "\n\nThe employee id stored in SESSION is: " . $_SESSION["emp_id"] . "\n\n";
// Open next page when button clicked.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Set the name of the page we are going to next
$filename = "firstpage.php";
// ***************************************************************************************************
// If headers have't been sent (seems to depend on php.ini settings), simply call the header function
// This is the code that has worked on my local machine for years.
// ***************************************************************************************************
if (!headers_sent()) {
$redirect_to = "Location:" . $filename;
exit(header($redirect_to));
// *******************************************************************************************************************
// If headers have already been sent (require_once() above will do that), using the header function
// will generate a "headers have already been sent" warning on the host server. So need to use Javascript to avoid that.
// ********************************************************************************************************************
} else {
echo " Opening page with Javascript. ";
$code = '<script type="text/javascript">';
$code = $code . 'window.location.href="' . $filename . '";';
$code = $code . '</script>';
$code = $code . '<noscript>';
$code = $code . '<meta http-equiv="refresh" content="0;url=' . $filename . '" />';
$code = $code . '<noscript>';
echo $code;
exit;
}
}
?>
<div>
<form action="mytestindex.php" method="post">
<button type="submit">Go to first page</button>
</form>
</div>
Here is the page it links to (called firstpage.php):
<?php
/* First page */
//***************************************************
// Print to the screen information about the session
// This sends headers on the host server.
//***************************************************
require_once("printsessioninfo.php");
//***********************************************************************
// Print out other information before session started again on this page
if (headers_sent()) {
echo "Headers have already been sent.\n";
} else {
echo "No headers have been sent.\n";
}
if (isset($_SESSION)) {
echo "Session variable exists.\n";
} else {
echo "Session variable does not exist.\n";
}
//*****************************************************
// Under what circumstances is session being started
// and does it cause a "headers already sent" warning?
//*****************************************************
// THIS check is what works on my local machine, with no warnings about headers being sent.
if ( (!isset($_SESSION)) && (!headers_sent()) ) {
echo " START SESSION: session var is not set AND headers have not been sent.";
session_start();
} elseif (session_status == PHP_SESSION_NONE) {
echo " START SESSION: session does not exist";
session_start();
// THIS check is what works on my host server, BUT throws the warning about headers being sent.
} elseif (!isset($_SESSION)) {
echo " START SESSION: session var is not set";
session_start();
} else {
echo " No need to start a new session";
}
//******************************************************************************
echo "\n\n The employee id stored in the session variable is: " . $_SESSION["emp_id"] . " .";
if (session_status() == PHP_SESSION_ACTIVE) {
echo "\n\n\n NOW Session is active!";
}
?>
Here is a snippet of code that prints out some session info, so I have demonstrate how "require_once()" affects things (called printsessioninfo.php):
<?php
// Print session info
echo "<pre>";
$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();
echo 'session file: ' . $sessionfile . ' ';
echo 'size: ' . filesize($sessionfile) . "\n\n\n";
if (session_status() == PHP_SESSION_NONE) {
echo "Session does not exist!\n";
} elseif (session_status() == PHP_SESSION_DISABLED) {
echo "Session is disabled!\n";
} elseif (session_status() == PHP_SESSION_ACTIVE) {
echo "Session is active.";
}
?>
I was able to fix this (thank you "mister martin"), by moving the code for "session_start()" into my config.php file, making sure it was the VERY FIRST bit of code.
Then for every page in the application I made sure this was the first line of code:
<?php
require_once("config.php");
And that did the trick, for both development and host servers.
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Explanation required as it seems it wasn't clear enough (??):
If the status of the session is NONE then start it.
http://php.net/manual/en/function.session-status.php
http://php.net/manual/en/session.constants.php
Also this should be called BEFORE any require or require_once
I have a problem with cookies. In my login script i have the following line of code:
if($_GET['keep'] == "true"){
setcookie('id',$id,time()+3153600);
}
The problem I'm facing is that the cookies are not saving at all ( not even if i don't quit the browser). I'm quite a beginer in this respect and I think I'm not doing it right.
EDIT:
If i print_r all the Cookies it only gives me PHPSESSID after the cookie is set. I printed on index.php and i set the cookie on login.php
SOLUTION: Cookies are saved by default with the path of the file they were created in. To change the path there is another atribute. So by setcookie('id',$id,time()+3153600,'/'); you make the cookie available for the entire domain.
There is no issue in your code
if($_GET['keep'] = "true"){
setcookie('id',$id,time()+3153600);
}
This will may cause to
No data passing to $_GET['keep']
Or if data passing $_GET['keep'] value in not Matched ("true").
Both Works then $id is empty in setcookie method
Improve your code
if(isset($_GET['keep']){
if($_GET['keep'] == "true"){
if(isset($id))
{
#all perpect
$cokkie_id = 'id';
setcookie('id',$id,time()+3153600);
echo "I'm Set. And My value is ".$cokkie_id;
}
else
{
echo "Opzz My ID is also empty";
}
}
else
{
echo 'Get method is Set. But Value is not "true". Actual value is '. $_GET['keep'];
}
}
else
{
echo 'I cant reach Get method Buddy';
}
I think you miss "=" sign
if ($_GET['keep'] == "true") {
if (!isset($_COOKIE['id'])) {
setcookie('id',$id,time()+3153600);
}
}
use isset or ==
if (isset($_GET['keep']) && $_GET['keep'] == "true") {
setcookie('id', $id,time()+3153600);
}else{
echo 'keep is empty';
}
I am just stuck today at a wall of confusion and I'm hoping someone will be able to assist :)
I have a database full of basic projects, and within that table are attributes like Project Name, Project Number, Project Image, etc. I am able to enter new projects / display existing projects / etc. without issue.
My problem seems to come up when I want to Edit a project. My thoughts were that I would have to create an IF statement to find out if there's a new file uploaded or not, and either set the new file name in the database if there is, or keep the old in the database if there isn't.
I've been playing around with this for days, and I think I started off a bit too far ahead of myself. I've started breaking down to basics and I'm getting stumped with my IF statement, it feels like it's backwards? Does this make sense?
Examples:
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(isset($OldProjectImage1)){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
Now in searching StackExchange I found that we have to do the statement on the COOKIE portion instead of the Variable as I did above, but it also similarly fails.
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(!empty($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
And I've also tried with isset
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
I've tried both with my script, and they're both behaving similarly. Perhaps I am just confused at the overall process?
When I run my tests with and without cookies enabled, it always seems to skip the first part of the IF statement (with both isset and !empty) and jump to the next section. Then, similarly, it feels like the IF statement is backwards (if that makes any sense) - if I set a file to upload which populates ProjectImage1, I get "Image1 FILES empty". If I set no file to upload and submit the form, I get "Image1 FILES isset".
I thought it would essentially be, in plain English,
If cookie is empty then echo "Your Browser Cookies are not enabled"
Else if ProjectImage1 Name is set, echo "Image1 FILES isset"
Else if ProjectImage1 Name is Empty, echo "Image1 FILES empty"
but it's feeling to me like it's backwards? Am I understanding this wrong?
Thanks in advanced for any responses!
Problem lays with:
if(isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
}
You check if the cookie exist, and if it does, then you say that cookies are not enabled. A bit weird. Add ! before the isset. Then the if-statement and the text are correct.
I think, but I can only assume, you want this in the end:
if (isset($_COOKIE["OldProjectImage1"])){
// I believe the variable below can also be put between the else { and } down below
$OldProjectImage1 = $_COOKIE["OldProjectImage1"];
}
if(!isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(!isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES is not set';
} else if(empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES is empty';
}else {
// upload file here
}
I think you want to check the browser cookie is enabled or not?
Detect if cookies are enabled in PHP
Answer by Shiplu Mokaddim:
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
Detect cookie in Javascript
Check if cookies are enabled
So, combine with your code and my own explanation:
<?php
session_start();
//check if a cookie test is started
if (isset($_GET['check']) && $_GET['check'] == true) {
//cookie test is started
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
//cookie test success, go back to the previous page
header("location: {$_SESSION['page']}");
} else {
//cookie test fail, echo the message and continue
echo 'Your Browser Cookies are not enabled';
}
} else {
//start cookie test if a cookie test wasn't done
//check if a cookie test was done.
if (!isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
//start a cookie test if a cookie test wasn't done
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
setcookie('foo', 'bar', time() + 3600);
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
}
if(!isset($_COOKIE['OldProjectImage1'])){
echo "OldProjectImage1 doesn't exists in cookies.";
} else if(!isset($_FILES['ProjectImage1']['name'])){
echo "Image1 FILES is not set";
} else if(empty($_FILES['ProjectImage1']['name'])){
echo "Image1 FILES is empty";
}
?>
What's the correct way of passing variable using PHP cookie. I can't seem to get it to work? I keep getting "FAILED!"
Here's my code:
On 1st page:
$crpid['ONE']="PAGE1";
$crpid['TWO']="PAGE2";
$crpid['THREE']="PAGE3";
$crp_id = $_SERVER["REDIRECT_URIPART"];
$crp_value = $crpid[$crp_id];
session_start();
setcookie('crpid', $crp_value, time()+3600, "/");
On 2nd page:
if(!isset($_COOKIE['crpid']) && $_COOKIE['crpid']==''){
echo "FAILED!";
}
else{
echo "Cookie ".$_COOKIE['crpid']." is set!";
}