Web upload file php

How to upload files with PHP correctly and securely

If you just want the sourcecode — scroll to the end of the page or click here. But I recommend reading the article to understand why I’m doing things as I do and how it works. Hey Guys, in this post, I’ll show you how to upload files to your server using HTML and PHP and validate the files. I hope it’s useful for some of you and now happy coding 🙂

Security information

First of all, the most important thing I want to tell you, the $_FILES variable in PHP (except tmp_name ) can be modified. That means, do not check e.g. the filesize with $_FILES[‘myFile’][‘size’] , because this can be modified by the uploader in case of an attack. In other words, when you validate the upload with this method, attackers can pretend that their file has another file size or type. As you can see, there is a lot we need to take care of. Maybe it’s worth considering to use an already existing service. With Uploadcare you can upload and manage files quickly and easily via their PHP integration. So, let’s move on and create our own, secure, file upload.

HTML Setup

 method="post" action="upload.php" enctype="multipart/form-data">  type="file" name="myFile" />  type="submit" value="Upload">  

That’s it. Note the action=»upload.php» , that’s the PHP script handling the upload. And we use the name myFile to identify the file in PHP.

PHP Validation

Now, let’s validate the file in the upload.php file. First of all, we have to check if there is a file passed to our script. We do this using the $_FILES variable:

if (!isset($_FILES["myFile"]))  die("There is no file to upload."); > 

But remember, for security reasons, we can’t get the filesize using $_FILES . When the user uploads the file, PHP stores it temporarily and you can get the path using $_FILES[‘myFile’][‘tmp_name’] . That’s what we use now to get the real size and type of the file.

$filepath = $_FILES['myFile']['tmp_name']; $fileSize = filesize($filepath); $fileinfo = finfo_open(FILEINFO_MIME_TYPE); $filetype = finfo_file($fileinfo, $filepath); 

Now we have the real information, let’s validate the filesize. We don’t want to allow users to upload empty files, so first, we check if the file size is greater than 0:

if ($fileSize === 0)  die("The file is empty."); > 
if ($fileSize > 3145728)  // 3 MB (1 byte * 1024 * 1024 * 3 (for 3 MB)) die("The file is too large"); > 

Great. But you’ll usually only allow specific types to be uploaded, e.g. .png or .jpg for profile images. For more flexibility, let’s create an array with all allowed file types:
(Thanks to Gary Marriott and Renorram Brandão for pointing me out, we have to store the extensions for each type here in the array so we can append it later to the filename)

$allowedTypes = [ 'image/png' => 'png', 'image/jpeg' => 'jpg' ]; 

You can find a list of MIME-Types here (It’s in german, but there is a great table with all MIME-Types and file extensions). Now let’s check if the type of the file is allowed:

if(!in_array($filetype, array_keys($allowedTypes)))  die("File not allowed."); > 

And we’re done with validating! In the last step, we move the file to our uploads directory (or wherever you want to). For this, I define a variable with my target directory, then grab the current filename and extension and build the new, target file path:

$filename = basename($filepath); // I'm using the original name here, but you can also change the name of the file here $extension = $allowedTypes[$filetype]; $targetDirectory = __DIR__ . "/uploads"; // __DIR__ is the directory of the current PHP file $newFilepath = $targetDirectory . "/" . $filename . "." . $extension; 
if (!copy($filepath, $newFilepath ))  // Copy the file, returns false if failed die("Can't move file."); > unlink($filepath); // Delete the temp file echo "File uploaded successfully :)"; 

That’s it! Now you have a secure file upload where you can strictly define which files can be uploaded and which not!

