简体   繁体   中英

ive set a global cookie for my domain and when user navigates to a page i want to check if that cookie exists; if not then it will give them a 404

Im trying to set a cookie for my domain via php so that once the user tries to navigate to another specific webpage that will require that cookie it will either allow them to view the html contents or block access.

This is what ive put in the cookie.php file where i set the cookie

`<?php
$cookie_name = 'jevans';
$cookie_value = "0042";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>`

This is the page i want protected and only accessible if the cookie is present

`<?php
if(!isset($_COOKIE[$cookie_name])) {
exit;
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?> <html>content to be displayed</html>`

I expect for the script to check if the cookie exists and either allow or block based on whether they have that cookie.

Your protected page should look like this

<?php 
    $cookie_name = $_GET['cookie_name'] or $_POST['cookie_name'];

    if(!isset($_COOKIE[$cookie_name])) {
         exit; 
    } else { 
         echo "Cookie '" . $cookie_name . "' is set!<br>";     
         echo "Value is: " . $_COOKIE[$cookie_name]; 
    } 
?> <html>content to be displayed</html>

You use the $_GET for a get request or the $_POST for a post request. A sample get request should look like this http://localhost/test/protectedpage.php?cookie_name=jevans

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