【问题标题】:How do fix '404 page not found' error when running a php file?运行 php 文件时如何修复“404 page not found”错误?
【发布时间】:2021-01-03 17:22:00
【问题描述】:

我刚开始学习 php,当我运行我的 php 文件时,无论使用哪种浏览器,我都会收到 404 错误。我的代码缺少什么导致这种情况?该文件应该在用户提交“联系我”表单后显示一条消息。

<!DOCTYPE html>
<html lang="">
<head>
    <title>Contact Form Submitted</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
    Thank you, <?php echo $_POST["name"]; ?> for your comments<br>
    You stated in your test Message:<br>
    <?php echo $_POST["message"]; ?>
    We will respond to you at <?php echo $_POST["email"]; ?> when we make updates to the site.
</p>
</body>
</html>

【问题讨论】:

  • 跑步是什么意思?访问/thefile.php?没有按钮的时候怎么提交?
  • “联系我”html 表单上有一个提交按钮。这些都应该放在一个文件中吗?
  • 我用的是phpstorm,有一个运行按钮

标签: php html forms http-status-code-404


【解决方案1】:

此代码有效。看到这是 Firefox:https://i.imgur.com/YeBFt9B.png

<?php
// var    // variable value       // default value
$php_path = $_SERVER['PHP_SELF']  ?? "";
$name     = $_POST["name"]        ?? "name";
$message  = $_POST["message"]     ?? "message";
$email    = $_POST["email"]       ?? "email";

?>
<!DOCTYPE html>
<html lang="">
<head>
    <title>Contact Form Submitted</title>
</head>
<body>
<form action="<?= $php_path ?>" method="POST">
<p>
    Thank you, <?= $name ?> for your comments<br>
    You stated in your test Message:<br>
    <?= $message ?>
    <br><br>
    We will respond to you at <?= $email ?> when we make updates to the site.
</p>
</form>
</body>
</html>

如果您没有为其他表单的参数指定默认值,您可能会遇到意外错误。这个版本更好;)

我确定您收到此错误是因为您的某个网址中有错字

【讨论】:

  • 那段代码给了我一个错误,提示“Coalesce 运算符仅在 PHP 7 中可用”
  • 您运行的不是版本 7 或更高版本? php.net/supported-versions.php
  • 我使用的是 jetbrains 的 PHP Storm,它是最新版本,我有它的教育许可证,所以我认为我不能更改版本。
  • stackoverflow.com/questions/4122585/… PHP 5 又旧又坏。 PHP7 是一个巨大的改进
  • 好的,谢谢,希望我的教授能提到这一点。我的联系表格也是一个 html 文件。它是否必须是一个 php 文件才能工作,我要做的就是在用户单击提交后将用户重定向到一个空白页面,该页面统计了谢谢你的消息。
【解决方案2】:

首先使用htmlspecialchars in:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

如果用户输入像 http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E 这样的 url,你会阻止 XSS attack

如果您收到 404 错误,可能是因为您在 contact me 页面上的表单操作未指向正确的脚本。

如果您有两个单独的文件,一个用于表单,第二个用于感谢信息,您必须确保网址正确。

// form.php
...
<form action="thanks-message.php">
    ...
</form>
...
// thanks-message.php
<?php
$name = $_POST["name"] ?? "Joe";
$message = $_POST["message"] ?? "Lorem ipsum...";
$email = $_POST["email"] ?? "joe@example.com";
?>
...
<p>
    Thank you, <?= $name ?> for your comments<br>
    You stated in your test Message:<br>
    <?= $message ?>
    <br><br>
    We will respond to you at <?= $email ?> when we make updates to the site.
</p>
...

form 元素在此页面上不是必需的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 2012-09-05
    • 1970-01-01
    • 2019-09-11
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多