Full code

  lang="en">  charset="UTF-8">  http-equiv="X-UA-Compatible" content="IE=edge">  name="viewport" content="width=device-width, initial-scale=1.0"> Document    method="post" action="upload.php" enctype="multipart/form-data">  type="file" name="myFile" />  type="submit" value="Upload">   
 if (!isset($_FILES["myFile"]))  die("There is no file to upload."); > $filepath = $_FILES['myFile']['tmp_name']; $fileSize = filesize($filepath); $fileinfo = finfo_open(FILEINFO_MIME_TYPE); $filetype = finfo_file($fileinfo, $filepath); if ($fileSize === 0)  die("The file is empty."); > if ($fileSize > 3145728)  // 3 MB (1 byte * 1024 * 1024 * 3 (for 3 MB)) die("The file is too large"); > $allowedTypes = [ 'image/png' => 'png', 'image/jpeg' => 'jpg' ]; if (!in_array($filetype, array_keys($allowedTypes)))  die("File not allowed."); > $filename = basename($filepath); // I'm using the original name here, but you can also change the name of the file here $extension = $allowedTypes[$filetype]; $targetDirectory = __DIR__ . "/uploads"; // __DIR__ is the directory of the current PHP file $newFilepath = $targetDirectory . "/" . $filename . "." . $extension; if (!copy($filepath, $newFilepath))  // Copy the file, returns false if failed die("Can't move file."); > unlink($filepath); // Delete the temp file echo "File uploaded successfully :)"; 

Источник

PHP File Upload

However, with ease comes danger, so always be careful when allowing file uploads!

Configure The «php.ini» File

First, ensure that PHP is configured to allow file uploads.

In your «php.ini» file, search for the file_uploads directive, and set it to On:

Create The HTML Form

Next, create an HTML form that allow users to choose the image file they want to upload:

Some rules to follow for the HTML form above:

  • Make sure that the form uses method=»post»
  • The form also needs the following attribute: enctype=»multipart/form-data». It specifies which content-type to use when submitting the form

Without the requirements above, the file upload will not work.

  • The type=»file» attribute of the tag shows the input field as a file-select control, with a «Browse» button next to the input control

The form above sends data to a file called «upload.php», which we will create next.

Create The Upload File PHP Script

The «upload.php» file contains the code for uploading a file:

$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>
?>

  • $target_dir = «uploads/» — specifies the directory where the file is going to be placed
  • $target_file specifies the path of the file to be uploaded
  • $uploadOk=1 is not used yet (will be used later)
  • $imageFileType holds the file extension of the file (in lower case)
  • Next, check if the image file is an actual image or a fake image

Note: You will need to create a new directory called «uploads» in the directory where «upload.php» file resides. The uploaded files will be saved there.

Check if File Already Exists

Now we can add some restrictions.

First, we will check if the file already exists in the «uploads» folder. If it does, an error message is displayed, and $uploadOk is set to 0:

// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>

Limit File Size

The file input field in our HTML form above is named «fileToUpload».

Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0:

// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>

Limit File Type

The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:

Complete Upload File PHP Script

The complete «upload.php» file now looks like this:

$target_dir = «uploads/»;
$target_file = $target_dir . basename($_FILES[«fileToUpload»][«name»]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST[«submit»])) $check = getimagesize($_FILES[«fileToUpload»][«tmp_name»]);
if($check !== false) echo «File is an image — » . $check[«mime»] . «.»;
$uploadOk = 1;
> else echo «File is not an image.»;
$uploadOk = 0;
>
>

// Check if file already exists
if (file_exists($target_file)) echo «Sorry, file already exists.»;
$uploadOk = 0;
>

// Check file size
if ($_FILES[«fileToUpload»][«size»] > 500000) echo «Sorry, your file is too large.»;
$uploadOk = 0;
>

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) echo «Sorry, your file was not uploaded.»;
// if everything is ok, try to upload file
> else if (move_uploaded_file($_FILES[«fileToUpload»][«tmp_name»], $target_file)) echo «The file «. htmlspecialchars( basename( $_FILES[«fileToUpload»][«name»])). » has been uploaded.»;
> else echo «Sorry, there was an error uploading your file.»;
>
>
?>

Complete PHP Filesystem Reference

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.

Источник

Загрузка файлов на сервер PHP

Загрузка файлов на сервер PHP

В статье приведен пример формы и php-скрипта для безопасной загрузки файлов на сервер, возможные ошибки и рекомендации при работе с данной темой. HTML-форма отправит файл только методом POST и с атрибутом enctype=»multipart/form-data» .

Форма для загрузки сразу нескольких файлов

