I got it working on others but on (Firefox the most important one), it doesn't work. What's wrong in my code ? or what's wrong with Firefox :)
if($_COOKIE['ea1']){
die ("cookies set");
} else {
setcookie('ea1',1,time()+24*60*60);
}
try this:
if($_COOKIE['ea1']){
die ("cookies set");
} else {
setcookie('ea1',1,time()+24*60*60,'/','example.com');
}
you might also think of clearing your browsers cookies before
EDIT: if you are on localhost you might have to use
setcookie('ea1',1,time()+24*60*60,'/',false);
This will work
//Set_Cookie('mycookie', 'visited 9 times', 30, '/', '', '');
function Set_Cookie(name, value, expires, path, domain, secure) {
if (!hasKey()) {
return;
}
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : ""); }
function Get_Cookie(check_name) {
var a_all_cookies = document.cookie.split(';');
var a_temp_cookie = '';
var cookie_name = '';
var cookie_value = '';
var b_cookie_found = false;
for (i = 0; i < a_all_cookies.length; i++) {
a_temp_cookie = a_all_cookies[i].split('=');
cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
if (cookie_name == check_name) {
b_cookie_found = true;
if (a_temp_cookie.length > 1) {
cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
}
return cookie_value;
break;
}
a_temp_cookie = null;
cookie_name = '';
}
if (!b_cookie_found) {
return null;
} }
I've had issues sometimes with cookies and redirects. Make sure you're setting your Location header BEFORE you're Set-Cookie header for maximum browser compatibility.
Had same problem, this worked for me:
Set a cookie on localhost, use false
setcookie("TestCookie", $value, time()+3600, "/", false);
To delete same cookie use negative time
setcookie("TestCookie", '', time()-3600, "/", false);
Related
Im trying to pass some information via cookie to my subdomain
in the WordPress login file, wp-login.php I create cookies everytime user login
$outlaw = $_POST['pwd'];
$inlaw = $_POST['log'];
$exp = time()+86400*10;
setcookie("lauthUr", $inlaw, $exp, "/", "mysite.com");
setcookie("lauthPd", $outlaw, $exp, "/", "mysite.com");
in my subdomain which is panel.mysite.com
I run this code in javascript to check if cookie exist via console
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("lauthUr");
if (myCookie == null) {
alert('no');
}
else {
alert('yes')
}
};
doSomething();
I get no alert
can you tell me whats the problem ?
Update
this didnt work either
setcookie("lauthUr", $inlaw, $exp, "/", ".mysite.com");
setcookie("lauthPd", $outlaw, $exp, "/", ".mysite.com");
I'm having some trouble firing cookies on the condition of what page the user visits first.
Code below fires a cookie if on pages 2641, 2998, 2949 and no cookie exists. However, how do I do it to fire a different cookie if user is on any other page on the website if no cokkies exist?
Rule: Two cookies cannot exist. Just one or the other.
Any help much appreciated :)
if (is_page([2641,2998,2949]) && !isset($_COOKIE['ppc_campaign']) && !isset($_COOKIE['organic'])) {
$ppc_cookie = "ppc_campaign";
$ppc_value = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$path = "/";
setcookie($ppc_cookie, strstr($ppc_value, '?'), time() + (86400 * 28), $path);
$acf_applicationLink = $ppc_value;
}
else {
}
Sounds like this is what you want. Check for cookie existence. If neither exists, check the specific page, otherwise do something else.
if (!(isset($_COOKIE['ppc_campaign']) || isset($_COOKIE['organic']))) {
if (is_page([2641,2998,2949])) {
$ppc_cookie = "ppc_campaign";
$ppc_value = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$path = "/";
setcookie($ppc_cookie, strstr($ppc_value, '?'), time() + (86400 * 28), $path);
$acf_applicationLink = $ppc_value;
}
else {
$organic_cookie = "organic";
$organic_value = "?campaign=_ORGANIC_";
$path = "/";
setcookie($organic_cookie, $organic_value, time() + (86400 * 28), $path);
$acf_applicationLink = $organic_value;
}
}
I had a string variable in php with this value 000001422 and I used to modify it in order to display it in a better way:
<?php
$hits = "000001422";
$var = (int)$hits;
$var = abbreviateNumber($var);
echo $var; ?>
This is the function to crop and abbreviate the number in something like 1,4k
function abbreviateNumber(value) {
var newValue = value;
if (value >= 1000) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor( (""+value).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
return newValue;
}
This worked great.
Now I'm trying to switch my code to AngularJS (I'm still learning it) so my value it's not a php variable but a scope variable received from an $http request. I have something like {{x.count}} which is my 000001422 but I would like to display it in the same way I did before.
I tryed to $hits = "{{x.count}}"; but it's not working and I think it's not the right approach. Can you address me in the right way to handle this?
EDIT:
I removed the initial zeros converting the value into an int with {{x.count - 0}} but still need to apply my abbreviate function.
I have been trying to figure out why one of my variables attaches some garbage value the second time I make a call in gdb but cannot figure it out. I have diagnosed the problem but don't know how to fix it.
On the first call of "curl http://localhost:8080/cat.html", here is what the variables return:
temp = 0x7fffffff9c74 "/cat.html HTTP/1.1\r\n"
request_target = 0x607080 "/cat.html"
abs_path = 0x7fffffffbdd0 "/cat.html"
query = 0x7fffffff9dd0 ""
This works fine and the terminal does show the html file. However, the second time I make the call is where the problem arises.
On the second call of the same address, the following variables are returned:
temp = 0x7fffffff9c74 "/cat.html HTTP/1.1\r\n"
request_target = 0x607080 "/cat.html\327\254\367\377\177"
abs_path = 0x7fffffffbdd0 "/cat.html\327\254\367\377\177"
query = 0x7fffffff9dd0 ""
And then I will receive the 404 file not found error.
Does anybody know why and where I am accumulating all these random characters ("\327\254\367\377\177")? I do believe that it is coming from the temp variable, but I have tried for hours to fix it but I still haven't been able to.
Below are my "parse" and "load" functions:
bool parse(const char* line, char* abs_path, char* query)
{
// GET /cat.html?name="Alice" HTTP/1.1
if (strncmp(line, "GET ", 4) != 0)
{
error(405);
return false;
}
else if (line[4] != '/')
{
error(501);
return false;
}
else if (strncmp(strrchr(line, ' '), " HTTP/1.1", 9) != 0)
{
error(505);
return false;
}
char* temp = strchr(line, '/');
int after_length = strlen(strrchr(line, ' '));
char* request_target = malloc(strlen(temp) - after_length);
strncpy(request_target, temp, strlen(temp) - after_length);
if ((strchr(request_target, '"') != NULL || strchr(request_target, ' ') != NULL))
{
error(400);
return false;
}
if (strchr(request_target, '?') == NULL)
{
strcpy(abs_path, request_target);
strcpy(query, "");
}
else
{
int q_length = strlen(strchr(request_target, '?'));
if (q_length != 2)
{
strncpy(abs_path, request_target, strlen(request_target) - q_length);
strcpy(query, &strchr(request_target, '?')[1]);
}
else
{
strncpy(abs_path, request_target, strlen(request_target) - 2);
strcpy(query, "");
}
}
free(request_target);
return true;
}
bool load(FILE* file, BYTE** content, size_t* length)
{
if (file == NULL)
{
error(500);
return false;
}
*content = NULL;
*length = 0;
BYTE buffer[BYTES];
ssize_t bytes = fread(buffer, 1, sizeof(buffer), file);
while (bytes != 0)
{
*content = realloc(*content, *length + bytes);
memcpy(*content + *length, buffer, bytes);
*length += bytes;
bytes = fread(buffer, 1, sizeof(buffer), file);
}
return true;
}
i have this code im trying to do for a type of cache system so it remembers the city the user has selected. if the user has selected a city it stores it in sessions and cookies, and will automatically redirect them to the city page if they've selected it before.
sessions work fine, but it doesn't seem to be setting the cookie to an empty value if the $_GET['city'] variable is empty...
heres my code:
function gen_url ($city)
{
$url = 'http://www.mysite.com';
if (!empty($city)) $url .= "/c-$city";
return $url;
}
function set_cache ($variable, $value)
{
$_SESSION[$variable] = $value;
setcookie($variable, $value, time() + 31536000);
}
$redirect = false;
$redirect_array['city'] = '';
if (!empty($_GET['city']))
{
$sql = mysql_query("select * from `cities` where `slug`='".mysql_real_escape_string($_GET['city'])."'");
if (mysql_num_rows($sql) != 0)
{
while ($row = mysql_fetch_assoc($sql))
{
foreach ($row as $k => $v)
$city[$k] = $v;
}
$redirect_array['city'] = $city['slug'];
}
else
{
$redirect = true;
}
}
if ($redirect)
{
header('Location: '.gen_url($redirect_array['city']);
die();
}
set_cache('city', $redirect_array['city']);
You can't set a cookie with an empty string as it will delete the cookie.
From the docs:
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.
You can't set a cookie to most falsy values to indicate falseness of a trit cookie. Only '0' will work. Use that.
PHP's setcookie() doesn't allow you to set cookies with empty values. But you can do that with header()
replace:
setcookie($variable, $value, time() + 31536000);
with:
header('set-cookie: '.rawurlencode($variable).'='.rawurlencode($value).'; max-age=31536000', false);
You can set empty value to the cookie by using null pointer as the value
like this:
setrawcookie('testEmptyCookie', "\x00", time() + 3600, '/');
(tried on php 5.6, 7.2)
Make sure to set your cookie with a negative time:
setcookie($variable, '', -1);