test PHP mail() - php

I have a mail submission script that is working exactly as expected on both a dev environment and live with one exception. I am getting conflicting results from the mail() test conditional on the live environment vs the dev environment.
On my dev environment it redirects to $ThanksURL on success. On the live server even through the mail is successfully the script proceeds to the else statement and redirects back to the form page.
This has been driving me crazy so any ideas as to why would be most welcome.
Snippet of the issue:
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ header("Location: $ThanksURL");
exit;
}else{ $_SESSION['error'] .= " There has been a problems submitting your details. <br />";
header("Location: $form");
exit;
}// end if ok
Script in full:
<?php
session_start();
$form = 'index.php';
$_SESSION['error'] = "The following errors have occured: ";
if(isset($_POST['submitted'])) {
// email fields: to, from, subject, and so on
// Here
$from = "Form Feedback <******#gmail.com>";
$to = "******#gmail.com";
$subject = "Competition";
$ThanksURL = "thankyou.html";
$headers = "From: $from";
$returnpath = "-f" . $from;
$attachment = 0; // is there an attachement
//form fields
$emailAddress = stripslashes($_POST['email']);
$phone = stripslashes($_POST['phone']);
$comments = stripslashes($_POST['comments']);
//basic message info
$message = "Info submitted:\n\nEmail address: " .$emailAddress ."\n\nPhone number: " .$phone."\n\nComments:\n ".$comments. "\n\n";
if($_FILES['attachment']['error'] == 4) {
$message .="No attachement included";
}else{
// test file type and size for submission
$allowedExts = array("doc", "docx", "pdf", "txt");
$extension = end(explode(".", $_FILES['attachment']["name"]));
if ((($_FILES['attachment']["type"] == "application/msword")
|| ($_FILES['attachment']["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")//docx mime
|| ($_FILES['attachment']["type"] == "application/pdf")
|| ($_FILES['attachment']["type"] == "application/plain")
|| ($_FILES['attachment']["type"] == "text/plain"))
&& ($_FILES['attachment']["size"] < 2097152 )
&& in_array($extension, $allowedExts)){
// 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/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// prepare the files uplaod
$message .= "--{$mime_boundary}\n";
$fp = #fopen($_FILES['attachment']['tmp_name'],"rb");
$data = #fread($fp,filesize($_FILES['attachment']['tmp_name']));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".$_FILES['attachment']['name']."\"\n"."Content-Description: ".$_FILES['attachment']['name']."\n" ."Content-Disposition: attachment;\n" . " filename=\"".$_FILES['attachment']['name']."\";size=".$_FILES['attachment']['size'].";\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
}else{
$_SESSION['error'] .= "Error: " . $_FILES["attachment"]["name"] . " is not a doc, docx, pdf or txt file or is larger than 2mb. Please resubmit <br />";
header("Location: $form");
exit;
}
}//file conditional
//prepare mail
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){
header("Location: $ThanksURL");
exit;
}else{
$_SESSION['error'] .= " There has been a problems submitting your details. <br />";
header("Location: $form");
exit;
}// end if ok
}// end sub
?>

Sorry to say this, but php mail can return something else on success than true or false, like mentioned in the php manual comment. Also, it is known to return false on success on some situations, too.
PHP mail() is a kludgy function from many different angles, and personally I would advise against using it in production systems. There are quite a few alternatives, such as swift mailer, PHP mailer, Zend_Mail etc.
However, if you want to use it, you should definitely log the actions and in this case, return values, and not have # to hide your return values.
As a summary, in this case mail() returned an empty string, and not true or false.

Related

PHP Email script to send emails with attachment not sending video files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I found a script from codexworld to send an email with an attachment using PHP. I did edit it slightly as I needed to add a few more inputs, but it works with one exception, it won't send video files. I will send picture and document files, but no video. I keep getting the status message: "Your contact request submission failed, please try again."
Can anyone look at this code and tell me why this is happening and how to fix it?
<?php
$postData = $uploadedFile = $statusMsg = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$email = $_POST['email'];
$name = $_POST['name'];
$category = $_POST['category'];
$location=$_POST['location'];
$URL = $_POST['URL'];
$message = $_POST['message'];
$hauntname = $_POST['hauntname'];
// Check whether submitted data is not empty
if(!empty($email) && !empty($name) && !empty($message)){
// 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('m4p', 'mp4', 'jpg', 'png', 'jpeg', 'mov');
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.\r\n";
}
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, only image or video files are allowed to be uploaded.\r\n";
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = 'submission#hyhpawardshow.com';
// Sender
$from = $email;
$fromName = $name;
// Subject
$emailSubject = $category.' submission from '.$name;
// Message
$htmlContent = '<h2>Submission</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Haunt Name:</b> '.$hauntname.'</p>
<p><b>Location:</b> '.$location.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Category:</b> '.$category.'</p>
<p><b>URL:</b> '.$URL.'</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 !\r\n";
$msgClass = 'succdiv';
$postData = '';
}else{
$statusMsg = "Your contact request submission failed, please try again.\r\n";
}
}
}
}else{
$statusMsg = 'Please fill all the fields.';
}
}
?>
So, as it turns out, it was not my code at all, but the mail server. The max file size is messed up and that is what was causing it to fail. I'm currently working with my hosting tech support to have this resolved.
Thank you all to tried to help. I truly appreciate it.

