Set cookies on file upload in PHP - php

I have a php upload handler in upload.php, and there, I have to following
<? setcookie("test",100,time()+3600); ?>
but, when I check the cookies that are set, I dont see any "test" cookie at all.
Can you please help me set a cookie on file upload? why is this upload script any different from any normal script that is accessed by the browser?
Here is the code I have
<?php
if (!empty($_FILES)) {
if(move_uploaded_file($tempFile,$targetFile))
{
setcookie("targetPath",$targetPath,time() + 3600,'/');
print $_COOKIE['targetPath']; // prints fine here
echo 1;
}
else
echo -1;}
else
{
//print_r($_COOKIE);
print "start cookie >> ";
print $_COOKIE['targetPath']; // does not print when I call upload.php standalone
print " << end cookie";
}
?>

This may or may not solve your problem, but I thought I should point it out:
setcookie needs to be called prior to any output, unless you are using output buffering.
The first argument to move_uploaded_file should be something like $_FILES["pictures"]["tmp_name"][0]
Cookies set with setcookie don't show up until the next page load. And yes, this is documented in the PHP manual:
Once the cookies have been set, they
can be accessed on the next page load
with the $_COOKIE or $HTTP_COOKIE_VARS
arrays.
This means that this code:
setcookie("targetPath",$targetPath,time() + 3600,'/');
print $_COOKIE['targetPath']; // prints fine here
should print the cookie's old value.
setcookie returns false if it fails. You might want to check that return value.

Are you checking to see if cookies are set in upload.php, ie. the same script you set them? If so, I wouldn't expect them to be set. The cookie will be sent by the client on the next HTTP request after they have received the cookie from upload.php.

setcookie has "path" argument. If it is not specified: "The default value is the current directory that the cookie is being set in."
So most likely you're trying to set cookie for something like www.youdomain.com/actions/upload.php and in that case cookie will be set for /actions/ path.
Also check that call setcookie is done before any output from your script

Try specifying the domain?
<?php
setcookie( 'test', 100, time()+3600, '/', '.sitename.com' );
Are you fetching it with $_COOKIE['test'] ?
PS - You should not be using short tags. Replace <? with <?php.

Related

Why can't I set a cookie in PHP which can be used in an If statement on the next page?

I'm trying to create a cookie within PHP.
By using the following code :
<?php
//Writing Cookie Data
setcookie("Enabled", "True", time()+3600);
setcookie("Username", $username);
//Test if cookie is set. / Just for test purposes.
echo $_COOKIE["Username"];
?>
After the cookie is set I've used a code to let users go to the next page by pressing an image (link).
This one :
<img src="image.png"></img>
And I've used a code on the next page which will check if the cookie exists.
This one :
<!-- Security Start -->
<?php
If (isset($_COOKIE["Enabled"])) {
}
else
{
header("Location: ../");
}
?>
<!-- Security Stop -->
And when the user goes to the next page he'll just be redirected to the folder specified if the security cookie doesn't exist.
I've probably setup everything correctly, and I've already checked many things, but I can't come up with a solution to this problem. The cookie should exist, and exsists.
Because the echo code works on the same page.
But after going to the next page; the cookie is suddenly gone, it doesn't exist.
Echo and using it in an If statement on the next page are both not possible.
Any ideas what might cause this?
Cookies
Some things I would do to debug this if you want cookies:
I would check the path as stated by Patrick
I would look at the return value of setcookie and see if it tells you it failed.
In your browser you should be able to see a list of all cookies, and you can check and see if the cookie was actually set. Again, look at the path here.
Using a session instead
However, I agree with the session recommendation by developerwjk, one way to do it is to make sure you call 'ob_start()' as one of the first things that happens on the page, it will then buffer the output and give you time to manipulate $_SESSION. Make sure you then call ob_flush(), to flush the buffer once you are finished with all session stuff.. I believe otherwise it will automatically flush the buffer at the end of the page but it might just discard everything..
You do not see the cookie because you have not set the PATH argument for setcookie
Using a path of "/" will enable the use of the cookie anywhere on the domain, otherwise the cookie can only be seen by scripts in the folder and sub folders of the executing script.
setcookie("Enabled", "True", time()+3600, "/");
setcookie("Username", $username,time()+3600,"/");
But as with the comments do not use cookies in place of sessions, as cookies can be easily faked.
If you already have session started you do not need to do session_start() again, if you have php 5.4 or higher you can check session status with session_status
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
or if it is lower than 5.4
if (!isset($_SESSION)) { session_start(); }
As per the user submitted comment on the session_status page

php script that will check for cookie,if cookie yes go to url, if no cookie run script

Im trying to create a php script that will check for cookie. If cookie exist it goes to a page. If the cookie does not exist it it will run script. however its not quiet working I think its the index.php code below thats the issue.
gateway.php
<?php
$value = "mobilecookie";
/*setcookie(name,value,expire,path,domain,secure)*/
setcookie("mobilecookie",$value, time()+60*60*24*30);
?>
index.php
<?php
if( $.cookie('mobilecookie') == null ) {
require_once("gateway/scripts/mobile.php");
window.location.replace('http://domian.com/index.php');
}
?>
use
header("Location: http://domian.com/index.php");
exit;
1 to redirect the user
And cookie is read by $_COOKIE['mobilecookie']
1: Do NOT output anything (even UTF-8 BOM) before header
If you require a delay, I would use your PHP to create a Javascript redirect so that way the page will load before you do the redirect.
If you would like an immediate redirect, you should use the PHP header() function.
Another note being that Cookies are sent out using a header, so you can not set a cooke and retrieve its value in the same instance of a script, the page must be reloaded to get the new value.

