【问题标题】:How to get html form data into PHP to send an email如何将 html 表单数据导入 PHP 以发送电子邮件
【发布时间】:2016-05-26 00:34:29
【问题描述】:

在我的 PHP 代码中,我有以下内容,这些变量从 html 表单中获取数据。

$name = @trim(stripslashes($_POST['name'])); 
$clientemail = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message']));

但是,如果我删除@,那么我看到的不是成功消息,而是"undefined",但如果我保留@,那么我确实会收到一封电子邮件,但它是一封空白电子邮件......

完整代码:

<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL);
   header('Content-type: application/json');

        // WE SHOULD ASSUME THAT THE EMAIL WAS NOT SENT AT FIRST UNTIL WE KNOW MORE.
        // WE ALSO ADD AN ATTACHMENT KEY TO OUR STATUS ARRAY TO INDICATE THE STATUS OF OUR ATTACHMENT:  
        $status = array(
                        'type'          =>'Error',
                        'message'       =>'Couldn\'t send the Email at this Time. Something went wrong',
                        'attachement'   =>'Couldn\'t attach the uploaded File to the Email.'
        );

//Added to deal with Files
require_once('/PHPMailer/class.phpmailer.php');\

    //      require_once('/PHPMailer/class.smtp.php');
    //Get the uploaded file information
    $name_of_uploaded_file =
        basename($_FILES['uploaded_file']['name']);

    //get the file extension of the file
    $type_of_uploaded_file =
        substr($name_of_uploaded_file,
        strrpos($name_of_uploaded_file, '.') + 1);

    $size_of_uploaded_file =
        $_FILES["uploaded_file"]["size"]/1024;//size in KBs

    //Settings
    $max_allowed_file_size = 10240; // size in KB
    $allowed_extensions = array("jpg", "jpeg", "gif", "bmp","png");

    //Validations
    if($size_of_uploaded_file > $max_allowed_file_size )
    {
      $errors .= "\n Size of file should be less than $max_allowed_file_size (~10MB). The file you attempted to upload is too large. To reduce the size, open the file in an image editor and change the Image Size and resave the file.";
    }

    //------ Validate the file extension -----
    $allowed_ext = false;
    for($i=0; $i<sizeof($allowed_extensions); $i++)
    {
      if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
      {
        $allowed_ext = true;
      }
    }

    if(!$allowed_ext)
    {
      $errors .= "\n The uploaded file is not supported file type. ".
      " Only the following file types are supported: ".implode(',',$allowed_extensions);
    }

    //copy the temp. uploaded file to uploads folder - make sure the folder exists on the server and has 777 as its permission
    $upload_folder = "/temp/";
    $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
    $tmp_path = $_FILES["uploaded_file"]["tmp_name"];

    if(is_uploaded_file($tmp_path))
    {
      if(!copy($tmp_path,$path_of_uploaded_file))
      {
        $errors .= '\n error while copying the uploaded file';
      }
    }
//--end

$name = @trim(stripslashes($_POST['name'])); 
$clientemail = @trim(stripslashes($_POST['email'])); 
$subject = @trim(stripslashes($_POST['subject'])); 
$message = @trim(stripslashes($_POST['message']));

$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $clientemail . "\n\n" .   'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$email = new PHPMailer();   
$email->From      = $clientemail;
$email->FromName  = $name;
$email->Subject   = $subject;
$email->Body      = $body;  
$email->AddAddress( 'root@localhost.com' ); //Send to this email

// EXPLICITLY TELL PHP-MAILER HOW TO SEND THE EMAIL... IN THIS CASE USING PHP   BUILT IT MAIL FUNCTION    
$email->isMail();

// THE AddAttachment METHOD RETURNS A BOOLEAN FLAG: TRUE WHEN ATTACHMENT WAS SUCCESSFUL & FALSE OTHERWISE:
// KNOWING THIS, WE MAY JUST USE IT WITHIN A CONDITIONAL BLOCK SUCH THAT 
// WHEN IT IS TRUE, WE UPDATE OUR STATUS ARRAY...   
if($email->AddAttachment( $path_of_uploaded_file , $name_of_uploaded_file )){
        $status['attachment']   = 'Uploaded File was successfully attached to the Email.';  
    }