Файл upload.php

  • Поддерживает как одиночную загрузку файла так и множественную (multiple) без изменения кода.
  • Проверка на все возможные ошибки которые могут возникнуть при загрузке файлов.
  • Имена файлов переводятся в транслит и удаляются символы которые будут в дальнейшем мешать вывести их на сайте.
  • Есть возможность указать разрешенные и запрещенные для загрузки расширения файлов.
// Название $input_name = 'file'; // Разрешенные расширения файлов. $allow = array(); // Запрещенные расширения файлов. $deny = array( 'phtml', 'php', 'php3', 'php4', 'php5', 'php6', 'php7', 'phps', 'cgi', 'pl', 'asp', 'aspx', 'shtml', 'shtm', 'htaccess', 'htpasswd', 'ini', 'log', 'sh', 'js', 'html', 'htm', 'css', 'sql', 'spl', 'scgi', 'fcgi' ); // Директория куда будут загружаться файлы. $path = __DIR__ . '/uploads/'; if (isset($_FILES[$input_name])) < // Проверим директорию для загрузки. if (!is_dir($path)) < mkdir($path, 0777, true); >// Преобразуем массив $_FILES в удобный вид для перебора в foreach. $files = array(); $diff = count($_FILES[$input_name]) - count($_FILES[$input_name], COUNT_RECURSIVE); if ($diff == 0) < $files = array($_FILES[$input_name]); >else < foreach($_FILES[$input_name] as $k =>$l) < foreach($l as $i =>$v) < $files[$i][$k] = $v; >> > foreach ($files as $file) < $error = $success = ''; // Проверим на ошибки загрузки. if (!empty($file['error']) || empty($file['tmp_name'])) < switch (@$file['error']) < case 1: case 2: $error = 'Превышен размер загружаемого файла.'; break; case 3: $error = 'Файл был получен только частично.'; break; case 4: $error = 'Файл не был загружен.'; break; case 6: $error = 'Файл не загружен - отсутствует временная директория.'; break; case 7: $error = 'Не удалось записать файл на диск.'; break; case 8: $error = 'PHP-расширение остановило загрузку файла.'; break; case 9: $error = 'Файл не был загружен - директория не существует.'; break; case 10: $error = 'Превышен максимально допустимый размер файла.'; break; case 11: $error = 'Данный тип файла запрещен.'; break; case 12: $error = 'Ошибка при копировании файла.'; break; default: $error = 'Файл не был загружен - неизвестная ошибка.'; break; >> elseif ($file['tmp_name'] == 'none' || !is_uploaded_file($file['tmp_name'])) < $error = 'Не удалось загрузить файл.'; >else < // Оставляем в имени файла только буквы, цифры и некоторые символы. $pattern = "[^a-zа-яё0-9,~!@#%^-_\$\?\(\)\\[\]\.]"; $name = mb_eregi_replace($pattern, '-', $file['name']); $name = mb_ereg_replace('[-]+', '-', $name); // Т.к. есть проблема с кириллицей в названиях файлов (файлы становятся недоступны). // Сделаем их транслит: $converter = array( 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '', 'Ы' => 'Y', 'Ъ' => '', 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', ); $name = strtr($name, $converter); $parts = pathinfo($name); if (empty($name) || empty($parts['extension'])) < $error = 'Недопустимое тип файла'; >elseif (!empty($allow) && !in_array(strtolower($parts['extension']), $allow)) < $error = 'Недопустимый тип файла'; >elseif (!empty($deny) && in_array(strtolower($parts['extension']), $deny)) < $error = 'Недопустимый тип файла'; >else < // Чтобы не затереть файл с таким же названием, добавим префикс. $i = 0; $prefix = ''; while (is_file($path . $parts['filename'] . $prefix . '.' . $parts['extension'])) < $prefix = '(' . ++$i . ')'; >$name = $parts['filename'] . $prefix . '.' . $parts['extension']; // Перемещаем файл в директорию. if (move_uploaded_file($file['tmp_name'], $path . $name)) < // Далее можно сохранить название файла в БД и т.п. $success = 'Файл «' . $name . '» успешно загружен.'; >else < $error = 'Не удалось загрузить файл.'; >> > // Выводим сообщение о результате загрузки. if (!empty($success)) < echo '

' . $success . '

'; > else < echo '

' . $error . '

'; > > >

Возможные проблемы

Оцените статью