can we know from which page the user visited this page in php?

Clash Royale CLAN TAG#URR8PPP
can we know from which page the user visited this page in php?
Is it possible in PHP to know which page a user came to a particular page from?
For example, the first page is index.php and the second page is index2.php.
index.php
index2.php
Now the user goes to index.php from index2.php using a hyperlink which is on index2.php.
index.php
index2.php
index2.php
Now I want to store the link in a database, for the page the user came to index.php from, in this case index2.php.
index.php
index2.php
4 Answers
4
If it's on your own site you might as well use the session, HTTP_REFERER is prone to spam or very likely simply not set, you can't trust it.
HTTP_REFERER
Maybe do something like:
<?php
session_start();
if (!isset($_SESSION['last_page']))
// first visit (landing)
else
// not first page
// insert into db
// set tracking for next page
$_SESSION['last_page'] = [
'page' => $_SERVER['REQUEST_URI'],
'time' => time() // know how long user was on the last page
];
Place it somewhere its hit on each page.
sidenote, using websockets is also an option..
– Lawrence Cherone
Aug 12 at 10:39
Sir I want to do this with two different websites? Plz help me out sir?
– user10211847
Aug 12 at 11:06
Don't move the goal posts, you didn't mention two different sites, then your only option is to use HTTP_REFERER (after checking domain origin) or if on same domain use cookies, then continue off as-above using session.
– Lawrence Cherone
Aug 12 at 11:09
Thank you sir....it is not on the same domain..I will use http-referer for this.
– user10211847
Aug 12 at 11:11
no worries, make sure you treat it as user input, I've seen many interesting things placed in the referer, from XSS to ads and ascii art..
– Lawrence Cherone
Aug 12 at 11:14
You can access the last page URL (which in this case will be the origin) using $_SERVER['HTTP_REFERER'].
$_SERVER['HTTP_REFERER']
If you only want to track sites that are from you, like index.php and index2.php then you should use a session and set the value on each page, its more precise than the $_SERVER['HTTP_REFERER'] variable.
index.php
index2.php
$_SERVER['HTTP_REFERER']
$_SERVER['HTTP_REFERER'] can easily be spoofed be the user.
$_SERVER['HTTP_REFERER']
Can please give me a demo program?
– user10211847
Aug 12 at 11:02
You can use the global variable $_SERVER, it should tell you where the user came from.
You can use it like this in your index.php:
$_SERVER
echo $_SERVER["HTTP_REFERER"];
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
session or referer
– mplungjan
Aug 12 at 10:20