Why are my cookies not being set? - php

We're using php to set some cookies for our users based on where they came from - some of these will be set based on the referrer URL, and some will be set based on a short query string in the URL.
We only set 2 cookies, and the purpose is to track where traffic is coming from and include the data in the user's submission for our product - then we are able to track which submissions come from which campaign.
It's a custom wordpress website, so the code is split across a few different files as follows:
header.php:
<?php
$origin = $_SERVER['HTTP_REFERER'];
$current = $_SERVER['PHP_SELF'];
$bestbefore = time() + 60 * 60 * 24 * 7;
if (isset($_COOKIE['ccsvissource']))
{
}
else
{
if (isset($_GET[gclid]))
{
setcookie('ccsvissource', 'Google', $bestbefore);
setcookie('ccsvismedium', 'Adwords', $bestbefore);
}
elseif (stripos($origin, 'facebook') !== false)
{
setcookie('ccsvissource', 'Advertising', $bestbefore);
setcookie('ccsvismedium', 'Facebook', $bestbefore);
}
elseif ($_GET[utm_medium] == "111")
{
setcookie('ccsvissource', 'Advertising', $bestbefore);
setcookie('ccsvismedium', 'emailcampaign', $bestbefore);
}
else
{
setcookie('ccsvissource', $origin, $bestbefore);
setcookie('ccsvismedium', 'Unknown', $bestbefore);
}
?>
footer.php:
<?php
$mktSource = $_COOKIE['ccsvissource'];
$mktMedium = $_COOKIE['ccsvismedium'];
?>
<p class="hide-me" id="mkt-source"><?php echo $mktSource; ?></p>
<p class="hide-me" id="mkt-medium"><?php echo $mktMedium; ?></p>
<script type="text/javascript">
$(document).ready(function(){
var mktSource = $('#mkt-source').text();
var mktMedium = $('#mkt-medium').text();
$('#hid-ms').val(mktSource);
$('#hid-mm').val(mktMedium);
});
</script>
The values will then get passed into the user's application form, with our lead management system doing the rest.
The problem is inconsistency - sometimes the cooks are being set, and sometimes not. Is there a certain circumstance client-side which will prevent cookies from being set?
I understand the user may have cookie tracking switched off, and have accounted for this - the volume of empty cookies is still too high so I think I'm missing something.
Please let me know if you need any further information!
Many thanks.

With new wordpress i've also face the same problem, my custom cookies wasn't set where my code was correct but somewhere i found that sometimes custom cookies does not work. So finally i found this working example with wp_head hook.
Let suppose you want to set 2 different cookies like Area and currency you need this function with wp_head, i have use this in my personal projects. it working prefectly.
add_action('wp_head', 'my_setcookie');
function my_setcookie()
{
if (!empty($_REQUEST['area'])) {
$area_set = ($_REQUEST['area']);
setcookie('area', $area_set, time() + 3600, COOKIEPATH);
}
if (!empty($_REQUEST['currency'])) {
$currency_request = ($_REQUEST['currency']);
setcookie('currency_cookie', $currency_request, time() + 3600, COOKIEPATH);
}
}

Related

Tracking non logged-in users in Yii/PHP

I am trying to track the actions of all non-logged in users on my site. The aim is to store this activity so that I can add it to their profile when they do create an account.
I am using the Behaviour below to assign new users a cookie and use that cookie as the basis of a "temp user" row in my Users table. This way a user can straight away start interacting with my API.
This seems to work fine. However, I am seeing loads more "temp user" rows being created in my DB than I have visitors to the site - about 2500 compared with around 500 visits yesterday (according to Google Analytics).
Is there anything wrong with the behaviour below, or am I doing something else wrong? Is there a better way?
<?php
class ApplicationBehavior extends CBehavior
{
private $_owner;
public function events()
{
return array(
'onBeginRequest' => 'setCookies'
);
}
public function setCookies()
{
$owner = $this->getOwner();
if ($owner->user->getIsGuest() && !isset(Yii::app()->request->cookies['dc_tempusername'])):
$tempusername = genRandomString(20);
$tempuser = new User();
$tempuser->username = $tempusername;
$tempuser->email = "noemailyet#tempuser.com";
if (isset(Yii::app()->request->cookies['dc_tempusername'])) {
$tempuser->name = Yii::app()->request->cookies['dc_tempusername']->value;
} else {
$tempuser->name = "CookieBasedTempuser";
}
$tempuser->points = 1;
$tempuser->firstip = $_SERVER['REMOTE_ADDR'];
if ($tempuser->validate()) {
Yii::app()->request->cookies['dc_tempusername'] = new CHttpCookie('dc_tempusername', $tempusername);
$cookie = new CHttpCookie('dc_tempusername', $tempusername);
$cookie->expire = time() + 60 * 60 * 24 * 180;
Yii::app()->request->cookies['dc_tempusername'] = $cookie;
$tempuser->save();
} else {
echo CHtml::errorSummary($tempuser);
}
endif;
}
}
?>
Check if cookies are enabled first:
Check if cookies are enabled
If we're correct, every time you see that the user is a guest and does not have a cookie then you're creating a new temp user.
Why not check to see if a cookie is set first, if so then create the temp user?
You would end up needing to set 2 cookies: initial temp cookie to check against, and then your 'dc_tempusername' cookie.
You could even go as far as using Browscap to check against known bots:
https://github.com/browscap/browscap-php
http://browscap.org/
You'll need to be able to define browscap in your php.ini

PHP Mobile Detection

I have a problem with the Mobile Detection Script.
There are two scenarios:
First the script should detect if it's a mobile or not. If mobile, than redirect to another page (this works fine).
The second query should determine, if the person is on the root page or not. If it's not the root page, the layout should be the classic one. (no redirection)
But when I add this line there won't be anymore redirection, even if I open the root page on a mobile.
I also tried to destroy the session on the google_mobile.php (redirected page) and set the $_SESSION['layoutType'] = 'mobile', but anyway the session is set to classic when I open the root page.
Thanks for your help!
Here is the script:
session_start();
require_once 'Mobile_Detect.php';
function layoutTypes() {
return array('classic', 'mobile');
}
function initLayoutType() {
// Safety check.
if (!class_exists('Mobile_Detect'))
return 'classic';
$detect = new Mobile_Detect;
$isMobile = $detect->isMobile();
$layoutTypes = layoutTypes();
// Set the layout type.
if (isset($_GET['layoutType'])) {
$layoutType = $_GET['layoutType'];
} else {
if (empty($_SESSION['layoutType'])) {
$layoutType = ($isMobile ? 'mobile' : 'classic');
} else {
$layoutType = $_SESSION['layoutType'];
}
//check if it's the root page
if ($_SERVER['REQUEST_URI'] != "/")
$layoutType = 'classic';
}
// Fallback. If everything fails choose classic layout.
if (!in_array($layoutType, $layoutTypes))
$layoutType = 'classic';
// Store the layout type for future use.
$_SESSION['layoutType'] = $layoutType;
return $layoutType;
}
$layoutType = initLayoutType();
if ($_SESSION['layoutType'] == 'mobile') {
header("Location: www.example.com/google_mobile.php");
exit;
}
I've tested your code, it seems to work as you described. I'd guess it is a session issue.
session_destroy() does not clear your previous session state in the immediate session. That means your $_SESSION would still be "dirty" in a script even if session_destroy() is the first line in it. It's safer to clear cookies from your browser instead.
One other possible problem would be query string. You're checking the REQUEST_URI and it includes any query string on URI. "/?foo=bar" is certainly not "/". You may want to check SCRIPT_NAME (i.e. $_SERVER['SCRIPT_NAME'] == 'index.php) instead.

