In this PHP tutorial, we will show you how to automatically add a copyright year to the footer of your website.
We will also provide you with a simple code snippet that you can copy and paste.
In PHP, you can dynamically get the current year like so:
//This print out the current year. echo date("Y");
By using PHP’s date function, we can also determine which year range we should display in our copyright notice.
Take a look at the following example:
//Specify a start year. This is the year that your website was founded. $startYear = 2012; //Get the current year. $thisYear = date("Y"); //By default, set the date to the start year. $yearInfo = $startYear; //If the start year and the current year are not the same, add a hyphen. if($startYear != $thisYear){ $yearInfo = $startYear . "-" . $thisYear; } //Print out the year info echo $yearInfo;
In the example above, we set 2012 as our “start year”. If you plan on using the code above, you will need to change the $startYear variable to match the year that your company or website was founded.
If the $startYear is not the same as the current year, then the code will display a date range. For example, 2012-2022.
However, if the start year is the same as the current year, then we will display a single year. This is because printing out “2022-2022” in the footer would look unprofessional.
To make things even simpler, we have created the following copyright function.
function copyright($name, $startYear = null){ $thisYear = date("Y"); if(is_null($startYear) || $thisYear == $startYear){ return "© ". date("Y") . " $name All Rights Reserved"; } return "© $startYear-" . date("Y") . " $name All Rights Reserved"; } //Examples echo copyright('ThisInterestsMe.com', 2011); echo copyright('ThisInterestsMe.com'); echo copyright('ThisInterestsMe.com', 2021);
As you can see, the first parameter is the name of the website. This can also be your personal name.
The second parameter is the start year. Note that the start year is an optional parameter. If you decide to omit the start year, then the code will always print out the current year.
We’ve also taken the liberty of adding the copyright symbol, as well as the “All Rights Reserved” text. However, you can change this if you need to.
If you’re not interested in adding functions and you’re wanting to keep it confined to one line of code, then you can use the following snippet.
© <? (2012 == date("Y")) ? date("Y") : 2012 . "-" . date("Y"); ?> ThisInterestsMe.com - All Rights Reserved
Obviously, you will need to change 2012 to match the start year of your website.