limiting a session

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tabatsoy
Forum Commoner
Posts: 29
Joined: Thu Mar 13, 2008 10:14 am

limiting a session

Post by tabatsoy »

Good Day Masters!
how can i limit a session in php. For example i want to limit a session to view my page only once.
thanks in advance.
www.WeAnswer.IT
Forum Newbie
Posts: 24
Joined: Wed Mar 19, 2008 6:33 pm

Re: limiting a session

Post by www.WeAnswer.IT »

You don't need a session, a cookie will work just fine. If the guest has cookies disabled, though, this code will not work.

The only way to make sure people only see your page once is by recording their IP address, and even that doesn't work every single time. To record the IP address, you would need a database.

But, to answer you question, put this at the top of the page you want people to visit only once:

Code: Select all

<?php
if(isset($_COOKIE['viewedAlready']))
{
    // this person has the cookie already
    die("Sorry, you have seen this page already.");
}
else
{
    // this person doesn't have the cookie
    // so we'll give it to them, then show the page
    setcookie("viewedAlready", "yes");
}
?>
Last edited by www.WeAnswer.IT on Mon Mar 24, 2008 2:45 pm, edited 1 time in total.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: limiting a session

Post by Christopher »

You could do the same thing with sessions. Just check to see if a session_id() exists yet. If it does then they have been to one page so deny access. You could also put a counter in either the session or a cookie and increment it to limit it to a specific number of page views. Make sure that there is session code on every page.
(#10850)
Post Reply