不再显示广告案例(php操作cookie)
1,页面简单结构搭建
ad.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ height:100px; background-color: #e0daff; } div > a{ float:right; } </style> </head> <body> <div> <a href="">不再显示广告</a> </div> </body> </html>
2,方式一,创建一个 close.php的页面
ad.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ height:100px; background-color: #e0daff; } div > a{ float:right; } </style> </head> <body> <?php if (empty($_COOKIE['hide_ad']) || $_COOKIE['hide_ad'] !== '1'): ?> <div> <a href="close.php">不再显示广告</a> </div> <?php endif ?> </body> </html>
close.php (只要有人来请求我,意味着这个人不想再看到广告,我们就给这个用户开张小票 )
<?php setcookie('hide_ad', '1'); header('Location: ad.php');
3,方式二,传参
ad.php
<?php if(isset($_GET['action']) && $_GET['action'] === 'close-ad'){ setcookie('hide_ad' , '1'); $_COOKIE['hide_ad'] === '1'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ height:100px; background-color: #e0daff; } div > a{ float:right; } </style> </head> <body> <?php if (empty($_COOKIE['hide_ad']) || $_COOKIE['hide_ad'] !== '1'): ?> <div> <a href="ad.php?action=close-ad">不再显示广告</a> </div> <?php endif ?> </body> </html>