简体   繁体   中英

PHP cookie setting but not recognizing

Bear with me. Over the years I've begun to understand that I'm terrible at explaining myself.

I have a site with a page full of Spotify download links. On their first visit, people need to fill out a contact form to capture their email before being able to download. After that, they can download as many playlists as they want, forever.

  1. When they click on the link the first time, a popup window opens the form.
  2. After filling it out, the form redirects them to a new URL that sets the cookie (../playlists-for-events/?download=true). It also sets a variable so that the page doesn't need to be reloaded to download.
  3. Now that the cookie is set, the playlists can be downloaded on any visit to the page (../playlists-for-events).

The cookie is setting as it's supposed to, but the PHP I've written isn't working.

The cookie

<?php $cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);
if(isset($_GET['download']) && $_GET['download'] == 'true'){ 
    setcookie($cookie_name, $cookie_value, $date_of_expiry, '/',null,false,true);
    $_COOKIE['spotify-download'] = 'allow';
} ?>

And the PHP that basically says "if the cookie isn't set, open the popup, else, start the download"

<?php if(!isset($_COOKIE['spotify-download'])) { ?>
    <script type="text/javascript">function zforms_open_window(...)></script><a></a>
<?php } else { ?>
    <a href="<?php echo $link; ?>" target="_blank"></a>
<?php } ?>

Help?

I've tested your code and it works fine, but the cookie can not be read until it is set. ie User redirected to /?download=true to set the cookie, it then needs to reload the page or go somewhere else that can now read the cookie.

<?php
$cookie_name = 'spotify-download';
$cookie_value = 'allow';
$date_of_expiry = time() + (10 * 365 * 24 * 60 * 60);

if( isset( $_GET['download'] ) && $_GET['download'] === 'true' ){
    setcookie($cookie_name, $cookie_value, $date_of_expiry);
    $_COOKIE[$cookie_name] = $cookie_value;
}

if( isset( $_COOKIE[$cookie_name] ) && $_COOKIE[$cookie_name] === $cookie_value) {
    echo "You have access!";
} else {
    echo "Access denied.";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM