简体   繁体   中英

Uploaded file doesnt get saved in the server in php

I am trying to upload a file and save the file in the server as well as attac and send the file through email.. Attachiing and sending the file through email works fine where has the file doesnt get saved in uploads folders in the server.. How can I save the file in the server has well has send as attachment through email.. Here is the code

<form method="post" action="email-script.php" enctype="multipart/form-data" id="emailForm">
    <div class="form-group">
        <input type="text" name="name" id="name" class="form-control" placeholder="Name" >
       
    </div>
    <div class="form-group">
        <input type="email" name="email" id="email" class="form-control" placeholder="Email address" >
        
    </div>
    <div class="form-group">
        <input type="text" name="subject" id="subject" class="form-control"  placeholder="Subject" >
       
    </div>
    <div class="form-group">
        <textarea name="message" id="message" class="form-control" placeholder="Write your message here"></textarea>
      
    </div>
    <div class="form-group">
        <input type="file" name="attachment" id="attachment" class="form-control">
        <div id="attachmentError" style="color: red;font-size: 14px;display: none">attachmentError</div>
    </div>
    <div class="submit">
        <input type="submit" name="submit" onclick="return validateEmailSendForm();" class="btn btn-success" value="SUBMIT">
    </div>
</form>

email-script.php

<?php

if(isset($_POST['submit'])){
    // Get the submitted form data
    $postData = $_POST;
    $email = $_POST['email'];
    $name = $_POST['name'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $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', 'jpg', 'png', 'jpeg');
        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, DOC, JPG, JPEG, & PNG files are allowed to upload.';
        }
    }

    if($uploadStatus == 1){
        // Recipient
        $toEmail = $email;
        // Sender
        $from = 'sender@codingbirdsonline.com';
        $fromName = 'CodexWorld';
        // Subject
        $emailSubject = 'Email attachment request Submitted by '.$name;
        // Message
        $htmlContent = '<h2>Contact Request Submitted</h2>
            <p><b>Name:</b> '.$name.'</p>
            <p><b>Email:</b> '.$email.'</p>
            <p><b>Subject:</b> '.$subject.'</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){
            $statusMsg = 'Your contact request has been submitted successfully !';
        }else{
            $statusMsg = 'Your contact request submission failed, please try again.';
        }
    }
     echo '<script>alert("'.$statusMsg.'");window.location.href="./";</script>';
}

?>

Are you getting any error/warning while uploading the attachment?

Please try to debug the code after this statement: if(!empty($_FILES["attachment"]["name"])){ , like weather you are getting the attachment data in $_FILES.

Check permission of the upload directory weather it's 777(read,write,executable) or not, if not then you should give permission to the directory.

One more thing to check is: max_execution_time and upload_max_filesize in you php.ini file, increase it's value

The unlink function is used to delete files on the server, you can do well to remove or comment out that section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM