How can PHP be used to handle file uploads and send attachments via email without user input?
To handle file uploads and send attachments via email without user input, you can use PHP to first upload the file to the server, then attach the uploaded file to an email and send it using the PHP `mail()` function.
```php
<?php
// Check if file is uploaded
if(isset($_FILES['file'])){
$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
// Upload file to server
move_uploaded_file($file_tmp, 'uploads/' . $file_name);
// Email settings
$to = 'recipient@example.com';
$subject = 'File Attachment';
$message = 'Please see the attached file.';
$headers = 'From: sender@example.com';
// Attach file to email
$file = 'uploads/' . $file_name;
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$header = "From: sender@example.com\r\n";
$header .= "Reply-To: sender@example.com\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$message = "--" . $uid . "\r\n";
$message .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= $message . "\r\n\r\n";
$message .= "--" . $uid . "\r\n";
$message .= "Content-Type: application/octet-stream; name=\"" . $file_name . "\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"" . $file_name . "\"\r\n\r\n";
$message .= $content . "\r\n\r\n";
$message .= "--" . $uid . "--";
// Send email with attachment
if (mail($to, $subject, $message, $header)) {
echo 'Email sent with attachment.';
} else {
echo 'Failed to send email.';
}
}
?>
Related Questions
- How can hidden fields impact the number of available input variables in a PHP form?
- What are the potential pitfalls of using setlocale() for translating weekdays and month names in PHP?
- How can PHP developers improve the security and efficiency of newsletter scripts that send emails to multiple recipients?