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. 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.

Background

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.

The Code

Since we're dealing with dates, let's set the time zone. For this example we'll use U.S. Central time:

date_default_timezone_set('America/Chicago');

We'll also need 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
}

Testing the Code

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); //<-- change this date to test the code
$deadline_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

<?php
//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

2 Comments

  • #2 Tony on 10.04.17 at 10:55 am

    Awesome. Simple yet effective!Easy to change time and message… Great Job!!!

  • #1 Thomas on 06.16.16 at 1:53 pm

    Great code ! I'm testing it on my page, for me it's simple, clean ana I can adjust it as I want to :) I'm using it to show my clients my special offers.

Leave a Comment