Cookie not setting in PHP - php

Thought this was super easy, but I've spent the last half hour trying to figure it out to no avail.
$unique_id = uniqid(microtime(),1);
if (is_null($_COOKIE['client_id']))
{
setcookie("client_id", $unique_id);
}
But when I go to check the cookie through $_COOKIE['client_id'], I get a null value. Any ideas whats going on?

Cookies have to be set before ANYTHING is outputted. also I've had many problems with cookies before.
Also, see Can't set cookies in PHP? for explanation why you cant check its existence at the same time as setting it.

The _COOKIE array is created when the script initializes, and is then left alone by PHP. Setting a cookie within the script will not magically add it to $_COOKIE. It will only show up on the next script request, or you manually assign it into $_COOKIE.

You should set cookie with
$_COOKIE['key'] = 'value';

Yeah FallingBullets has right. Be affraid when you use UTF8 file encoding - the first chars with is sent to client is UTF8 file head ( 0xEF 0xBB 0xBF). In this case is ob-start http://php.net/manual/en/function.ob-start.php not work (UTF8 file head is sent before ob-start).
What I describe is probably characteristic of the web server. Try save jour script in ascii encoding.

Related

php cookies error - http setcookie over request only [duplicate]

Thought this was super easy, but I've spent the last half hour trying to figure it out to no avail.
$unique_id = uniqid(microtime(),1);
if (is_null($_COOKIE['client_id']))
{
setcookie("client_id", $unique_id);
}
But when I go to check the cookie through $_COOKIE['client_id'], I get a null value. Any ideas whats going on?
Cookies have to be set before ANYTHING is outputted. also I've had many problems with cookies before.
Also, see Can't set cookies in PHP? for explanation why you cant check its existence at the same time as setting it.
The _COOKIE array is created when the script initializes, and is then left alone by PHP. Setting a cookie within the script will not magically add it to $_COOKIE. It will only show up on the next script request, or you manually assign it into $_COOKIE.
You should set cookie with
$_COOKIE['key'] = 'value';
Yeah FallingBullets has right. Be affraid when you use UTF8 file encoding - the first chars with is sent to client is UTF8 file head ( 0xEF 0xBB 0xBF). In this case is ob-start http://php.net/manual/en/function.ob-start.php not work (UTF8 file head is sent before ob-start).
What I describe is probably characteristic of the web server. Try save jour script in ascii encoding.

UTF-8 encoding and SESSION inconsistency?

QUESTION:
Hello stackoverflow!
So this encoding stuff is getting on my last nerve. Not enough that it is difficult to figure out what the best combination of encodings needs to be when sending stuff forth and back using AJAX and PHP and SQL etc.. But it also causing problems with SESSION???!
So basically I already found a hot-fix solution no-thanks to google, partly the reason I'm writing this now. But I would also like to see if anyone of you actually have any more practical solution.
PROBLEM:
For example if I want my PHP file to have UTF-8 encoding, it then adds hidden characters in the file which then can only be viewed and deleted in a hex-editor. For those that don't know, YES any extra characters that aren't commented out will cause problems with SESSION and give you header error. So when I delete them, and re-upload the file, it falls back to ANSI encoding. Maybe there are different editors that can encode files more properly into UTF-8? I don't know, I'm using Notepad++ at the moment and am perfectly happy with it and it is hard to believe it should cause problems with encoding. I have also tried to change my default encoding in .htaccess file and no difference for the index file anyways.
It seems, although we get WARNING: session_start(): Cannot send session cache limiter - headers already sent ... the sessions are still set perfectly fine and all we could do at this point is simply turning off warning errors by placing this on top of our php file: error_reporting(~E_NOTICE & ~E_WARNING); although this doesn't really solve our problem and simply hiding it from public eye.
Page open Notepad2 or Sublime Text -> Save with Encoding -> UTF-8
index.php
<?php
session_start();
header('Content-type: text/html; charset=utf-8');
echo 'Hello ÇÖİŞÜĞüğışçö'; // bla bla
?>
SOLUTION:
I had to therefore make a fix by making 2 separate files for one and the same index, just with different encoding. Like my main file is ANSI encoded and called
index.php
that will have session_start(); line in it and beneath it we include our main scripts that were originally supposed to be there, but instead now included with this include('index_.php'); ................ Also I found out that this problem will NOT occur on all hosting servers, but only some. So the real solution may be found trough somewhere in the server settings.

Sending UTF8 in GET parameter

When navigating to a URL like this:
http://example.com/user?u=ヴィックサ
I notice that Chrome encodes the characters as:
http://example.com/user?u=%E3%83%B4%E3%82%A3%E3%83%83%E3%82%AF%E3%82%B5
And everything works serer-side.
However, in IE I get this error from my code:
The user you are trying to find (?????) does not exist.
Note the five question marks. For some reason the PHP never gets to see the parameter.
What could be causing this, and is there any way to fix it?
Sadly it seems what you want to do is not going to work for the current generation of IE
The accepted answer for this question UTF-8 Encoding issue in IE query parameters says that you need to encode the characters yourself rather than relying on the browser as support varies from browser to browser, and maybe even device to device
<a href='/path/to/page/?u=<?=urlencode('ヴィックサ')?>'>View User</a>
Also I presume you are setting utf8 headers from the webserver? you didn't say, if not, in php
header('Content-Type: text/html; charset=utf-8');

Cookies with extensions