PHP - Give access to only one device at a time

I want to make a simple website on a local server that would be accessed by only one device at a time. I've found user management scripts but they are more more complex than what I am searching for. I don't need it to be password protected or have different kind of users and/or rights. Juste a page where only one person at a time can connect.
Is there a way to make it in PHP ?
I've first searched for an option in my server (lighttpd) then for some kind of htaccess but I think PHP is the only way to do it right.
Thank you for your consideration.
According to my comment above:
<?php
$minInterval = 5 * 60; // 5 minutes
$access = true;
if (file_exists('visitor')) {
$visitor = unserialize(file_get_contents('visitor'));
if ($visitor['addr'] != $_SERVER['REMOTE_ADDR']) {
if ($visitor['time'] + $minInterval >= time()) {
$access = false;
}
}
}
if (!$access) {
exit('Access denied.');
} else {
// Update last visitor data
file_put_contents('visitor', serialize([
'addr' => $_SERVER['REMOTE_ADDR'],
'time' => time()
]));
}

browser cookie. and other options for achieve the same effect

How would I create a cookie that would store the randomly added body class for one browser session or for one day. My intention would be to randomly give every user a body background image and then store that image so that it won't change every pagereload or when they go to page 2.
Site http://www.midnightlisteners.com/
i am using this jQuery plugIn: https://github.com/carhartl/jquery-cookie
but it does not work somehow
My jQuery code:
the code that I use:
if($.cookie('userBackground') === null) {
var classes = ['body-bg1','body-bg2', 'body-bg3', 'body-bg4'];
var randomnumber = Math.floor(Math.random()*classes.length);
var chosenClass = classes[randomnumber];
$('body').addClass(chosenClass );
$.cookie('userBackground', chosenClass, { expires: 7, path: '/' });
} else {
//todo verify cookie value is valid
$('body').addClass($.cookie('userBackground'));
}
Errors i am getting:
Uncaught ReferenceError: require is not defined
Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'cookie'
Are there other ways to do this? php? pure javascript?
UPDATE:
If you want to make it only last the length of the session then just use the session instead:
<?php
if(!isset($_SESSION['bgclass'])) {
// lets make our cookie!
$classes = array('body-bg1','body-bg2', 'body-bg3', 'body-bg4');
$classIndex = array_rand($classes);
$_SESSION['bgclass'] = $classes[$classIndex];
}
$bgclass = $_SESSION['bgclass'];
?>
This way after the session times out or the browser is closed the user will get a new bgclass value.
If you already have php running i would do it that way. Much better to handle this server side if you can. Its also a bit simpler:
<?php
if(!isset($_COOKIE['bgclass'])) {
// lets make our cookie!
$classes = array('body-bg1','body-bg2', 'body-bg3', 'body-bg4');
$expire = time()+(60*60*24); // expire 1 day form now
$classIndex = array_rand($classes);
$bgclass = $classes[$classIndex]; // had $class here as opposed to $classes
setcookie('bgclass', $bgclass, $expire);
} else {
$bgclass = $_COOKIE['bgclass'];
}
?>
<html>
<head></head>
<body class="<?php echo $bgclass ?>">
...
</body>
</html>
The key thing to remeber is that a cookie is essentially a response header so you have to do this before headers have been sent (ie. anything from php is output to the browser).

