I'm trying to redirect a user if they access a page more than 5 times. So the basic idea is if a user is not logged in on my site and they are browsing a users profile (profile.php) then this counts the number of hits that cookie session has had and redirects to a page to say sign up or something.
I'm new to php and wouldn't know where to start. Could someone please show me.
This is very easy to implement in PHP. Just set a session with the count value and read it after each access.Then you can redirect if the count is 5 or more. Below is a sample code
!session_id() ? session_start() : null; if(!isset($_SESSION['page_access_count'])){ $_SESSION['page_access_count'] = 1; }elseif($_SESSION['page_access_count'] >= 5){ // redirect to signup page header('Location:/signup.php'); exit; } // increase the page access session value $_SESSION['page_access_count']++; ...
Basically you should be able to set a counter in a session variable in server-side or a cookie. on each visit to the profile page increase that counter. if that counter is greater than 5
then use the php header
function to redirect the user to your signup page. here is a quick code hint for you using session variable to achieve this:
if(! isset($_SESSION["ProfileVisitCount"])){
$_SESSION["ProfileVisitCount"] = 1;
}
$_SESSION["ProfileVisitCount"]++;
if($_SESSION["ProfileVisitCount"] > 5){
header("Location: http://domain.com/signup");
exit();
}
Also be sure to start the php session prior to these codes using session_start()
.
The same thing can be achieved using cookies like this:
if(! isset($_COOKIE["ProfileVisitCount"])){
setcookie("ProfileVisitCount", "1", time()+3600);
}
if($_COOKIE["ProfileVisitCount"] > 5){
header("Location: http://domain.com/signup");
exit();
}
else {
setcookie("ProfileVisitCount", ($_COOKIE["ProfileVisitCount"] + 1), time()+3600);
}
Use cookies. Here's how I'd do it in PHP:
<?php
if (!isset($_COOKIE["cookie1"]))
{
setcookie(
"cookie1",
"1",
time() + (20 * 365 * 24 * 60 * 60),
'/',
'.example.com'
);
}
else{
setcookie(
"cookie2",
"2",
time() + (20 * 365 * 24 * 60 * 60),
'/',
'.example.com'
);
else{
setcookie(
"cookie3",
"3",
time() + (20 * 365 * 24 * 60 * 60),
'/',
'.example.com'
);
}
else{
setcookie(
"cookie4",
"4",
time() + (20 * 365 * 24 * 60 * 60),
'/',
'.example.com'
);
}
else{
setcookie(
"cookie5",
"5",
time() + (20 * 365 * 24 * 60 * 60),
'/',
'.example.com'
);
}
else
{
header("Location: http://domain.com/signup");
}
}
?>
Make sure to replace .example.com with your domain name. And keep the "." instead of "www." if you want it to work when you run it with a domain name with "www", or without it.
Tell me if it works... I can always modify it.