Check if a PHP cookie exists and if not set its value

I am working on a multilingual site so I tried this approach:
echo $_COOKIE["lg"];
if (!isset($_COOKIE["lg"]))
setcookie("lg", "ro");
echo $_COOKIE["lg"];
The idea is that if the client doesn't have an lg cookie (it is, therefore, the first time they've visited this site) then set a cookie lg = ro for that user.
Everything works fine except that if I enter this page for the first time, the first and second echo return nothing. Only if I refresh the page is the cookie set and then both echo print the "ro" string I am expecting.
How can I set this cookie in order to see its value from the second echo on the first visit/page load of the user? Should be without needing to refresh the page or create a redirect.
Answer
You can't according to the PHP manual:
Once the cookies have been set, they can be accessed on the next page
load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
Work around
But you can work around it by also setting $_COOKIE when you call setcookie():
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
Source
If you set a cookie with php setcookie you can see the set and the value of the cookie, as an example, with the developer tools of firefox just in time.
But you need to reload/load the same/next page if you wanna read, get or check the cookie and the value inside to work with that cookie in PHP.
With this example you can choose if you wanna reload the same page with PHP, HTML or JAVASCRIPT.
If the cookie is not accepted or cookies are disabled, a loading loop is obtained and the browser stops loading the page.
LONGVERSION WITH PHP 'header' RELOAD SAME PAGE:
<?php
$COOKIE_SET = [
'expires' => '0'
,'path' => '/'
// ,'domain' => 'DOMAIN'
,'secure' => 'true'
,'httponly' => 'true'
// ,'samesite' => 'Strict'
];
$COOKIE_NAME = "MYCOOKIE";
$COOKIE_VALUE = "STACKOVERFLOW";
if(!isset($_COOKIE[$COOKIE_NAME])){
setcookie($COOKIE_NAME, $COOKIE_VALUE, $COOKIE_SET);
// YOU NEED TO RELOAD THE PAGE ONCE
// WITH PHP, HTML, OR JAVASCRIPT
// UNCOMMENT YOUR CHOICE
// echo '<meta http-equiv="refresh" content="0;URL=/">';
// echo '<script>window.location.replace("/");</script>';
header("Location: /");
exit;
}
else{
echo ($_COOKIE[$COOKIE_NAME]);
}
?>
SHORTVERSION WITH PHP 'header' RELOAD SAME PAGE:
if(!isset($_COOKIE['MYCOOKIE'])){
setcookie('MYCOOKIE', 'STACKOVERFLOW');
header("Location: /");
exit;
}
echo ($_COOKIE['MYCOOKIE']);

PHP Cookies are not being set

I'm having issues with setting up cookies. The problem is that my cookies aren't even being set, I have setup a test below to see if they are being set but they are never being set. I've even checked in my browser to see if anything is being set, but nothing from my site.
I would like you to help me make my cookies set. I'm not quite sure what to do. Thank you.
Here is my code:
<?php
session_start();
setcookie("ridArray","", time()+3600);
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
}
?>
<head>
</head>
<html>
<body>
<?php
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
} else { echo "not set"; }
?>
</body>
</html>
Here's the problem, from the SetCookie documentation:
Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.
You are setting the cookie value to empty string (""). Try:
setcookie("ridArray","not blank value", time()+3600);
The other issue is that when you set a cookie, it will not be in the request headers (accessed via $_COOKIE) until the next page load. This means when you load that page the first time, $_COOKIE['ridArray'] will NOT be set. On subsequent loads, it will be set, and it will be reset every time.
First page load, it won't be set. Refresh, and it will be set.
The easiest way to debug cookies is to use something like Chrome's developer tools or Firefox's FireBug and watch the response headers for the SetCookie header, and the request headers to see what cookies your browser is sending.

Unable to set cookie if it does not already exist in PHP

I am trying to set a cookie for a site if it does not exist. It is not working.
if(isset($_COOKIE['about'])){
$_COOKIE['about'] += 1;
}
if(!isset($_COOKIE['about'])){
setcookie("about", 1, time()+3600);
}
I have also tried
if(empty($_COOKIE['about'])){
setcookie("about", 1, time()+3600);
}
The $_COOKIE superglobal is only available for you to read values from. Writing to it does not update the cookie, since that requires a new Cookie header to be sent to the browser. You would probably be better served by sessions backed by cookies, since PHP allows you to modify the session without explicitly saving/setting the cookie.
You can only read stuff from the $_COOKIE superglobal, try setting it normally:
setcookie("about",$_COOKIE['about']+1,time()+3600);
So all together:
if(isset($_COOKIE['about'])){
$_COOKIE['about'] += 1;
}else{
setcookie("about", 1, time()+3600);
}
Note the else, you've checked before if the cookie isset, so there is no need to check again as either it is or it isn't.
Make sure you have not sent any information to the user yet as the setcookie call is just an alias to header() (but with a specific schema to follow). You may have error output disabled and are missing the message, so it appears to work but is failing in the background.
setcookie should be one of the first calls on your page, up there with starting a session and setting a header.

Categories