Search code examples
phpcookiestimesetcookie

Make Cookie expire according to URL-variable with PHP


I'm working on a new product/website, where the homepage (not the subpages) should be closed for visitors until the website launches. The launch-date should be read out of the URL like this:

website.com/some-subpage?launch=0421

In this example the homepage should be accessible to the visitor from the 21th (21) of April (04).

For this I want to do that if somebody visits "some-subpage" (or any other subpage, doesnt matter), a cookie should be set like this:

  • Cookie-Name: Launch
  • Cookie-Value: 0421
  • Cookie expiration: At the launch, so in this case the 21th of April

Here is what I have so far:

<?php
if ($_GET['launch'] != "null") {
date_default_timezone_set('Europe/Berlin');
$launchdate = $_GET['launch'];

$launchdatenew->format('*********'); // Here I probably need to convert the "0421" to a readable time, but I dont know how
// or probably using this version?
$launchdatenew = date_format(date_create_from_format('m d', $launchdate), '*********'); // Here I probably need to convert the "0421" to a readable time, but I dont know how

setcookie("Launch", $launchdate, $launchdatenew, "/"); // The Cookie-Name should be "Launch", the value "0421", and it should expire when the launch starts

} ?>

Could you please help me finishing this? I don't know how to convert the "0421" into a new format that could be set as the expiration-date for the cookie. My PHP-skills are almost zero unfortunately.

Thank you very much! Bye, Imre


Solution

  • I'll show you then how to set the expire on that cookie based off the date in $launch.

    Assuming that will always be in format 'mmdd' then with some simple string manipulation...

    $launchDateStr = '0421';
    
    $launchTime = mktime(0, 0, 0, substr($launchDateStr, 0, 2), substr($launchDateStr, 2));
    
    $ttl = $launchTime - time(); //just an example... find seconds between now and launch
    
    setcookie("launch", $launchDateStr, $launchTime, "/");
    

    caveats... this ignores year. You should not trust user data. All this can be spoofed.