Skip to main content
Participating Frequently
August 11, 2020
Answered

Form PHP file upload and redirect not working

  • August 11, 2020
  • 2 replies
  • 1764 views
We're looking for a bit of help with the PHP for this form if possible please,
 
 
which is an adapted version of one we had that worked previously, including recaptcha, this time with a file upload section (limited to PDF and Word docs).

 

The script seems to work to a point, in that an attached file uploads to the uploads folder on the server, but the details filled in in the form aren't sent in an email nor does the redirect work so I'm guessing somewhere in the midst of this script something isn't quite right – if anyone could offer a bit of assistance (or a better version of this PHP) it'd be much appreciated thanks!

 
 
<?php
 
//set recaptcha url/secret-key/response
$recaptcha_secret = 'xxxxxxxxxxxxx';
$recaptcha_response = $_POST['token'];
//send information to recaptcha url
$recaptcha = file_get_contents($recapture_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
//check if recaptcha has been successful
if($recaptcha->success==true) {
if($recaptcha->score >= 0.5) {
// if recaptcha is successful and score is equal or more than 0.5 process the form information
 
 
$postData = $uploadedFile = $statusMsg = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
    // Get the submitted form data
    $name = htmlspecialchars($_POST['name']);
$job = htmlspecialchars($_POST['job']);
$telephone = htmlspecialchars($_POST['telephone']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
if(empty($name) || empty($job) || empty($telephone) || empty($email) || empty($message)) {
$error = true;
$status = "Failed";
}
elseif(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$error = true;
$status = "Failed"; 
}
           
            // 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;
                    }
else
{
                        $uploadStatus = 0;
                        $statusMsg = "Sorry, there was an error uploading your file.";
                    }
                }
else
{
                    $uploadStatus = 0;
                    $statusMsg = 'Sorry, only PDF and DOC files are allowed to upload.';
                }
            }
            
            if($uploadStatus == 1){
                
               // Recipient
                $toEmail = 'xxxxxxxxx';
 
                // Sender
                $from = 'xxxxxxxxx';
                $fromName = 'Job Application';
                
                // Subject
                $emailSubject = 'Contact Request Submitted by '.$name;
                
                // Message 
                $htmlContent = '<h2>Job Application Submitted</h2>
                    <p><b>Name:</b> '.$name.'</p>
<p><b>Job applied for:</b> '.$job.'</p>
                    <p><b>Telephone number:</b> '.$telephone.'</p>
                    <p><b>Email:</b> '.$email.'</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 =  @9046115($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 recaptcha fails set a status
else {
$status = "Failed";
}
 
}
// if status is successful then include the contact_sent.html page
 if($mail){
include('pages/jobapplication-sent.html');
}
 
}else{
// if status is failed then include the contact_failed.html page
include('pages/jobapplication-failed.html');
}
}
?>

 

This topic has been closed for replies.
Correct answer osgood_

My guess is its because the failed.html include page is located inside of the if($uploadStatus == 1) {  } block of code.

 

 if($uploadStatus == 1){

 

else{
// if status is failed then include the contact_failed.html page
include('pages/jobapplication-failed.html');
}

 

}

 

 

You would need to locate the failed.html include page inside of the 'if' block of code which checks if the form fields have been left empty:

 

if(empty($name) || empty($job) || empty($telephone) || empty($email) || empty($message)) {

include('pages/jobapplication-failed.html');
$error = true;
$status = "Failed";
}

 

 

You also don't want to wrap the php processing code in a block which checks to see if the 'submit' form button has been clicked. You only do that IF the php script is included in the same page as the form itself.

 

if(isset($_POST['submit'])){

 

}

 

2 replies

Legend
August 11, 2020

Not at computer right now so cant check much but looking at the php code it doesnt look as if you have set the $uploadStatus variable to 1

 

Try adding that at the same time you have checked the file type being uploaded is correct. After the comment:

// Upload file to server

Add:

$uploadStatus  = 1;

 

Your mail part of the script is saying IF the upload status is 1 then mail the contents of the form. If its not 1 then mail section wont do anything.

mercafeAuthor
Participating Frequently
August 12, 2020

Thanks for that that change has made the script work!

 

Oddly now though if one or any of the form elements aren't filled in it goes to a blank page rather than the failure page

osgood_Correct answer
Legend
August 13, 2020

My guess is its because the failed.html include page is located inside of the if($uploadStatus == 1) {  } block of code.

 

 if($uploadStatus == 1){

 

else{
// if status is failed then include the contact_failed.html page
include('pages/jobapplication-failed.html');
}

 

}

 

 

You would need to locate the failed.html include page inside of the 'if' block of code which checks if the form fields have been left empty:

 

if(empty($name) || empty($job) || empty($telephone) || empty($email) || empty($message)) {

include('pages/jobapplication-failed.html');
$error = true;
$status = "Failed";
}

 

 

You also don't want to wrap the php processing code in a block which checks to see if the 'submit' form button has been clicked. You only do that IF the php script is included in the same page as the form itself.

 

if(isset($_POST['submit'])){

 

}

 

Nancy OShea
Community Expert
Community Expert
August 11, 2020

Ask your web host which form-to-email processing scripts they recommend you use with your hosting plan. 

 

If your server supports PHP scripts, have a look at this PHP sending library on GitHub.

https://github.com/PHPMailer/PHPMailer

 

Nancy O'Shea— Product User & Community Expert
mercafeAuthor
Participating Frequently
August 12, 2020

Thanks Nancy will take a look at that!