File upload option in form

im trying to create form submission with file upload which is working fine but i dont want all field to be mandatory, specially file uploaded is throwing error
if i uploaded file form is submitted without any error but if i leave file uploaded field empty then form is not submitted and section below form are gonna
i want form to be submitted even if file upload is left empty:

<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" class="appointment">
    <div class="row g-3">
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="name" placeholder="Your Name" >
            </div>
        </div>
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="email" class="form-control border-0" name="email"  placeholder="Your Email" >
            </div>
        </div>
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="phone"  placeholder="Phone Number" >
            </div>
        </div>
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0"  name="location" placeholder="Full Location" >
            </div>
        </div>
        
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="project"  placeholder="" >
            </div>
        </div>
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="waterproofing"  placeholder="" >
            </div>
        </div>
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="chosen_title" placeholder="" >
            </div>
        </div>
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="shower_base" placeholder="" >
            </div>
        </div>

        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="niche"  placeholder="" >
            </div>
        </div>
        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="file" id="myFile" name="my_file" class="form-control border-0" >
            </div>
        </div>

        <div class="col-sm-12 col-md-6">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="floor_waste"  placeholder="" >
            </div>
        </div>

        <div class="col-sm-12 col-md-6 ">
            <div class="form-group">
                <input type="text" class="form-control border-0" name="grout_color"  placeholder="" >
            </div>
        </div>

        <div class="col-12 col-md-12">
            <div class="form-group">
                <textarea class="form-control border-0" name="message" placeholder="Leave a message here"  style="height: 100px" ></textarea>
            </div>
        </div>
        <div class="col-12">
            <button name="submit" class="btn btn-dark w-100 py-3" type="submit">Submit</button>
        </div>
    </div>
</form>

form submission

if(isset ($_POST['submit'])){ 
    
$name          = $_POST['name'];
$email         = $_POST['email'];
$phone         = $_POST['phone'];
$location      = $_POST['location'];
$project       = $_POST['project'];
$waterproofing = $_POST['waterproofing'];
$chose_title   = $_POST['chosen_title'];
$shower_base   = $_POST['shower_base'];
$niche         = $_POST['niche'];
$floor_waste   = $_POST['floor_waste'];
$grout_color   = $_POST['grout_color'];
$message       = $_POST['message'];
$info = '
      <table  border="1" cellspacing="0" width="60%" cellpadding="10px">
            <tr style="height: 21px;">
              <td colspan="2" bgcolor="#dddfe2 " align="center" style="font-family: Verdana, Geneva, sans-serif; font-size: 14px; color: #000; height: 21px;"><b>Mail From Client: '.$name.'</b></td>
            </tr>
            <tr>
                <td>Name:</td>
                <td>'.$name.'</td>
            </tr>
            <tr>
                <td>Email:</td>
                <td>'.$email.'</td>
            </tr>
            <tr>
                <td>Phone:</td>
                <td>'.$phone.'</td>
            </tr>
            <tr>
                <td>Location:</td>
                <td>'.$location.'</td>
            </tr>
            <tr>
                <td>How big is your project ?</td>
                <td>'.$project.'</td>
            </tr>
            <tr>
                <td>Does your project require waterproofing?</td>
                <td>'.$waterproofing.'</td>
            </tr>
            <tr>
                <td>Have you chosen tiles?</td>
                <td>'.$chose_title.'</td>
            </tr>
            <tr>
                <td>Shower Base</td>
                <td>'.$shower_base.'</td>
            </tr>
            <tr>
                <td>Niche/wall recess</td>
                <td>'.$niche.'</td>
            </tr>
            <tr>
                <td>Floor waste</td>
                <td>'.$floor_waste.'</td>
            </tr>
            <tr>
                <td>Have you thought about grout colors?</td>
                <td>'.$grout_color.'</td>
            </tr>
            <tr>
                <td>Message:</td>
                <td>'.$message.'</td>
            </tr>
      </table>
'; 

    $from_email = $email; 
    $recipient_email    = 'someone@gmail.com'; 
    
    $sender_name    = filter_var($_POST["name"], FILTER_SANITIZE_STRING); 
    $reply_to_email = filter_var($_POST["email"], FILTER_SANITIZE_STRING); 
    $subject        = 'Mail From ' .$name;

    //Get uploaded file data
    $file_tmp_name    = $_FILES['my_file']['tmp_name'];
    
    $file_name        = $_FILES['my_file']['name'];
    $file_size        = $_FILES['my_file']['size'];
    $file_type        = $_FILES['my_file']['type'];
    
    //read from the uploaded file & base64_encode content for the mail
    $handle = fopen($file_tmp_name, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $encoded_content = chunk_split(base64_encode($content));

    $boundary = md5("random");
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "From:".$from_email."\r\n";
    $headers .= "Reply-To: ".$reply_to_email."" . "\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
       
    
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($info));
       
    //attachment
    $body .= "--$boundary\r\n";
    $body .="Content-Type: $file_type; name=".$file_name."\r\n";
    $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
    $body .="Content-Transfer-Encoding: base64\r\n";
    $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
    $body .= $encoded_content;
   
    $sentMail = mail($recipient_email, $subject, $body, $headers);
    if($sentMail) //output success or failure messages
    {      
        //die('Thank you for your email');
        echo "<script langauge='javascript'>alert ('We have received your mail. We will contact you soon'); </script>";
    }else{
        die('Could not send mail! Please check your PHP mail configuration.');  
    }

How can i solve this error form should submitted even if uploaded field is left empty

You would test the [‘error’] element of the uploaded file data before using the uploaded file information. If the upload wasn’t successful, you wouldn’t use the data at all and let the user know what was wrong with the upload (for user recoverable errors.) If no file was selected, the [‘error’] element will be UPLOAD_ERR_NO_FILE (4.) The list of error values can be found in the php documentation.

here i checking error if it doesnt match then die which will break site

if($file_error > 0){
  die('Upload error or No files uploaded');
  $imageerror ='Upload error or No files uploaded';
}

Where does $file_error come from? That doesn’t seem to be in the code you posted.

The new code snippet causes the processing to die / exit if there is no file uploaded. Unless I’m reading it wrongly, that’s the opposite of what you want to do. In your position I’d just surround all the processing of the file upload with a check to see if a file was uploaded, and only deal with the file if there is one to deal with.

Not that this is an answer to your issue, but the proper way to check for

if ($_SERVER['REQUEST_METHOD'] === 'POST')

if($file_error > 0){
  die('Upload error or No files uploaded');
  $imageerror ='Upload error or No files uploaded';
}

this error check was when file upload was mandatory, this if statement have been remove but still site is broke if file is not uploaded

i have check this method too but still if file is not uploaded site broke, but if file is uploaded form is submitted, how can fix this i ran out idea

Exactly what happens when you attempt to submit the form without a file? Do you get an error message? If you don’t, are you disabling error messages? If so, re-enable them while you debug. Is there anything in the server log?

The only issue I can see is that your code presumes a file has been uploaded. You should check whether or not a file has been uploaded, and if not, don’t try to open it and load the contents, and don’t try to add it into your email. Off the top of my head I don’t know if any of the code in there will cause the script to exit or just give a warning, but if a file upload is optional then your code shouldn’t try to process a file unless there is one.

ETA - actually, a quick three-line test script tells me that fread() will give a fatal error if fopen() wasn’t able to open the file:

Fatal error: Uncaught TypeError: fread(): Argument #1 ($stream) must be of type resource, false given in

So, as I said above, check to see whether a file was uploaded, and only try to include it in your email if it was.

1 Like