You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带附件的HTML表单邮件提交在客户服务器卡顿问题求助

Hey there, let's figure out why your form is hanging on the client's server—since it works perfectly on your test environment, the issue is almost definitely tied to differences between the two servers. Here's a breakdown of the most likely culprits and actionable fixes:

Troubleshooting the Hanging PHP Form with Attachments

1. Truncated Code (Critical Syntax Error)

Looking at your provided code, the attach_files() method is cut off mid-line:

private function attach_files() {
    foreach($this->attachments as $file_field) {
        if (!array_key_exists($file

This is a fatal syntax error. If this is how the code is deployed on the client's server, it will crash the script silently (especially if error reporting is disabled on production), leading to the "hang" you're seeing. Here's the corrected, complete version of this method:

private function attach_files() {
    foreach($this->attachments as $file_field) {
        // Skip if the file field doesn't exist in the upload data
        if (!array_key_exists($file_field, $_FILES)) {
            continue;
        }
        $file = $_FILES[$file_field];
        // Only attach if the upload was successful
        if ($file['error'] === UPLOAD_ERR_OK) {
            $this->mailer->addAttachment(
                $file['tmp_name'],
                $file['name'],
                'base64',
                $file['type']
            );
        }
    }
}

2. SMTP Connection Blocked or Failing

Your code uses Gmail's SMTP server (smtp.gmail.com:587), which is often restricted on shared hosting environments:

  • Firewall/Network Restrictions: Many hosting providers block outgoing connections to external SMTP servers. Ask the client to check if their server allows traffic to smtp.gmail.com:587.
  • Gmail Security Settings: If you're using a regular Gmail account, ensure 2FA is disabled (or use an App Password if 2FA is enabled—Google phased out "Less secure app access" for most accounts).
  • Switch to Host's SMTP: For reliability, use the client's hosting provider's native SMTP server (e.g., localhost for cPanel-based hosts) instead of Gmail's.

3. PHP Execution Time Limits

File uploads and email sending can take time, especially with large attachments. If the client's server has a low max_execution_time (default is often 30 seconds), the script will timeout mid-process:

  • Temporarily increase the limit at the top of your script:
    ini_set('max_execution_time', 300); // 5 minutes
    
  • Ask the client to check the php.ini settings for max_execution_time if this is a recurring issue.

4. File Upload Permissions & Limits

Silent upload failures can also cause hangs:

  • Temp Directory Permissions: Ensure the server's temporary upload directory (usually /tmp) has write permissions for the web server user (e.g., www-data).
  • PHP Upload Limits: Check upload_max_filesize and post_max_size in the client's php.ini—if users are uploading files larger than these limits, the script will fail without feedback.

5. Disabled Error Reporting

Production servers often hide errors, so you can't see what's breaking. Enable temporary error reporting to debug:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Add this at the very top of your PHP file to catch fatal errors, warnings, or notices that might be causing the hang.

Additional Debugging Steps

  • Check Server Logs: Ask the client for Apache/Nginx access logs and PHP error logs—these will have detailed info about what's failing.
  • Test Without Attachments: Comment out the attachment logic temporarily to see if the email sends successfully. If it does, the issue is specifically with file handling.
  • Test SMTP Connection: Use this simple script to verify the server can connect to Gmail's SMTP:
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->CharSet="UTF-8";
    $mail->SMTPSecure = 'tls';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->Username = 'ceilaoezy@gmail.com';
    $mail->Password = 'hahadonttrythis';
    $mail->SMTPAuth = true;
    
    if (!$mail->smtpConnect()) {
        die('SMTP Connection Failed: ' . $mail->ErrorInfo);
    } else {
        echo 'SMTP Connection Successful!';
    }
    

Full Corrected Code (with Fixed Methods)

<?php 
namespace FormGuide\Handlx; 

use FormGuide\PHPFormValidator\FormValidator; 
use PHPMailer; 
use FormGuide\Handlx\Microtemplate; 
use Gregwar\Captcha\CaptchaBuilder; 

class FormHandler { 
    private $emails; 
    public $validator; 
    private $mailer; 
    private $mail_template; 
    private $captcha; 
    private $attachments; 
    private $recaptcha; 

    public function __construct() { 
        $this->emails = array(); 
        $this->validator = FormValidator::create(); 
        $this->mailer = new PHPMailer; 
        $this->mail_template=''; 
        $this->mailer->IsSMTP(); 
        $this->mailer->CharSet="UTF-8"; 
        $this->mailer->SMTPSecure = 'tls'; 
        $this->mailer->Host = 'smtp.gmail.com'; 
        $this->mailer->Port = 587; 
        $this->mailer->Username = 'ceilaoezy@gmail.com'; 
        $this->mailer->Password = 'hahadonttrythis'; 
        $this->mailer->SMTPAuth = true; 
        $this->mailer->Subject = "Contact Form Submission "; 
        $host = isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'localhost'; 
        $from_email ='forms@'.$host; 
        $this->mailer->setFrom($from_email,'Contact Form',false); 
        $this->captcha = false; 
        $this->attachments = []; 
        $this->recaptcha =null; 
    } 

    /** 
     * sendEmailTo: add a recipient email address 
     * @param string/array $email_s one or more emails. If more than one emails, pass the emails as array 
     * @return The form handler object itself so that the methods can be chained 
     */ 
    public function sendEmailTo($email_s) { 
        if(is_array($email_s)) { 
            $this->emails =array_merge($this->emails, $email_s); 
        } else { 
            $this->emails[] = $email_s; 
        } 
        return $this; 
    } 

    public function useMailTemplate($templ_path) { 
        $this->mail_template = $templ_path; 
        return $this; 
    } 

    /** 
     * [attachFiles find the file uplods and attach to the email] 
     * @param array $fields The array of field names 
     */ 
    public function attachFiles($fields) { 
        $this->attachments = array_merge($this->attachments, $fields); 
        return $this; 
    } 

    public function getRecipients() { 
        return $this->emails; 
    } 

    /** 
     * [validate add Validations. This function takes a call back function which receives the PHPFormValidator object] 
     * @param function $validator_fn The funtion gets a validator parameter using which, you can add validations 
     */ 
    public function validate($validator_fn) { 
        $validator_fn($this->validator); 
        return $this; 
    } 

    public function requireReCaptcha($config_fn=null) { 
        $this->recaptcha = new ReCaptchaValidator(); 
        $this->recaptcha->enable(true); 
        if($config_fn) { 
            $config_fn($this->recaptcha); 
        } 
        return $this; 
    } 

    public function getReCaptcha() { 
        return $this->recaptcha; 
    } 

    public function requireCaptcha($enable=true) { 
        $this->captcha = $enable; 
        return $this; 
    } 

    public function getValidator() { 
        return $this->validator; 
    } 

    public function configMailer($mailconfig_fn) { 
        $mailconfig_fn($this->mailer); 
        return $this; 
    } 

    public function getMailer() { 
        return $this->mailer; 
    } 

    public static function create() { 
        return new FormHandler(); 
    } 

    public function process($post_data) { 
        if($this->captcha === true) { 
            $res = $this->validate_captcha($post_data); 
            if($res !== true) { 
                return $res; 
            } 
        } 

        if($this->recaptcha !== null && $this->recaptcha->isEnabled()) { 
            if($this->recaptcha->validate() !== true) { 
                return json_encode([ 
                    'result'=>'recaptcha_validation_failed', 
                    'errors'=>['captcha'=>'ReCaptcha Validation Failed.'] 
                ]); 
            } 
        } 

        $this->validator->test($post_data); 

        if($this->validator->hasErrors()) { 
            return json_encode([ 
                'result'=>'validation_failed', 
                'errors'=>$this->validator->getErrors(/*associative*/ true) 
            ]); 
        } 

        if(!empty($this->emails)) { 
            foreach($this->emails as $email) { 
                $this->mailer->addAddress($email); 
            } 

            $this->compose_mail($post_data); 

            if(!empty($this->attachments)) { 
                $this->attach_files(); 
            } 

            if(!$this->mailer->send()) { 
                return json_encode([ 
                    'result'=>'error_sending_email', 
                    'errors'=> ['mail'=> $this->mailer->ErrorInfo] 
                ]); 
            } 
        } 

        return json_encode(['result'=>'success']); 
    } 

    private function validate_captcha($post) { 
        @session_start(); 
        if(empty($post['captcha'])) { 
            return json_encode([ 
                'result'=>'captcha_error', 
                'errors'=>['captcha'=>'Captcha code not entered'] 
            ]); 
        } else { 
            $usercaptcha = trim($post['captcha']); 
            if($_SESSION['user_phrase'] !== $usercaptcha) { 
                return json_encode([ 
                    'result'=>'captcha_error', 
                    'errors'=>['captcha'=>'Captcha code does not match'] 
                ]); 
            } 
        } 
        return true; 
    } 

    private function attach_files() { 
        foreach($this->attachments as $file_field) { 
            if (!array_key_exists($file_field, $_FILES)) { 
                continue; 
            } 
            $file = $_FILES[$file_field]; 
            if ($file['error'] === UPLOAD_ERR_OK) { 
                $this->mailer->addAttachment( 
                    $file['tmp_name'], 
                    $file['name'], 
                    'base64', 
                    $file['type'] 
                ); 
            } 
        } 
    }

    // Placeholder for missing compose_mail method
    private function compose_mail($post_data) {
        $body = "New Form Submission:\n\n";
        foreach($post_data as $key => $value) {
            if(!in_array($key, ['captcha', 'g-recaptcha-response'])) {
                $body .= ucfirst(str_replace('_', ' ', $key)) . ": " . $value . "\n";
            }
        }
        $this->mailer->Body = $body;
        $this->mailer->AltBody = $body;
    }
}

内容的提问来源于stack exchange,提问作者Ravindu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:31:26