move uploaded file php пример
move_uploaded_file
(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)
move_uploaded_file — Перемещает загруженный файл в новое место
Описание
Такая проверка особенно важна в том случае, если существует шанс того, что какие-либо действия, производимые над загруженным файлом, могут открыть его содержимое пользователю или даже другим пользователям системы.
Список параметров
Путь к загруженному файлу.
Путь, по которому необходимо переместить файл.
Возвращаемые значения
Примеры
Пример #1 Загрузка нескольких файлов
Примечания
Если результирующий файл уже существует, он будет перезаписан.
Смотрите также
User Contributed Notes 40 notes
Security tips you must know before use this function :
First : make sure that the file is not empty.
Second : make sure the file name in English characters, numbers and (_-.) symbols, For more protection.
You can use below function as in example
?>
Third : make sure that the file name not bigger than 250 characters.
?>
Fourth: Check File extensions and Mime Types that you want to allow in your project. You can use : pathinfo() http://php.net/pathinfo
or you can use regular expression for check File extensions as in example
or use in_array checking as
?>
You have multi choices to checking extensions and Mime types.
Fifth: Check file size and make sure the limit of php.ini to upload files is what you want, You can start from http://www.php.net/manual/en/ini.core.php#ini.file-uploads
And last but not least : Check the file content if have a bad codes or something like this function http://php.net/manual/en/function.file-get-contents.php.
Do not forget this steps for your project protection.
nouncad at mayetlite dot com posted a function that uploaded a file, and would rename it if it already existed, to filename[n].ext
It only worked for files with extensions exactly three letters long, so I fixed that (and made a few other improvements while I was at it).
If you’re dealing with files uploaded through some external FTP source and need to move them to a final destination, searching php.net for «mv» or «move» won’t get you what you want. You want the rename() function.
(move_uploaded_file() won’t work, since the POST vars won’t be present.)
To nouncad at mayetlite dot com,
That function will work fine for files with a 3-character file extension. However, it is worth noting that there are valid, registered file extensions that are longer than 3 characters. For example, a JPEG file can be denoted by *.jpg (and others), but it can also have *.jpeg as a valid extension. Check out http://www.filext.com/ for a good reference of file extensions.
You may have other mechanisms for verifying a file’s extension, such as a preg_match on the whole name, using something like «/\\.(gif|jpg|jpeg|png|bmp)$/i» (more can, of course, be added if you so desire) for the most common types of images found on the web.
For blindly guaranteeing an uploaded file will be uniquely named, this seems like a fantastic way to go. Enjoy!
I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails. My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails. This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload. The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.
The secret sauce is:
1. adjust server memory size, file upload size, and post size
2. convert image to standard formate (in this case jpg) and scale
htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M
In other words, move_uploaded_file() executes as if it’s root, not the user under which the web server is operating or the owner of the script that’s executing.
I have looked at a lot of the file upload code listed below and other php documentation and have developed hopefully a robust single file upload routine. I will later update with a multi file upload. I have modestly tested the code.
// 5MB maximum file size
$MAXIMUM_FILESIZE = 5 * 1024 * 1024 ;
// Valid file extensions (images, word, excel, powerpoint)
$rEFileTypes =
«/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|
ppt|pptx)<1>$/i» ;
$dir_base = «/your/file/location/» ;
php_value post_max_size 16M
php_value upload_max_filesize 6M
You may also need to extend the execution time depending upon the amount of data being transferred.
(sorry if spacing of code is a little off. it was hard to make the note editor like the code style.)
Загрузка файлов на сервер в PHP
Наверняка, Вы часто загружали различные файлы на сайты. Например, загружали аватары на форуме, фотографии в социальных сетях, различные видеоролики на видеохостинги, просто файлы на файлообменники. И вот в этой статье Вы узнаете, как загрузить файлы на сервер в PHP. Именно через PHP в большинстве случаев это и реализуют.
Теперь пишем скрипт «loading.php«, в котором мы ещё загружать файл не будем, а пройдёмся немного по различным важным моментам, которые надо обязательно учитывать, иначе может пострадать безопасность:
И все эти параметры присутствуют для каждого загружаемого файла (каждые из которых представляют собой массив в двумерном массиве $_FILES).
Теперь давайте уже закончим с загрузкой файлов на сервер в PHP, и для этого напишем такой код («loading.php«):
То есть вначале мы задаём путь к загружаемому файлу на сервере. Здесь мы хотим поместить файл в директорию «images» с тем же именем, что и было раньше у файла. А функцией move_uploaded_file() мы перемещаем файл в выбранную нами директорию из его временного хранилища.
Однако, обратите внимание, это очень важно! Так использовать код ни в коем случае нельзя, иначе Вашему сайту будет угрожать серьёзная опасность! Фактически, на данный момент может быть загружено абсолютно всё, что угодно: любые исполняемые файлы, скрипты, HTML-страницы и другие весьма опасные вещи. Поэтому обязательно надо проверять загружаемые файлы на сервер очень тщательно. И вот этим мы и займёмся в следующей статье. Поскольку тема очень важная, то я советую Вам подписаться на обновления, чтобы не пропустить эту статью.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 62 ):
Вот посмотри тут может яснее будет http://saitsozdanie.ru/php/php-zagruzka-fajlov-na-server.html
а что прописывается в пункте [somename] и [tmp_name]?? в [name] пишется имя файла, что на форме?
тоесть [tmp_name] оставляем пустым или так и писать [tmp_name]? (Выберите фоновый рисунок: ) Здесь [somename]=path? а что пишется тогда в после [name]?
— вот так, tmp_name нужен для того, чтобы потом можно было скопировать файл из этого временного пути в уже какую-то папку на сайте.
————— «; PRINT «Вас приветствует «.$_POST[‘firstname’]; PRINT «
Учитесь искать ошибки самостоятельно: http://myrusakov.ru/php-finderror.html Это действительно очень важно! И на будущее. Ваши ошибки происходят от того, что Вы изначально неправильно работаете. Вот правильный подход к программированию: http://myrusakov.ru/how-programming.html
Михаил, помогите с загрузкой нескольких файлов на сервер.
а как-то более красивше. ну скажем, нельзя же предусмотреть, сколько изображений клиент захочет загрузить. как работать с multiple?
И так красиво. А поля можно добавлять по мере их заполнения через JavaScript.
У Вас есть статья, как добавлять эти поля после заполнения верхних через яву?
Через onclick можно и проверку value, если оно не пустое, то добавить ещё одно поле, иначе ничего не делать. Если знаете JS, то прекрасно меня поймёте. Если нет, то статей подобных у меня нет.
Здравствуйте, у меня php выдает ошибки: [[ Warning: move_uploaded_file(images/img.png) [function.move-uploaded-file]: failed to open stream: No such file or directory in I:\home\test1.ru\www\loading.php on line 3 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘I:\tmp\phpF453.tmp’ to ‘images/img.png’ in I:\home\test1.ru\www\loading.php on line 3 ]]
Директории не существует, куда Вы отправляете файл.
Мне кто-нибудь поможет. Я даж заплачу за потраченное время!
Михаил, а почему бы вам не сделать свой хостинг изображений специально для форума, чтобы люди могли загружать изображения и вставлять ссылку в сообщение на форуме? Было бы очень удобно а главное оригинально так как никто не додумается такое сделать и вы будете единственным с такой возможностью
Идея не нова, но я так сделаю. Но всё это будет не раньше весны.
Будет интересно посмотреть
В статье ошибка, в самом начале, пропущена буква «О» в слове «видеОхостинги». Мелочь, конечно. 🙂
У меня такая проблема: записываю файл на сервер, всё записывается нормально. Но если попытаться снова записать с тем же именем, то он не перезаписывается. Но время файла (атрибуты) обновляется. Не подскажете как быть?
У меня получается что изображение с веб камеры сохраняется допустим с именем 123.jpg. если такого файла нет, то всё нормально. А если я хочу это фото обновить. То есть перезаписать по верх старого, он только атрибуты файла меняет. А само изображение не перезаписывает. У меня подозрение что я просто что то не так делаю. Может сперва старый файл удалить нужно?
Попробуйте так, для удаления используйте unlink().
Так и сделал. Всё получилось! Благодарю.
У меня проблема такая: не могу загрузить на сервер. На всех папках стоит право доступа 777. Код: http://pastebin.com/p6Ash6BN
Михаил, такой вопрос. Фотография выводится на одной странице со ссылкой на статью, как сделать, так чтобы эта же картинка выводилась на странице со статьей??
Здравствуйте, Михаил! У меня вопрос: как сделать своё уникальное имя для каждого файла? То есть что бы не было такого, что бы два пользователя загрузили разные файлы с одинаковым именем.
Генерировать это имя в PHP, например, используя это: http://myrusakov.ru/php-uniqid.html
А может ли быть так, что функция uniqid вернет такой же ключ как и возвращал раньше?
Чисто теоретически всё может быть, но на практике я думаю, что таких случаев не было.
Функция Move_uploaded_file
Функция Move_uploaded_file перемещает загруженный файл в новое место.
Функция Move_uploaded_file проверяет, является ли файл Filename загруженным на сервер (переданным по протоколу HTTP POST). Если файл действительно загружен на сервер, он будет перемещен в место, указанное в аргументе Destination.
Такая проверка особенно важна в том случае, если существует шанс того, что какие-либо действия, производимые над загруженным файлом, могут открыть его содержимое пользователю или даже другим пользователям системы.
Параметр Filename содержит путь к загруженному файлу.
Параметр Destination содержит путь, по которому необходимо переместить файл.
Функция Move_uploaded_file возвращает TRUE в случае успеха. Если Filename не является загруженным файлом, никаких действий не предпринимается и функция Move_uploaded_file возвращает FALSE.
Если Filename является загруженным файлом, но не может быть перемещен по каким-либо причинам, никаких действий не предпринимается и возвращается FALSE с отображением предупреждения.
Если результирующий файл уже существует, он будет перезаписан.
Функция Move_uploaded_file принимает во внимание директиву Open_basedir. Тем не менее, ограничения накладываются лишь на параметр Destination, чтобы разрешить перемещение загруженных файлов, так как параметр Filename может конфликтовать с этими ограничениями. Функция Move_uploaded_file гарантирует безопасность этой операции, работая лишь с теми файлами, которые были загружены через PHP.
Загрузка файлов на сервер PHP с помощью самого простого функционала
Дата публикации: 2017-02-23
Зачем нам серверное пространство?
Не думаю, что такой вопрос может возникнуть у кого-то. Но всякое бывает! Скажу только, что различные решения для загрузки чего-либо на серверное пространство востребованы в сфере сайтостроения. Благо, за примерами бегать далеко не надо.
Все мы являемся пользователями той или иной социалки. Паутинки этих «липких» сетей окутали, затронули всех и каждого. Чтобы загрузить в свой профиль фотки с отдыха, с семейного торжества и другие доказательства успешной жизни, используется загрузка файлов на сервер через PHP.
Кроме этого подобный функционал реализован и на обычных сайтах с поддержкой комментариев. Пользователю предоставляется возможность украсить свой аккаунт аватаркой, выделяющей его среди остальной аудитории. В общем, по всей Сети на серверное пространство грузят все и каждый.
Проще не бывает!
Любое программное решение можно «обвешать» стольким количеством дополнительного функционала, что порой автор и сам забывает, какая из функций программы является основной.
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC
В курсе 39 уроков | 15 часов видео | исходники для каждого урока
Но мы постараемся так не закапываться. Рассмотрим основы PHP загрузки файла на сервер на примере, который не «отяжелен» различными фичами. То есть это будет просто загрузчик.
Загрузка файлов на сервер
Содержание
User Contributed Notes 32 notes
Example:
( ‘Content-Type: text/plain; charset=utf-8’ );
echo ‘File is uploaded successfully.’ ;
Clarification on the MAX_FILE_SIZE hidden form field:
PHP has the somewhat strange feature of checking multiple «maximum file sizes».
The two widely known limits are the php.ini settings «post_max_size» and «upload_max_size», which in combination impose a hard limit on the maximum amount of data that can be received.
Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
Be reminded that this mime type can easily be faked as PHP doesn’t go very far in verifying whether it really is what the end user reported!
My best bet would be for you to check the extension of the file and using exif_imagetype() to check for valid images. Many people have suggested the use of getimagesize() which returns an array if the file is indeed an image and false otherwise, but exif_imagetype() is much faster. (the manual says it so)
IE on the Mac is a bit troublesome. If you are uploading a file with an unknown file suffix, IE uploads the file with a mime type of «application/x-macbinary». The resulting file includes the resource fork wrapped around the file. Not terribly useful.
(There is probably a better way to do it, but this solved my problem):
If «large files» (ie: 50 or 100 MB) fail, check this:
It may happen that your outgoing connection to the server is slow, and it may timeout not the «execution time» but the «input time», which for example in our system defaulted to 60s. In our case a large upload could take 1 or 2 hours.
Additionally we had «session settings» that should be preserved after upload.
1) You might want review those ini entries:
* session.gc_maxlifetime
* max_input_time
* max_execution_time
* upload_max_filesize
* post_max_size
2) Still fails? Caution, not all are changeable from the script itself. ini_set() might fail to override.
You can see that the «upload_max_filesize», among others, is PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set():
http://www.php.net/manual/en/configuration.changes.modes.php
3) Still fails?. Just make sure you enabled «.htaccess» to overwrite your php settings. This is made in the apache file. You need at least AllowOverride Options.
You will necessarily allow this manually in the case your master files come with AllowOverride None.
Depending on the system, to allow «large file uploads» you must go up and up and up and touch your config necessarily up to the apache config.
These work for me, for 100MB uploads, lasting 2 hours:
In the example,
— As I last 1 to 2 hours, I allow 3 hours (3600×3)
— As I need 100MB, I allow air above for the file (110M) and a bit more for the whole post (120M).
For those of you trying to make the upload work with IIS on windows XP/2000/XP Media and alike here is a quick todo.
2) In windows explorer browse to the upload directory created above and share it. To do that execute the following substeps.
a) Right click the folder click «sharing and security. »
b) Check ‘Share this folder on the network’
c) Check ‘Allow network users to change my files’ ( THIS STEP IS VERY IMPORTANT )
d) click ‘ok’ or ‘apply’
3) you can then go in the IIS to set read and write permissions for it. To do that execute the followin substeps.
a) Open IIS (Start/Controp Panel (classic View)/ Admistrative tools/Internet Information Service
b) Browse to your folder (the one we created above)
c) right click and select properties.
d) in the Directory tab, make sure, READ, WRITE, AND DIRECTORY BROWSING are checked.
e) For the security freaks out there, You should also make sure that ‘execute permissions:’ are set to Script only or lower (DO NOT SET IT TO ‘script and executable)'( that is because someone could upload a script to your directory and run it. And, boy, you do not want that to happen).
Send me feed back it if worked for you or not so that I can update the todo.
PS: BIG thanks to oportocala
Using /var/www/uploads in the example code is just criminal, imnsho.
One should *NOT* upload untrusted files into your web tree, on any server.
Nor should any directory within your web tree have permissions sufficient for an upload to succeed, on a shared server. Any other user on that shared server could write a PHP script to dump anything they want in there!
One’s code should INSPECT the actual file to see if it looks kosher.
For example, images can quickly and easily be run through imagegetsize and you at least know the first N bytes LOOK like an image. That doesn’t guarantee it’s a valid image, but it makes it much less likely to be a workable security breaching file.
For Un*x based servers, one could use exec and ‘file’ command to see if the Operating System thinks the internal contents seem consistent with the data type you expect.
I’ve had trouble in the past with reading the ‘/tmp’ file in a file upload. It would be nice if PHP let me read that file BEFORE I tried to move_uploaded_file on it, but PHP won’t, presumably under the assumption that I’d be doing something dangerous to read an untrusted file. Fine. One should move the uploaded file to some staging directory. Then you check out its contents as thoroughly as you can. THEN, if it seems kosher, move it into a directory outside your web tree. Any access to that file should be through a PHP script which reads the file. Putting it into your web tree, even with all the checks you can think of, is just too dangerous, imnsho.
There are more than a few User Contributed notes here with naive (bad) advice. Be wary.