// NOW, TRY TO SEND THE EMAIL ANYWAY:
    try{
        $success    = $email->send();
        $status['type']     = 'success';
        $status['message']  = 'Thank you for contact us. As early as possible  we will contact you.';   
    }catch(Exception $e){
        $status['type']     ='Error';
        $status['message']  ='Couldn\'t send the Email at this Time. Something went wrong';     
    }   

    // SIMPLY, RETURN THE JSON DATA...
die (json_encode($status));

HTML:

            <form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php">
                <div class="col-sm-5 col-sm-offset-1">
                    <div class="form-group">
                        <label>Name *</label>
                        <input type="text" name="name" class="form-control" required="required">
                    </div>
                    <div class="form-group">
                        <label>Email *</label>
                        <input type="email" name="email" class="form-control" required="required">
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="number" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Company Name</label>
                        <input type="text" class="form-control">
                    </div>                        
                </div>
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>Subject *</label>
                        <input type="text" name="subject" class="form-control" required="required">
                    </div>
                    <div class="form-group">
                        <label>Message *</label>
                        <textarea name="message" id="message" required="required" class="form-control" rows="8" style="height:125px"></textarea>
                        <label for='uploaded_file' style="margin-top:10px">Select A Photo To Upload:</label>
                        <input type="file" name="uploaded_file">
                    </div>                        
                    <div class="form-group">
                        <button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
                    </div>
                </div>
            </form> 

这是在用户单击提交时向用户显示消息的 AJAX:

// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: $(this).attr('action'),

        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
        }
    }).done(function(data){
        form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
    });
});

【问题讨论】:

  • @ 抑制错误。
  • 你在做$email = new PHPMailer(); 两次......
  • 您是否使用 AJAX 调用 sendemail.php 脚本?正常的表单提交返回 JSON 是不寻常的,它应该返回 HTML。
  • 您没有在 AJAX 调用中发送任何表单字段。添加data: $(this).serialize()

标签: php html email phpmailer


【解决方案1】:

您需要将表单数据放入 AJAX 请求中。

$.ajax({
    url: $(this).attr('action'),
    data: $(this).serialize(),
    beforeSend: function(){
        form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
    }
})

但是,serialize() 不适用于 type="file" 输入。这就是为什么您会得到 $_FILES['uploaded_file'] 的未定义索引。你需要使用FormData:

$.ajax({
    url: $(this).attr('action'),
    data: new FormData(this),
    processData: false,
    contentType: false,
    beforeSend: function(){
        form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
    }
})

这一行还有语法错误:

require_once('/PHPMailer/class.phpmailer.php');\

去掉最后的斜线。

请参阅PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset",了解有关您收到的所有警告的信息。

【讨论】:

  • 因此serialize(), 行允许表单工作,但会导致 Jquery 文件中出现错误,从而破坏 JS 代码。但是,如果我使用 serialize(); JS 很好,但 PHP 会中断并给出 undefined 输出
  • 如果你使用FormData呢?
  • enctype="multipart/form-data" 中是否与此有关??
  • 哦,您的意思可能是data: new FormData(this), 是的,我也尝试过同样的问题。我收到一条undefined 消息,我相信当它尝试运行beforeSend: function(){ form.prepend( form_status.html('&lt;p&gt;&lt;i class="fa fa-spinner fa-spin"&gt;&lt;/i&gt; Email is sending...&lt;/p&gt;').fadeIn() ); }
  • 我不认为beforeSend 应该对此有任何影响,但如果你删除它会发生什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 2015-10-23
  • 2020-04-22
  • 2016-03-11
  • 1970-01-01
  • 2012-10-31
相关资源
最近更新 更多