PHP redirection issue

I have a program that prints reports for a user id list. The program is supposed to print reports one by one for users on the list uploaded. The problem is that when I was running the printing process and getting to print the report with indexInList=30, I got error:
This webpage has a redirect loop
The webpage at http://127.0.0.1/content/8520?print=1&bulkprinting=1&filename=/private/var/tmp/phpHRXEw8.moved&indexInList=30&nopeergroup=1&nolabpage=0&hideScreeningOnly=1&showOnlyScreening=0&hideHoldMailing=1 has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
I tried to clean the cookie but still keep getting the same error.
I attached some code here and hope anyone can help me:
$sessionData['first_name'] = $foundUser->first_name;
$sessionData['last_name'] = $foundUser->last_name;
// Overwrite $_REQUEST variable with parameters before including
// the hpa report
$_REQUEST = array(
'user_id' => $foundUser->id,
'bulkprinting' => true
);
if($nopeergroup) { $_REQUEST['nopeergroup'] = $nopeergroup; }
if($nolabpage) { $_REQUEST['nolabpage'] = $nolabpage; }
if($hideScreeningOnly) { $_REQUEST['hideScreeningOnly'] = $hideScreeningOnly; }
if($showOnlyScreening) { $_REQUEST['showOnlyScreening'] = $showOnlyScreening; }
if($hideHoldMailing) { $_REQUEST['hideHoldMailing'] = $hideHoldMailing; }
$includeValue = include __DIR__.'/../hpa/hpa.php';
$url = sprintf(
"/content/8520?print=1&bulkprinting=1&filename=%s&indexInList=%s" .
"&nopeergroup=%s&nolabpage=%s&hideScreeningOnly=%s" .
"&showOnlyScreening=%s&hideHoldMailing=%s",
$filename, $indexInList, (int)$nopeergroup, (int)$nolabpage,
(int)$hideScreeningOnly, (int)$showOnlyScreening, (int)$hideHoldMailing);
if($hradata[0] !== false) {
$sessionData['hra_id'] = $hradata[0]['id'];
}
if($screeningdata[0] !== false) {
$sessionData['screening_id'] = $screeningdata[0]['id'];
}
if($includeValue !== 1) {
// Redirect to URL
$sessionData['message'] = $messages_set[$includeValue];
$_SESSION['printing_set'][] = $sessionData;
redirect($url);
}
$sessionData['markAsMailed'] = true;
$_SESSION['printing_set'][] = $sessionData;
?>
<script type="text/javascript">
function waitPrint() {
window.print();
var t = setTimeout("timed()", 1000);
}
function timed() {
window.location.replace("<?php echo $url ?>");
}
if(window.attachEvent) {
window.attachEvent("onload", waitPrint);
} else if(window.addEventListener) {
window.addEventListener("load", waitPrint, false);
}
</script>
Sounds like you have a lot of files that need printing!
You may be able to alter your browser settings (I seem to remember you can in Firefox) to allow more than 30 loops.
Alternatively, you could always limit your code to 30 loops then wait for further user interaction to proceed to the next 30.
The 3rd option is to always create a Word document or PDF with one report on each page, then save the file and print it - a little more hassle (in a way) but at least you'll be able to print everything at once.
In order for $includeValue to be set to anything, the file __DIR__.'/../hpa/hpa.php' must have a return statement inside of it, as demonstrated in the PHP documentation for include, example 5. include will only return a value when called if the included file returns a value.
If your script still produces an infinite loop, your logic within the included file is incorrect and it is consistently producing a value that is not 1.
Essentially, here is the code that your question boils down to:
$includeValue = include __DIR__.'/../hpa/hpa.php';
if($includeValue !== 1) {
// Redirect
}
Browsers have checks built-in to help you when sites are misconfigured into a redirection loop, and 30 must be the limit for the browser you're using. You've built a redirection loop on purpose, but the browser doesn't know that. Instead of using the window.location.replace() method, how about a form that automatically submits? That should look different to the browser, and allow your loop to progress as designed.
<script type="text/javascript">
function waitPrint() {
window.print();
var t = setTimeout("timed()", 1000);
}
function timed() {
window.reloadForm.submit();
}
if(window.attachEvent) {
window.attachEvent("onload", waitPrint);
} else if(window.addEventListener) {
window.addEventListener("load", waitPrint, false);
}
</script>
<form name="reloadForm" action="<?php echo $url ?>">
</form>

Categories