Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML "required" Attribute does not work for spam bots

I have a form, which users should be able to submit only if they upload/attach a document. For that I use the following line:

<input type="file" id="file" name="attachment" 
       accept=".pdf, .doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" 
       required >

This is the PHP code:

<?php
$postData = $uploadedFile = $statusMsg = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
    // Get the submitted form data
    $postData = $_POST;
    
    $servicetypes = $_POST['servicetypes'];
    $turnaroundspeeds = $_POST['turnaroundspeeds'];
    $englishtype = $_POST['englishtype'];
    $currency = $_POST['currency'];
    $email = $_POST['email'];
    $name = $_POST['name'];
    $wordcount = $_POST['wordcount'];
    $message = $_POST['message'];
    $promocode = $_POST['promocode'];
    
    
    
    
    // Check whether submitted data is not empty
    if(!empty($turnaroundspeeds) && !empty($servicetypes) && !empty($englishtype) && !empty($currency) && !empty($email) && !empty($name) ){
        
        // Validate email
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
            $statusMsg = 'Please enter your valid email.';
        }else{
            $uploadStatus = 1;
            
            // Upload attachment file
            if(!empty($_FILES["attachment"]["name"])){
                
                // File path config
                $targetDir = "uploads/";
                $fileName = basename($_FILES["attachment"]["name"]);
                $targetFilePath = $targetDir . $fileName;
                $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
                
                

                
                
                
                // Allow certain file formats
                $allowTypes = array('pdf', 'doc', 'docx');
                if(in_array($fileType, $allowTypes)){
                    // Upload file to the server
                    if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
                        $uploadedFile = $targetFilePath;
                    }
                }
            }
            
            if($uploadStatus == 1){
                
                // Recipient
                $toEmail = '[email protected]';

                // Sender
                $from = '[email protected]';
                $fromName = 'Customer';
                
                // Subject
                $emailSubject = 'Quote Request Submitted by '.$name;
                
                // Message 
                $htmlContent = '<h2>Contact Request Submitted</h2>
                    <p><b>Service Type:</b> '.$servicetypes.'</p>
                    <p><b>Turnaround Speed:</b> '.$turnaroundspeeds.'</p>
                    <p><b>English Type:</b> '.$englishtype.'</p>
                    <p><b>Name:</b> '.$name.'</p>
                    <p><b>Email:</b> '.$email.'</p>
                    <p><b>Word Count:</b> '.$wordcount.'</p>
                    <p><b>Promo Code:</b> '.$promocode.'</p>
                    <p><b>Currency:</b> '.$currency.'</p>
                    <p><b>Message:</b><br/>'.$message.'</p>';
                
                // Header for sender info
                $headers = "From: $fromName"." <".$from.">";

                if(!empty($uploadedFile) && file_exists($uploadedFile)){
                    
                    // Boundary 
                    $semi_rand = md5(time()); 
                    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
                    
                    // Headers for attachment 
                    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 
                    
                    // Multipart boundary 
                    $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
                    "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n"; 
                    
                    // Preparing attachment
                    if(is_file($uploadedFile)){
                        $message .= "--{$mime_boundary}\n";
                        $fp =    @fopen($uploadedFile,"rb");
                        $data =  @fread($fp,filesize($uploadedFile));
                        @fclose($fp);
                        $data = chunk_split(base64_encode($data));
                        $message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" . 
                        "Content-Description: ".basename($uploadedFile)."\n" .
                        "Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" . 
                        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                    }
                    
                    $message .= "--{$mime_boundary}--";
                    $returnpath = "-f" . $email;
                    
                    // Send email
                    $mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
                    
                    // Delete attachment file from the server
                    @unlink($uploadedFile);
                }else{
                     // Set content-type header for sending HTML email
                    $headers .= "\r\n". "MIME-Version: 1.0";
                    $headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
                    
                 

                    
                    // Send email
                    $mail = mail($toEmail, $emailSubject, $htmlContent, $headers); 
                }
                
                // If mail sent
                
                if(!$mail) {
  print_r( 'Mailer error: Please send your document through [email protected] ' . error_get_last());
} else {
  echo 
  header('Location: submit-thank-you.htm');
exit()
}

            }
        }
    }else{
       echo 
  header('Location: problem.htm');
exit();
    }
}
?

This code works for real users: on my webpage, I cannot submit the form without an attachment.

However, I receive many spam submissions without an attachment. How does that even happen? How can I avoid this?

I checked many times, but could not find a solution. Is there anything I can change in the PHP code to prevent spam bots from filling out my form?

like image 516
Schneider Avatar asked Aug 31 '25 03:08

Schneider


2 Answers

Being well behaved is obviously against its interests. Most likely the spambot analyzes your form and then submits data to match its fields.

Client side validation (which includes enforcement of a required rule) is the first thing to go out of the window when dealing with spammers and scammers.

like image 79
Peter B Avatar answered Sep 02 '25 18:09

Peter B


Solution 1 : Implement a Honeypot Field

A honeypot field is a hidden field that should not be filled out by real users but might be filled out by spam bots that automatically submit all form fields. If this field is filled out, you can treat the submission as spam and reject it.

Add a hidden field to your form:

<input type="text" name="honeypot" style="display:none" />

In your backend, check if the honeypot field has been filled out. If it has, reject the form submission.

Solution 2 : Use Google reCAPTCHA

Adding a CAPTCHA like Google reCAPTCHA can significantly reduce the chance of automated submissions. It will ask users to solve a challenge (e.g., identifying objects in images) to prove they're human.

like image 35
Piyush Sapariya Avatar answered Sep 02 '25 16:09

Piyush Sapariya