загрузка файла — PHP: если $ _FILES пусто, пропустите код. ОШИБКА: Но это все равно пропускается, когда $ _FILES не пусто

Я пытаюсь дать моей контактной форме возможность отправить форму без вложенного файла.
Мне было рекомендовано использовать что-то вроде этого:

if(isset($_FILES["fileToUpload"]) && !empty($_FILES["fileToUpload"]["tmp_path"])){
// code here
}

Я попытался реализовать это в моей форме, кажется, что он работает правильно при пропуске кода, когда я не загружаю файл, но когда я загружаю файл, проверки больше не работают и позволяют мне отправлять файлы любого формата и не проверить это уже существует.

Что я делаю неправильно и правильно ли реализован код, если нет, что мне нужно изменить?


PHP-код


$to = 'email123@gmail.com';
$subject = 'Website Submission';
$company_name = $_POST['company_name'];
$ref = $_POST['ref'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$fromweb = $_POST['fromweb'];
$qr = $_POST['qr'];
$message = $_POST['message'];

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image

if(isset($_FILES["fileToUpload"]) && !empty($_FILES["fileToUpload"]["tmp_path"])){

// Check if file already exists
if (file_exists($target_file)) {
echo '<p style="color:red;">Sorry, file already exists.</p>';
$uploadOk = 1;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 150000000) { // Byte = 150MB
echo '<p style="color:red;">Sorry, your file is larger than 150MB.</p>';
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" && $imageFileType != "eps" && $imageFileType != "tiff"&& $imageFileType != "psd") {
echo '<p style="color:red;">Sorry, only JPG, JPEG, PNG, GIF, TIF, EPS and PSD files are allowed.</p>';
if($imageFileType !=null) {
echo "no file uploaded";
}
$uploadOk = 0;

}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
die('<p style="color:red;">Sorry, your file was not uploaded.</p>');
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo '<p style="color:red;">Sorry, there was an error uploading your file.</p>';

}
}

} //skip code when no file uploaded$body = <<<EMAIL

<html>

<p><h3>Email from website.</h3></p>

<p><strong>Company Name:</strong> $company_name</p>
<p><strong>Ref:</strong> $ref</p>
<p><strong>Website:</strong> $website</p>
<p><strong>Email:</strong> $email</p>
<p><strong>Tel:</strong> $tel</p>
<p><strong>Create From Website:</strong> $fromweb</p>
<p><strong>Add QR Code:</strong> $qr</p>
<p><strong>File Location:</strong> $target_file</p>
<p><strong>Message:</strong> $message</p></html>

EMAIL;

/* Attachment File
Attachment location */
$file_name = $target_file;

$path = $file_name;

// Read the file content

$file = $file_name;
$file_size = filesize($file_name);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));

/* Set the email header
Generate a boundary */
$boundary = md5(uniqid(time()));

// Email header
// $header = "From: ".$from_name." \r\n";

$header = 'From: <noreply@email.co.uk>' . "\r\n";
// $header .= "Reply-To: ".$reply_to."\r\n";
$header .= "MIME-Version: 1.0\r\n";

// Multipart wraps the Email Content and Attachment
$header .= "Content-Type: multipart/mixed;\r\n";
$header .= " boundary=\"".$boundary."\"";

$message .= "This is a multi-part message in MIME format.\r\n\r\n";
$message .= "--".$boundary."\r\n";

/* Email content
Content-type can be text/plain or text/html */
// $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";

// this header below is the important one if you want HTML message
$message .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "$body\r\n";
$message .= "--".$boundary."\r\n";

/* Attachment
Edit content type for different file extensions */
$message .= "Content-Type: application/xml;\r\n";
$message .= " name=\"".$file_name."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment;\r\n";
$message .= " filename=\"".$file_name."\"\r\n";
$message .= "\r\n".$content."\r\n";
$message .= "--".$boundary."--\r\n";if ($_POST['submit']){
mail($to, $subject, $message, $header);
echo '<p style="color:green;">Message Successfully Sent.</p>';
} else {
die('<p>Error Email Not Sent</p>');
}

1

Решение

Чтобы ответить на ваш вопрос для @Ares Draguna:

Когда правильный тип файла загружен, то вы устанавливаете $uploadOk до 0 в этой части:

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" && $imageFileType != "eps" && $imageFileType != "tiff"&& $imageFileType != "psd") {
echo '<p style="color:red;">Sorry, only JPG, JPEG, PNG, GIF, TIF, EPS and PSD files are allowed.</p>';
if($imageFileType !=null) {
echo "no file uploaded";
}
$uploadOk = 0;
}

Так $uploadOk = 0; должно быть во втором if-Statement, а не снаружи. Так и должно быть:

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" && $imageFileType != "eps" && $imageFileType != "tiff"&& $imageFileType != "psd") {
echo '<p style="color:red;">Sorry, only JPG, JPEG, PNG, GIF, TIF, EPS and PSD files are allowed.</p>';
if($imageFileType !=null) {
echo "no file uploaded";
$uploadOk = 0;
}
}

Надеюсь это поможет!

0

Другие решения

Я не понимаю, как будет работать код. Вы проверяли информацию о пути к файлу, который еще не существует. $target_file не существует, пока вы не переместите туда загрузку. Недавно загруженный файл можно найти только на $_FILES["fileToUpload"]["tmp_path"] до Вы перемещаете это (что вы делаете в конечном счете).

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector