I have Facebook ads that bring users to a website. Each ad has a different tracking ID:
www.scaredycut.com/index.php?azn=TRACKING_ID
Once on the site, the tracking ID is inserted into the link to Amazon (so as to indicate a referral sale if something is bought). If a user comes to the site directly (not through an ad), they receive the tracking ID scaredycut-direct.
I set up two lines of defense: first, a cookie is created that contains TRACKING_ID. In case cookies are disabled, the url tag is still there (azn=TRACKING_ID), up for grabs.
In index.php, an initial php file that redirects to the home page:
# capture TRACKING_ID from URL
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parsed_url = parse_url($actual_link);
$azn = substr($parsed_url[query], 4);
# save tag into a cookie set to expire in 30 days
setcookie ("ScaredyCut_AmazonReferral1", $azn,time()+60*60*24*30);
In the Wordpress' functions.php:
# create TRACKING_ID variable from url tag
$urltrackingID = $_GET["azn"];
# create TRACKING_ID variable from cookie
$cookietrackingID = $_COOKIE["ScaredyCut_AmazonReferral1"];
# logic: which variable to use?
if ($cookietrackingID == NULL) { // if there's no cookie,
if ($urltrackingID == NULL) { // if they came directly,
$trackingID = "scaredycut-direct"; // use tracking ID "scaredycut-direct"
} else { // otherwise, cookies are disabled, so use url tracking ID
$trackingID = $urltrackingID;
}
} else { // otherwise, cookie are enabled, so use cookie tracking ID
$trackingID = $cookietrackingID;
}
In header.php:
# declare global tracking ID var
<?php
global $trackingID;
?>
And then, I just insert $trackingID into the link's href. (I give precedence to cookies. If they have cookies on, I'd rather make a cookie in case they leave and come back later.)
My method is working, for the most part (surprising for the novice I am). Sessions are being tracked correctly, but I have a very strong suspicion that some sessions are being mistakenly tracked as "scaredycut-direct" instead of their ad-specific tracking ID.
The site is, for the most part, a single page. There isn't really a way for a user to lose a url tag by navigating to another page.
Is there a way that sessions are being marked incorrectly as "scaredycut-direct", and bypassing the cookie AND the url tag methods? Is there another way to do this?
Thanks so much for the help.
A third option to add is $_SERVER['HTTP_REFERER'], but it's set by the browser and isn't reliable. It also means that if they come from google, it'll be set to google.
Other than that, it looks okay.
Related
I am running woocommerce/wordpress and noticed customers refreshing the thankyou page cause google analytics to record multiple transactions.
The url they visit is: /checkout/order-received/24420/?key=wc_order_a5m1jzQDJLjjr
I figure i need to Set a cookie using that order number. If cookie exists then redirect before analytics code runs. Thus preventing reloads of thank you page.. (i hope)
I don't know who to extract the number 24420 from the url and set a cookie. Redirecting on Cookie i can figure out.
thanks
/J
To retrieve the Order ID
$order_id = wc_get_order_id_by_order_key( $_GET['key'] );
I would suggest to use a session instead of cookie so you can do something like
if(isset($_SESSION['order_'.$order_id])) {
header("Location: /where-you-want");
die;
} else {
$_SESSION['order_'.$order_id] = 1;
}
Please note that both Session and Cookies need to be set before any other output on the page, so be sure that the code you're running is executed before any HTML is printed.
i have some problem, i create a page to read news and if the page open it will be update in my database field for news_read +1 but i want if page refresh by user isn't +1
this is my query in page
$q="SELECT*FROM t_news WHERE news_id=$b_id";
$dataJ=mysql_query($q);
$a=mysql_fetch_array($dataJ);
$plus=$a['news_read']+1;
mysql_query("UPDATE t_news set news_read=$plus WHERE news_id=$a[news_id]");
anyone know, how to disable $plus=$a['berita_dibaca']+1; after refreshing the page?
UPDATE
UPDATE
thanks all ,i have solved my problem with session
i put
if ($_SESSION['load']==1){
$_SESSION['load']=0;
}
in all of my page except read.php and i put
if ($_SESSION['load']==0)
{
//QUERY
}
$_SESSION['load'] = 1;
in read.php
Method 1.
Save cookie, if user has cookie don't update database.
Method 2. (better)
Save users who have already viewed this article, and if user is in list do not update database.
Tip:
UPDATE t_news set news_read = news_read + 1 WHERE news_id = $a[news_id]
to avoid useless queries.
That's not a question to solve with sql, but with HTTP.
There is basically no difference between a refresh of a page and the inital request. There both just HTTP commands. There may be a difference in the headers of both requests but you can't always be sure they are present. So using the referer is probaly not a great idea.
Beside Valdas answer with the cookie you may also use the session of your user and set a flag there. (Although most session implementations do also use cookies, but in another way)
This method doesn't require a user to be logged in:
session_start(); // ignore if you're already using sessions
if( !isset($_SESSION['has_read_news'])) $_SESSION['has_read_news'] = array();
if( !isset($_SESSION['has_read_news'][$b_id])) {
mysql_query("UPDATE `t_news` SET `news_read`=`news_read`+1 WHERE `news_id`=".$b_id);
$_SESSION['has_read_news'][$b_id] = true;
}
Note that it's not completely foolproof (clearing the session cookie will allow the user to be counted again) but overall it should be plenty good enough.
Basically I want to grab an id send via the url (ex. www.website.com/?id=432432) and take it accross my website till the user hits the contact page. I created a variable and a session variable
session_start();
$getId = $_GET["id"];
$_SESSION['session_browser_test'] = $getId;
$adv_id = $_SESSION['session_browser_test'];
and used
echo $adv_id;
on my index.php Joomla template so it applies to all the pages.
But the issue is when i go to www.website.com/?id=432432 it echos the id on my web page, but if I click on the next link to go to another page (ex. www.website.com/nextPage) it doesnt hold the session value from the previous page. Why is that? and how can I carry the ID through out the site?
you will not get an id from URL on next page, likely
echo $getId;
instead you need to use id from session like,
$_SESSION['session_browser_test']; // your id stored in session
Start the session in each page
session_start();
In order to access the variable in a session, you have to call the $_SESSION variable.
echo $_SESSION['session_browser_test'];
HTTP is stateless, so you have to do something to remember your variable throughout the website .
make sure you correctly use session , like session_start();
when you send your id through get method ,it works, but when you go to any other page ,it doesn't make any sense to remember this.
use this for send id through pages:
<?php echo get_permalink(910); ?>?userid=<?php echo $value['userId'];?>
send this in url and use on next page as:
$sql = "select * from `wp_pelleresuser` where userId =".$_GET['userid'];
using this approach you can use a single variable on every page you want without using session. try google to how wordpress manage variable through all pages without using session. it will help you.
happy coding!
Start
session_start();
(if not started) in the index.php in root of your app (session probably will start on every pages) and then call (when desired):
$_SESSION['session_browser_test'];
instead of assi8gning this sess var to your own variable and then calling it in different places.
if(isset($_GET["adv_id"])){
$_SESSION['session_browser_test2'] = $_GET["adv_id"];
$adv_id = $_SESSION['session_browser_test2'];
}
else {
$adv_id = $_SESSION['session_browser_test2'];
}
Can someone tell me why the session vars are not passing between pages? They were working up to 2 days ago. Now its not? There is a third party system that logs users in based on the third party system. I direct users to the login page with the return url. The third party system logs a user in and passes their id and a token generated on their end and returns them to my site with the id and the token in the url.
If sessions are not set i try and grab the id and the token from the url and set the sessions. (working) I then generate my own token to validate against the token passed from the third party system (working) when i go to click to another page the sessions i set are not empty (????)
Here is my code:
<?php
session_start();
// FUNCTION TO PASS THE URL THE USER IS ON SO THEY COME
// BACk TO THIS PAGE AFTER THE LOG IN. IF APPLICABLE
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
// DESTROY SESSION INFO IF TIMED OUT
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
}
// SET THE SESSIONS WITH INFO PASSED FROM
// LOGIN PAGE SENT AS A GET
if(isset($_SESSION['ID']) && isset($_SESSION['token'])) {}else{
$_SESSION['ID'] = $_GET['ID'];
$_SESSION['token'] = $_GET['token'];
}
// GENERATE MY TOKEN TO MATCH THE LOGIN SYSTEM TOKEN
$userIP = $_SERVER['REMOTE_ADDR'];
$secretkey = 'A Unique Key For The Logged In User Matching the Login System Passed From mydomain.com/login.php';
$algorithm = 'md5';
$mm = date('m');
$dd = date('d');
$mmdd = $mm.$dd;
$mytoken = strtoupper(hash($algorithm, $secretkey.$_SESSION['ID'].$userIP.$mmdd));
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
// THIS IS WHERE THINGS ARE GOING WRONG
// SESSION token IS NO LONG SET AFTER I Go To another page
// and my token isnt the same any more either because session ID
// is no longer set???
if($_SESSION['token']==$mytoken){}else{
header("location: https://mydomain.com/login.php?returnURL=".curPageURL());
}
?>
ok this is messed up. It has to be a problem on the hosting providers PHP setup i think because i created two pages. one called info with this code:
<?
session_start();
$_SESSION['ID'] = "112233";
$_SESSION['token'] = "mytoken";
print $_SESSION['ID'];
print $_SESSION['token'];
?>
info 2
and one called info2 with this code:
<?
session_start();
print $_SESSION['ID'];
print $_SESSION['token'];
?>
info
info created and printed the session ok. when i click the link to go to info2 the sessions dont print. Is this a hosting config problem?
As already mentioned, ensure you're calling session_start() on each page.
Additionally, are the scripts on different subdomains?? If they are you should set the INI value session.cookie_domain to .DOMAIN.EXT.
To further debug this whole situation, do some simple cookie watching. See if PHPSESSID is present as a cookie on both page requests, if it's not then this is your problem. You can't store cookies cross-domain unless you reconstruct them.
In response to your update, try doing this underneath your call to session_start():
echo session_id();
Confirm that it's the same on both pages. If not, check the value of session.cookie_domain like this:
echo ini_get('session.cookie_domain');
Is that set to anything? By default it should be blank, if it's set, especially not to your domain, this is the problem.
You can also try debugging the cookie value of PHPSESSID like I first suggested.
Check List
1. Make sure that you have used session_start(); in the next page.
2. Are you using .htaccess file?
if so remove the .htaccess file and check the same.
some time rewrite rules cause session probs...
3. If session is working fine and you have trouble only with token, then check the token sent in url is url_encoded.
it's not the hosting server issue...
check your URLs
if a user is login under "example.com" session will be stored for "example.com" and not "WWW.example.com" so if a link goes to www.example.com it will not have that session.
you can use htaccess to always set the url to "WWW.example.com" use below code for it
RewriteEngine On
RewriteCond %{HTTP_HOST} ^hemantjadhav.com$ [NC]
RewriteRule ^(.*)$ http://www.hemantjadhav.com/$1 [L,R=301]
(replace hemantjadhav with your domain name)
Check the size of the session file: (code taken from this post)
$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();
echo 'session file: ', $sessionfile, ' ';
echo 'size: ', filesize($sessionfile), "\n";
If your session file has zero size, make sure there is still disk space available on your server. That was the problem I had.
Check disk space with df -h on a linux server.
The answer to this is it was a hosting configuration error. Hosting company changed something and it has worked ever since.
In my case the solution was to have different parameter names in $_GET and $_SESSION.
$_SESSION["businessid"] = $_GET["businessid"]; // Leads to problems with session.
$_SESSION["business_id"] = $_GET["businessid"]; //Works perfectly.
It sounds strange but that's my experience.
The only answer for this problem is to use session_start(); on the top of every page. It will work fine. Else you might need to contact your hosting provider about this problem.
I would add that I got caught up with the same problem, except that in my case page was behind Varnish caching proxy and I missed out that configuration had a line where cookies were allowed only on specific paths, otherwise they would get removed with the following directive:
unset req.http.cookie;
Dont forget to also check your proxy settings.
I had session.cookie_samesite = "Strict" in my runtime file and was trying to bounce my user from Oauth2.0 back to my site and the PHP session ID was getting erased when the redirects hit. I removed this from my runtime file and it works fine now.
For anyone else searching this in frustration - another thing to check is the cookie_secure setting in php.ini.
If cookie_secure=1, cookies will only be sent and persist on secure connections. In our case, the site was deployed to an environment that did not have an ssl setup yet.
Set cookie_secure back to its default (0) - or get the site secured.
Make sure both pages are on the same domain.
Even www.site.com is different than site.com
If the above solutions do not work I suggest you do the following right before you set the new session variables:
session_destroy();
session_start();
and THEN save the new session variables that were not persisting before
In case this helps others:
If sessions are closed (e.g. with session_write_close() or session_commit()), then anything written to a session after that is not persisted.
Re-opening a closed session during the same request seems at best an uncertain endeavor. If anything has been sent back to the client already, session_start() seems to fail (return false) and nothing written to $_SESSION is persisted even if errors are not thrown.
Some may wonder why one would close sessions intentionally in the first place - the reason is "performance". Session resources (e.g. files with file-based sessions) are locked while the session is "open" and so for the duration of handling a request by default unless the session is specifically closed. If a response is taking awhile on the server (e.g. a long-running report query), a user (or multi-threaded UI) cannot complete another session-locking request while one is already in progress - so effectively all the session-based requests stack up sequentially and users are stuck waiting (the opposite of what is wanted with most modern UIs). The best answer, in most of my cases, is to release (close) the session as soon as possible (typically just after is has been read for the first time when handling a request) and keep it open for the duration of the request handling only if one needs to write to the session later (cases which should be minimized for performance of course).
You did not call session_write_close()
I am using $_SERVER['HTTP_REFERER']; to get the referer Url. It works as expected until the user clicks another page and the referer changes to the last page.
How do I store the original referring Url?
Store it either in a cookie (if it's acceptable for your situation), or in a session variable.
session_start();
if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];
As Johnathan Suggested, you would either want to save it in a cookie or a session.
The easier way would be to use a Session variable.
session_start();
if(!isset($_SESSION['org_referer']))
{
$_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}
Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.
Store it in a cookie that only lasts for the current browsing session
Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.
Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):
if(!isset($_COOKIE['origin_ref']))
{
setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}
Then you can access it later:
$var = $_COOKIE['origin_ref'];
And to addition to what #pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.