mail() is Incorrectly Sending Emails to cPanel Default Account

I purchased a domain from GoDaddy and linked it to Office 365 (via MX records). This means I have several email accounts in Outlook that are #mydomain.com.
Example Outlook accounts:
sales#mydomain.com
contact#mydomain.com
matt#mydomain.com
I can send/receive emails through those accounts.
My website is hosted on basic web hosting with a cPanel installation, which means I was given a "default" email account. For example: default#mydomain.com. I wrote a PHP script on my website (contact form) that sends emails via mail() to contact#mydomain.com.
However all the emails are sent to the default cPanel account default#mydomain.com instead of the Outlook account contact#mydomain.com.
To test, I tried sending the emails to my personal account that is not hosted on mydomain and it works as expected. Emails are sent instantly.
How come my website incorrectly send emails to the Outlook accounts? Thanks for your time.
EDIT:
The script was requested:
<?php
$uploadedFile = $statusMsg = '';
if (isset($_POST['submit']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if(!empty($first_name) && !empty($last_name) && !empty($message))
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$uploadStatus = 1;
if(!empty($_FILES["attach"]["name"]))
{
$targetDir = "uploads/";
$fileName = basename($_FILES["attach"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["attach"]["tmp_name"], $targetFilePath))
{
$uploadedFile = $targetFilePath;
}
else
{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}
if($uploadStatus == 1)
{
$name = $first_name.' '.$last_name;
$mailTo = "contact#mydomain.com";//changed to my real outlook account
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Phone:</b> '.$phone.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $name"." <".$email.">";
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($mailTo, "Contact Form Submission from ".$name, $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($mailTo, 'Contact Form Submission from '.$name, $htmlContent, $headers);
}
// If mail sent
if($mail)
{
$statusMsg = "Your message has been sent. Thanks!";
}
else
{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
}
else
{
$statusMsg = 'Please enter a valid email address.';
}
}
else
{
$statusMsg = "Please fill out the required information.";
}
}
?>
The solution was to change my cPanel "Email Routing" option to "Remote" in order for all local emails to first check with the MX records.

send email via php only once

i studying on PHP now, and want to learn how to send email from diretory web to someone email with attachment,,
i try with this code, and it worked, but when i try to send email again to other email address, it didnt send again and need a few hour (or few moment, i didnt know exactly, just my guess) to worked again. i didnt know what the real problem is?
if someone have same problem with me, please share here. thanks in advance. and sorry for my bad english.
this is my code,
<?php
session_start();
if (isset($_SESSION['xx']) && $_SESSION['xx'] == session_id() ) {
//panggil file config.php untuk menghubung ke server
include('config.php');
//catch data from the form
$nmMhs = $_POST['name'];
$sexMhs = (isset($_POST['sex']))?$_POST['sex']:"";
$almMhs = $_POST['address'];
$tlpMhs = $_POST['telp'];
$date=$_POST['tgl']; $month=$_POST['bln']; $year=$_POST['thn'];
$tgllhrMhs = $date.'-'.$month.'-'.$year;
$emlMhs = $_POST['email'];
$prodiMhs = (isset($_POST['prodi']))?$_POST['prodi']:"";
$statMhs = (isset($_POST['stat']))?$_POST['stat']:"";
$klsMhs = (isset($_POST['kelas']))?$_POST['kelas']:"";
$orgMhs = $_POST['org'];
$sakitMhs = $_POST['sick'];
$almetMhs = (isset($_POST['almet']))?$_POST['almet']:"";
$kausMhs = (isset($_POST['kaos']))?$_POST['kaos']:"";
//send email
$email_to = $emlMhs; // The email you are sending to (example)
$email_from = "someone#gmail.com"; // The email you are sending from (example)
$email_subject = "subject of the messages"; // The Subject of the email
$email_txt = "hello everybody, this is a message"; // Message that the email has in it
//email attachment
$fileatt = "path/file"; // Path to the file (example)
$fileatt_type = "application/msword"; // File Type
$fileatt_name = "file.docx"; // Filename that will be used for the file as the attachment
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers="From: $email_from"; // Who the email is from (example)
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $email_txt;
$email_message .= "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
//save data to database
if($prodiMhs == "S1 Manajemen"){
$query = mysql_query("insert into mhs_manajemen values(null, '$nmMhs', '$sexMhs', '$almMhs', '$tlpMhs', '$tgllhrMhs', '$emlMhs', '$prodiMhs', '$statMhs', '$klsMhs', '$orgMhs', '$sakitMhs', '$almetMhs', '$kausMhs' )") or die(mysql_error());
if ($query) {
mail($email_to,$email_subject,$email_message,$headers);
echo "<script type='text/javascript'>
window.alert('Data has been inputed')
window.location.href='isi_data.php';
</script>";
}
}
if($prodiMhs == "S1 Administrasi Niaga"){
$query = mysql_query("insert into mhs_administrasi values(null,'$nmMhs', '$sexMhs', '$almMhs', '$tlpMhs', '$tgllhrMhs', '$emlMhs', '$prodiMhs', '$statMhs', '$klsMhs', '$orgMhs', '$sakitMhs', '$almetMhs', '$kausMhs' )") or die(mysql_error());
if ($query) {
mail($email_to,$email_subject,$email_message,$headers);
echo "<script type='text/javascript'>
window.alert('Data has been inputed')
window.location.href='isi_data.php';
</script>";
}
}
} else {
session_destroy();
echo "<script type='text/javascript'>
window.alert('<b>Access denied! Please login first!<b>')
window.location.href='index.php';
</script>";
}
?>
If you use else if and else instead of just an if the script will only execute one of the 2 blocks of code. So try putting else if directly after the closing curly bracket of if($prodiMhs == "S1 Manajemen"){. Basicly change if($prodiMhs == "S1 Administrasi Niaga"){ to else if($prodiMhs == "S1 Administrasi Niaga"){ More info on elseif and else.
I hope this helps you.

PHP Order Form - Email with Attachment

I am trying to create an order form which when complete, passes you on to the order.php page (sends the email), where you are then passed on to paypal. Everything was working fine until i tried to add attachments, when i added the code for attachment, the email is no longer sent.
<?php
$to = 'hidden' ;
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Distinctive Writers - Contact Form";
$tprice = $_REQUEST['tprice'] ;
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"number"} = "number";
$fields{"subject"} = "subject";
$fields{"doctype"} = "doctype";
$fields{"spec"} = "spec";
$fields{"grade"} = "grade";
$fields{"days"} = "days";
$fields{"due"} = "due";
$fields{"pages"} = "pages";
$fields{"price"} = "price";
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
if (file_exists($tmp_name)){
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$headers2 = "From: noreply#YourCompany.com";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.oursite.com";
if($from == '') {print "You have not entered an email, please go back and try again";}
else {
if($name == '') {print "You have not entered a name, please go back and try again";}
else {
$send = mail($to, $subject, $body, $headers, $message);
$send2 = mail($from, $subject2, $autoreply, $headers2);
}
}
if(!mail($to, $subject, $body, $headers, $message)){
print "ERROR!!";
}
}
?>
I recommend PHPMailer too as mentioned by pc-shooter
then you can use
$mail = new PHPMailer();
then you can utilize either one of these two
$mail->AddStringAttachment($string,$filename)
$mail->AddAttachment($path);
Something to keep in mind, something else might be blocking the email. if the mail function returns TRUE then the mail was dispatched.

PHP mailer script error

I have an submit page where client scan submit a fillable PDF form along with a photo, using the attached mailer script. The form uploads to the server correctly, however when it is sent to the client, the PDF is blank.
<?php
// did files get sent
if(isset($_FILES) && (bool) $_FILES) {
// define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
// loop through all the files
foreach($_FILES as $name=>$file) {
// define some variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
// check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
// move this file to the server YOU HAVE TO DO THIS
$server_file = "/home/castmeb1/public_html/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
// add this file to the array of files
array_push($files,$server_file);
}
// define some mail variables
$to = "castmebg#gmail.com";
$from = "castmebg#gmail.com";
$subject ="test attachment";
$msg = "Please see attached";
$headers = "From: $from";
// define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// tell the header about the boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// part 1: define the plain text email
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
// part 2: loop and define mail attachments
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send the email
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
die();
}
?>
Thanks,
JB
if(isset($_FILES) && (bool) $_FILES) {
is an invalid test for a successful upload. The $_FILES array is always set, and assuming a file upload ATTEMPT was made, the array will NEVER be empty.
You should check for errors like this:
if ($_FILES['name_of_file_field']['error'] === UPLOAD_ERR_OK) {
... file was successfully uploaded ...
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php

Categories