Using PHP to Dynamically Hide Content after an Expiration Date

If you need to pull something offline by a specific date, what happens when no one's around to remove the content? People get sick or maybe a deadline was overlooked and you're out of the office. Well you could just suck it up, go into work, and remove the registration form from the website. Or you could write a little PHP code to disable the form (or any other information) for you.

Before getting into any code, it should be said that you'll need access to a web server that supports PHP for the following solution to work. It's also helpful if you have a basic knowledge of how PHP works. Of course, if you have any questions feel free to post them in the comments section. Now on to the code.

Since we'll be dealing with dates, it's a good idea to set the time zone. For this example, we'll use U.S. Central time:

date_default_timezone_set('America/Chicago');

We'll also need a couple variables to store the current and deadline timestamps:

$current_ts = time();
$deadline_ts = mktime(0,0,0,5,1,2011);

Now let's say we have a registration form that needs to be disabled after the deadline which was set above to May 1, 2011. To do that, we need to see if the current timestamp is greater than the deadline. If it is, we'll let the user know that we're no longer accepting registrations. Otherwise the registration form is shown.

if($current_ts > $deadline_ts) {
     //message about the form being disabled
} else {
     //code for the registration form
}

With the code in place, it's a good idea to make sure it works. Since we don't have a time machine, we'll need to find another way to change the current timestamp. Let's use the mktime() function again:

$current_ts = time();
$current_ts = mktime(0,0,0,5,1,2011);

You can now test whatever date you want by changing the mktime() function arguments. When testing, make sure that at least one date before, during, and after the deadline date works.

Final Code

//SET THE TIME ZONE
date_default_timezone_set('America/Chicago');

//CREATE TIMESTAMP VARIABLES
$current_ts = time();
$deadline_ts = mktime(0,0,0,5,1,2011);

//IF THE DEADLINE HAS PASSED, LET USER KNOW…ELSE, DISPLAY THE REGISTRATION FORM
if($current_ts > $deadline_ts) {
     //message about the form being disabled
} else {
     //code for the registration form
}

Related Resources

0 Comments

There are currently no comments.

Leave a Comment


Warning: Undefined variable $user_ID in /home/cyberscorp/webdev.cyberscorpion.com/wp-content/themes/scorpbytes/comments.php on line 72