I've seen cookies set by web pages with the "." character in them. I'm trying to maximize the dynamic use of a $_GET['url'] to set my cookies, and then include it in a next page as a conditional where it checks to make sure the cookie was set before it allows users to perform an action. Basically I'm using cookies and IP addresses in an anonymous voting action to make sure anyone who votes only gets one per day. IPs are reset through a cron job once a day, and the cookies are set to expire after 17 hours. I have no issues setting a cookie named with the .php extension, however after many hours of trial and error, I can't get it to accept it in an if(isset). No matter what I try, it will not recognize that the cookie is set. Without the extension everything works fine. I've tried a dozen configurations, but here's basically what I have trying to debug.
<?php
$cookie = "test.php";
setcookie("$cookie", "workdamnyou");
if (isset($_COOKIE[$cookie])) {
echo "is set";
}
else {
echo "not set";
}
?>
I've tried isset($_COOKIE["$cookie"]) and isset($COOKIE['$cookie']) as well. That said, I really wish you could run PHP without uploading it each time to your server.. --
setcookie doesn't change $_COOKIE immediately. It sets the headers to change the cookie in the browser, so the script won't see the test value until you refresh the page.
You CAN run PHP without uploading to a server; the easiest option is to install a xAMP stack (LAMP/MAMP/WAMP depending on if you're developing on Linux/Mac/Windows).
Well, I found the solution I guess... PHP doesn't like dots in variable names (http://www.php.net/manual/en/language.variables.basics.php). Now, since Register Globals could be on, it might be possible that a $_COOKIE["name.ext"] could turn into a $name.ext which would be invalid. Thus, "Dots and spaces in variable names are converted to underscores. For example becomes $_REQUEST["a_b"]." (http://www.php.net/manual/en/language.variables.external.php). Does a check for isset("name_php") work?
You cannot set and access a cookie in the same instance! You have to do a redirect, refresh or something, but you cannot both set and access at the same time. Also make sure your other parameters are set like hostname, expiry time. . e.t.c
Eg.
setcookie("TestCookie", $value, time()+3600, "/", "/", 1);
For debugging, just do a var_dump($_COOKIE)
Note that cookies only become available on the next pageload (when they have traversed from server to client and back).
Try setting the cookie directly with $_COOKIES["test.php"] = "test"; and see what happens with
var_dump($_COOKIE);
Also don't use the quotes around the $cookie variable. Thus make it
setcookie($cookie, "work");
instead of
setcookie("$cookie", "work");
Last, you can run PHP locally with your own server. The easiest way on Windows is the WAMPP stack. I find this one very easy to install and run: http://www.apachefriends.org/en/xampp.html
Good luck!
Why would you have a .php extension in the cookie name? It should be:
$cookie = 'test';
See http://www.ietf.org/rfc/rfc2109.txt point 4.1:
The two state management headers, Set-Cookie and Cookie, have common
syntactic properties involving attribute-value pairs. The
following grammar uses the notation, and tokens DIGIT (decimal
digits) and token (informally, a sequence of non-special, non-white
space characters) from the HTTP/1.1 specification [RFC 2068] to
describe their syntax.
av-pairs = av-pair *(";" av-pair)
av-pair = attr ["=" value] ; optional value
attr = token
value = word
word = token | quoted-string
Attributes (names) (attr) are case-insensitive. White space is
permitted between tokens. Note that while the above syntax
description shows value as optional, most attrs require them.
NOTE: The syntax above allows whitespace between the attribute and
the = sign.

How to ensure variables submitted in UTF8 using jquery $.post

I have been struggling with this for three days now and this is what i have got and i cannot understand why i am seeing this behavior.
my problem is that i have a MySql spanish db with char set and collation defined as utf8_general_ci. when i query the data base in delete.php like this "DELETE FROM countryNames WHERE country = '$name'"
the specified row doesnot get deleted. i am setting the variable $name in delete.php through a post variable $name=$_post['data'] . mostly $name gets the value in spanish characters e.g español, México etc. the delete.php file gets called from main.php.if i send a post message from main.php $.post("delete.php", {data:filename}); , the query doesnot deletes the entry (although the 'filename' string is in utf8) but if i create a form and then post my data variable in main.php, the query works!! the big question to me is why do i have to submit a form for the query to work? what im seeing is my database rejects the value if it comes from a jquery post call but accepts it when its from a submitted form. (i make no code change for the query to work. just post the value by submiting the form)
First of all, to see what charset ìs used for requests, install something like Firebug and check the 'Content-Type' header of your request/response. It will look something like 'application/json; charset=...'. This should be charset=utf-8 in your case.
My guess why it worked when posting a form is probably because of x-www-form-urlencoded - non-alphanumeric characters are additionally encoded on the client side and again decoded on the server, that's the difference to posting the data directly.
This means that somewhere there is a wrong encoding at work. PHP treats your strings agnostic to its encoding by default, so I would tend to rule it out as the source of the error. jQuery.post also uses UTF-8 by default... so my suspect is the filename variable. Are you sure it is in UTF-8? Where and how do you retrieve it?
You should probably also ensure that the actual HTML page is also sent as UTF-8 and not, let's say iso-8859-1. Have a look at this article for a thorough explanation on how to get it right.
guys this was a Mac problem!! i just tested it on windows as my server and now everything works fine. So beware when u r using Mac as a server with MySql having UTF8 as charset and collation. I guess the Mac stores the folder and file name in some different encoding and not UTF-8.
You answer might be here: How to set encoding in .getJSON JQuery
As it says there, use $.ajax instead of $.post and you can set encoding.
OR, as it says in the 2nd answer use $.ajaxSetup to set the encoding accordingly.
Use .serialize() ! I think it will work. More info: http://api.jquery.com/serialize/

Categories