我是PHP的新手,我正在尝试创建一个年龄验证表单,它将限制访问网站上的特定内容,如果一个用户在某个年龄以下。
这是HTML表单(index.HTML):
null
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="data.php" method="POST">
<input type="date" name="date" />
<input type="submit" name="submit" />
</form>
</body>
</html>
null
这是PHP脚本(data.PHP):
null
<?php //Age Validation Form
session_start();
if (isset($_POST['submit'])) { //Check if button clicked on form page
$date2=date("Y-m-d");//today's date
$date1=new DateTime($_REQUEST['date']); //user date
$date2=new DateTime($date2);
$interval = $date1->diff($date2); //check diff between dates
$myage= $interval->y; //resulting age
if ($myage >= 16){ //full access to website is granted
$_SESSION[$limited] = false;
header('Location: ../index.php');
}else{ //limited access is granted
$_SESSION[$limited] = true;
header('Location: ../index.php');
}
}else{ //if result page page is loaded without form submission
echo "Return to start page";
}
?>
<form action="index.html"> <!--Return to form page-->
<button type="submit">Return</button>
</form>
null
我希望能够将PHP文件中得到的有限变量携带到这个HTML文件中:
null
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function myFunction () {
var access = <?php echo $limited ?>;
var txt = document.createElement('h1');
txt.innerHTML = access;
document.body.appendChild(txt);
}
myFunction();
</script>
</body>
</html>
null
目前这只是为了测试,以确保它可以继续使用。我尝试了_session方法,但我似乎没有弄清楚它。
欢迎任何和所有可能的解决办法。
谢谢
您正在使用limited作为_session数组中的键。什么是有限的?我很确定,如果您将正确的值重新分配给limited,您可以使用以下命令访问_session中的值:
<?php $limited = 'MyAwesomeKey'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function myFunction () {
var access = <?php echo $_SESSION[$limited] ?>;
var txt = document.createElement('h1');
txt.innerHTML = access;
document.body.appendChild(txt);
}
myFunction();
</script>
</body>
</html>