【问题标题】:How do I connect php file to HTML form? [duplicate]如何将 php 文件连接到 HTML 表单? [复制]
【发布时间】:2020-07-28 07:29:29
【问题描述】:

我需要使用表单中的数据发送电子邮件(mailto 不起作用)

不知何故,php 文件无法连接到 html。当我在本地运行 index.html 时,如果我推送 submit,浏览器会显示一个 php 代码并且不执行任何其他操作。当我使用 localhost 时,如果我按下 submit,它会抛出一个 405 Error

PLS 帮助,因为我不是 php 开发人员。

<form method="POST" name="myName" action="registration.php">
  <textarea name="message"></textarea>
  <div class="form_submit">
    <input type="submit" value="Submit" class="form_submit-btn">
   </div>
</form>


<?php

if($_POST["message"]) {

mail("myemail@gmail.com", "Here is the subject line",

$_POST["insert your message here"]. "From: an@email.address");

}

?>

【问题讨论】:

  • 您使用的是哪个服务器?
  • 正如 Navan 所问的那样,index.html 应该是 index.php,因为代码在同一个文件中(基于上面的示例)。您真正想要做的是将 php 代码移动到名为 registration.php 的文件中。并确保您使用 php 运行 Nginx/Apache,并将服务器配置为读取应用程序的目录。

标签: php html forms email action


【解决方案1】:

您对 mail 函数的调用看起来不太正确 - 调用的 headers 元素似乎附加到消息正文中,而不是作为单独的参数。

<?php
    # registration.php
    
    error_reporting( E_ALL );
    ini_set( 'display_errors', 1 );

    
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['message'] ) ){
        ob_clean();
        
        $lb="\r\n";
        
        $recipient='geronimo@example.com';
        $message=$_POST['message'];
        $subject='This is a test';
        $headers=array(
            'From: webmaster@example.com',
            'Reply-To: webmaster@example.com',
            'Cc: joe.bloggs@example.com'
        );
        
        $status=mail( $recipient, $subject, $message, implode( $lb, $headers ) ;
        exit( header( sprintf('Location: index.html?mailsent=%s', $status ) ) );
    }
?>





<!-- index.html -->
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
        <form method='POST' action='registration.php'>
            <textarea name='message'></textarea>
            <div class='form_submit'>
                <input type='submit' value='Submit' class='form_submit-btn'>
            </div>
        </form>
    </body>
</html>

【讨论】:

    【解决方案2】:

    将您的文件 index.html 重命名为 index.php。它抛出 405 错误,因为 index.html 不能接受 POST 请求。在这种情况下,您需要使用服务器端语言处理表单,将 index.html 更改为 index.php。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-05
      • 2021-09-13
      • 1970-01-01
      • 2011-08-20
      • 2021-04-25
      • 2019-01-13
      • 2021-10-05
      • 2018-05-04
      相关资源
      最近更新 更多