我试图通过"早期退出"来清理我的代码。每次我使用return语句时都会得到一个空白页面
我应该将PHP代码移动到单独的文件吗?
此外,我很乐意获得一些清理代码的提示。
谢谢!!
<?php
$capt_error = "";
$mismatch = "";
$name = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
session_start();
// validate captcha
if (empty($_POST["capt"])) {
$capt_error = "Fältet är obligatoriskt.";
return null; // HERE, I GET A BLANK PAGE
} else {
if($_POST['capt'] != $_SESSION['rand']) {
$name = $_POST["name"];
$message = $_POST['message'];
$mismatch = "Inmatningen av CAPTHA är fel. Vänligen prova igen.";
}
else {
// write to file but only if cookie is not set
$ip_address = $_SERVER['REMOTE_ADDR'];
$time_stamp = date('Y-m-d H:i');
$data = "\n" . $_POST['name'] . ',' . $_POST['message'] . ',' . $ip_address . ',' . $time_stamp;
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if ($ret == false) {
die('Fel vid skrivning till fil. Skrivrättigheter saknas');
}
// set cookie
$cookie_name = $_POST['name'];
$cookie_value = $ip_address;
setcookie($cookie_name, $cookie_value, null, "/");
}
}
}
?>
<link rel="stylesheet" href="labb1.css" type="text/css">
<html>
<head>
<title>Labb 1</title>
</head>
<body>
<h1 class="title">Laboration 1 - Gästboken</h1>
<table border="1">
<thead>
<tr>
<th colspan="3" class="table-title">Min Gästbok</th>
</tr>
</thead>
<tbody>
<tr>
<td class="bold">FRÅN</td>
<td class="bold">INLÄGG</td>
<td class="bold">LOGGNING</td>
</tr>
<?php
// open file
$f = fopen("data.txt", "r");
// while not end of file
while (!feof($f)) {
// split values with -
$arr = explode(",", trim(fgets($f), "\r\n"));
print "<tr>";
print "<td>$arr[0]</td>";
print "<td>$arr[1]</td>";
print "<td>IP: $arr[2]<br>TID: $arr[3]</td>";
print "</tr>";
}
?>
</tbody>
</table>
<form action="" method="post">
<div class="border">
<div>
<span>Namn:</span>
<input type="text" name="name" value="<?php echo $name;?>">
</div>
<div>
<span>Meddelande:</span>
<textarea name="message" rows="5"><?php echo $message;?></textarea>
</div>
<div>
<?php
$rand = substr(str_shuffle(str_repeat("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
session_start();
$_SESSION["rand"] = $rand;
print "<span>CAPTCHA skriv detta i rutan nedan: </span> <span class='red bold'>$rand</span>"
?>
<span class="error">* <?php echo $capt_error; ?></span>
<input type="text" name="capt">
<span class="error"><?php echo $mismatch?></span>
</div>
<div>
<input type="submit" value="Skicka">
</div>
<div>
<span class="red">*</span> är ett obligatoriskt fält
</div>
</div>
</form>
</body>
</html>
答案 0 :(得分:0)
您似乎在代码中错误地使用了return语句。以下内容来自文档:
http://php.net/manual/en/function.return.php
如果从全局范围调用,则结束当前脚本文件的执行。如果包含或需要当前脚本文件,则将控制权传递回调用文件。
你似乎想要做的是捕获错误信息,然后在你的代码中使用它 - 这是完全可以的。只需设置一个带有错误的变量,继续执行代码并稍后检查变量。