<form action="session_registration_form_script.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" />
<label for="email">Email:</label>
<input type="text" name="email" />
<input type="submit" value="Register" />
</form>
和PHP脚本类似:
<?php
// Initialize session data
session_start();
/*
* If the user is already registered, display a
* message letting them know.
*/
if(isset($_SERVER['username'])) {
echo "You're already registered as $_SESSION[username]";
}
// Checks if the form was submitted
else if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*
* If both the username and email fields were filled
* out, save the username in a session variable and
* output a thank you message to the browser. To
* eliminate leading and trailing whitespace, we use the
* trim() function
*/
if(!empty(trim($_POST['username']))
&& !empty(trim($_POST['email']))) {
// Store escaped $_POST values in variables
$uname = htmlentities($_POST['username']);
$email = htmlentities($_POST['email']);
$_SESSION['username'] = $uname;
echo "Thanks for registering! <br />",
"Username: $uname <br />",
"Email: $email <br />";
}
/*
* If the user did not fill out both fields, display
* a message letting them know that both fields are
* required for registration
*/
else {
echo "Please fill out both fields! <br />";
}
}
// If the form was not submitted, dispalys the HTML form
else {
?>
<?php } ?>
当我在浏览器上输出两个文件时,浏览器报告:致命错误:无法在“文件路径”的写入上下文中使用函数值和代码行
请通过修复此问题来帮忙,并随时添加您可能对我有用的任何内容。在此先感谢...
答案 0 :(得分:2)
我可以在您的代码中看到许多问题。
if(isset($_SERVER['username'])) {
echo "You're already registered as $_SESSION[username]";
}
应该是
if(isset($_SESSION['username'])) {
echo "You're already registered as ".$_SESSION['username'];
}
此外,当您的表单字段被调用$_POST
时,您正在寻找名为username
的{{1}}变量。
至于您看到的实际错误,这是因为您一起使用name
和empty
的方式 - 您应该分别检查2。 E.g。
trim
答案 1 :(得分:0)
我认为在检查全局变量之前修剪变量是一个好主意,然后检查它们是否为空
$uname = trim($_POST['username']);
$email = trim($_POST['email']);
if(!empty($uname) && !empty($email)) {
//if(!empty($_POST['username']) && !empty($_POST['email']))
//{
// Store escaped $_POST values in variables
$uname = htmlentities($_POST['username']);
$email = htmlentities($_POST['email']);
$_SESSION['username'] = $uname;
echo "Thanks for registering! <br />",
"Username: $uname <br />",
"Email: $email <br />";
}