file_get_contents creating an empty file
how can I prevent file_get_contents from creating an empty file when being used as a test condition in an if clause?
An empty file is created regardless, which causes a subsequent call in a different method to getimagesize() to fail.
The problem is, that as I have my code setup, the first time it is called will determine to save an image or to display a previously saved imaged. This is in part dependent on the presence of a file. As an empty file is created, this causes problems when calling my code subsequent times.
Is the easiest way to add a check if the file exists and is greater than 0?
Regardless of if my code works, file_get_contents will still output an error. This error is accounted for and dealt with(by my if condition), so I would like to avoid the error interrupting the output of my application if possible. Is there a way to turn this off without hiding actual errors?
2 Answers 2
Check if the file exists using file_exists :
It isn’t file_get_contents() that is creating an empty file, it is file_put_contents().
file_put_contents() will create a file even if the second parameter is empty. Hence, empty file.
You’ll need to check the file exists first.
The easiest fix would be to move file_put_contents() inside the conditional, so that it only creates a file if there are contents.
Now, this still leaves you with a bunch of problems.
Работа с файлами в PHP
Чтение файла: file_get_contents()
С помощью функции file_get_contents() можно получить содержимое файла:
Также мы можем получить html-код какой-либо страницы в интернете:
Но работает это далеко не для всех сайтов, у многих есть защита от такого примитивного парсинга.
Чтение файла: file()
Функция file() позволяет получить содержимое файла в виде массива. Разделителем элементов является символ переноса строки.
Создадим в корне сайта файл data.txt со следующим содержимым:
Теперь запустим скрипт index.php со следующим кодом:
При запуске этого скрипта мы получим в браузере:
Заметили, что у первых двух строк длина 7 символов вместо пяти? Это из-за того, что каждая строка содержит в конце символы переноса строки.
Чаще всего они нам не нужны, поэтому их можно убрать, передав вторым параметром константу FILE_IGNORE_NEW_LINES :
Теперь у всех строк будет по 5 символов.
Если нам необходимо получить только заполненные строки в файле и пропустить пустые, можно передать вторым параметром константу FILE_SKIP_EMPTY_LINES :
Разумеется, мы можем передать сразу две константы:
Создание файла и запись в файл: file_put_contents()
Функция file_put_contents() позволяет создать файл и заполнить его данными.
Чтобы не перезаписывать данные, а добавить их в конец файла, нужно передать третьим параметром константу FILE_APPEND :
Также вторым параметром можно передать массив:
Но этот вариант не очень удобен, поскольку все элементы массива запишутся подряд, без каких-либо разделителей. Чтобы их добавить, можно использовать функцию implode:
Создание папки или структуры папок
Создать папку можно с помощью функции mkdir() (make directory):
Кроме этого, второй параметр может игнорироваться при заданной umask (пользовательская маска (user mask), которая нужна для определения конечных прав доступа). В этом случае принудительно сменить права можно функцией chmod() :
Также мы можем создать структуру папок рекурсивно, для этого нужно третьим параметром передать true :
Но в этом случае права доступа будут заданы только для конечной папки. Для изменения прав у каждой из папок придётся указывать права вручную:
Проверка существования файла или папки
Проверить существование папки или файла можно с помощью функции file_exists() :
Если вы хотите проверить существование только папки или только файла, для этого есть специальные функции is_dir() и is_file() :
Проверка прав доступа
Функции is_readable() и is_writable() проверяют, есть ли у пользователя, от имени которого запущен PHP, права на чтение и запись файла или папки:
Копирование, перенос и удаление файла
Для удаления файлов используется функция unlink() :
Чтобы скопировать файл, используем функцию copy() :
Для переименования и переноса файла в другую папку используется функция rename() :
Работа с файлами с помощью fopen()
Но иногда возникают ситуации, когда нам необходимы более продвинутые инструменты. Например, если у нас есть большой текстовый файл и мы хотим читать его построчно, а не весь сразу, для экономии оперативной памяти.
Итак, открыть (или создать и открыть) файл можно с помощью функции fopen() :
Для построчного чтения файла используется функция fgets() :
Также в PHP существует множество других полезных функций, работающих с дескриптором файла. Почитать о них можно в документации.
PHP File Create/Write
In this chapter we will teach you how to create and write to a file on the server.
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
The example below creates a new file called «testfile.txt». The file will be created in the same directory where the PHP code resides:
Example
PHP File Permissions
If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.
The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.
The example below writes a couple of names into a new file called «newfile.txt»:
Example
If we open the «newfile.txt» file it would look like this:
PHP Overwriting
Now that «newfile.txt» contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file «newfile.txt», and write some new data into it:
Example
If we now open the «newfile.txt» file, both John and Jane have vanished, and only the data we just wrote is present:
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
HTML:
22 Answers 22
Here’s a check-list for file uploading in PHP:
Make sure your close tags.
Make sure your file input tag has a NAME attribute. An ID attribute is NOT sufficient! ID attributes are for use in the DOM, not for POST payloads.
Make sure you are not using Javascript to disable your field on submission
Make sure you’re not nesting forms like
Check your HTML structure for invalid/overlapping tags like
Also make sure that the file you are uploading does not have any non-alphanumeric characters in it.
You could potentially try avoiding underscores ( _ ) in the name=»» attribute of the tag
Try uploading very small files to narrow down whether it’s a file-size issue.
Check your available disk space. Although very rare, it is mentioned in this PHP Manual page comment:
As far as the HTML you appear to have set that part up correctly. You already have the enctype=»multipart/form-data» which is very important to have on the form.
As far as your php.ini setup, sometimes on systems multiple php.ini files exist. Be sure you are editing the correct one. I know you said you have configured your php.ini file to have file uploads, but did you also set your upload_max_filesize and post_max_size to be larger than the file you are trying to upload? So you should have:
Does your directory: «c:\wamp\tmp» have both read and write permissions? Did you remember to restart Apache after you made the php.ini changes?
It is important to add enctype=»multipart/form-data» to your form, example
Thank you everybody for the vary comprehensive replies. Those are all very helpful. The answer turned out to be something very odd. It turns out that PHP 5.2.11 doesn’t like the following:
Example:
Here another cause I found: When using JQuery Mobile and the form attribute data-ajax is set to true, the FILES array will be empty. So set data-ajax to false.
Make sure your input element has a ‘name’ attribute.
No one mentioned this but it helped me out and not many places on the net mention it.
Make sure your php.ini sets the following key:
You’ll need to check with your webhost if they want you to use an absolute server file path. You should be able to see other directory examples in your php.ini file to determine this. As soon as I set it I got values in my _FILES object.
Finally make sure that your tmp folder and wherever you are moving files to have the correct permissions so that they can be read and written to.
I was struggling with the same problem and testing everything, not getting error reporting and nothing seemed to be wrong. I had error_reporting(E_ALL) But suddenly I realized that I had not checked the apache log and voilà! There was a syntax error on the script. (a missing «>» )
So, even though this is something evident to be checked, it can be forgotten. In my case (linux) it is at:
If you are trying to upload an array of files then you may need to increase max_file_uploads in php.ini which is by default set to 20
Note: max_file_uploads can NOT be changed outside php.ini. See PHP «Bug» #50684
Another possible culprit is apache redirects. In my case I had apache’s httpd.conf set up to redirect certain pages on our site to http versions, and other pages to https versions of the page, if they weren’t already. The page on which I had a form with a file input was one of the pages configured to force ssl, but the page designated as the action of the form was configured to be http. So the page would submit the upload to the ssl version of the action page, but apache was redirecting it to the http version of the page and the post data, including the uploaded file was lost.
Do not trust the temp folder location provided by sys_get_temp_dir if you’re in a shared hosting environment.
Here is one more thing to check that has not yet been mentioned.
To verify that the uploaded file does in fact briefly appear in my /tmp folder, I added a sleep(30); statement to my script (as suggested here) and navigated to my /tmp folder in cPanel File Manager to locate the file. However, no matter what, the uploaded file was nowhere to be found there.
I spent hours trying to determine the reason for this, and implemented every suggestion that’s been offered here.
So, why does the sys_get_temp_dir function return inaccurate info?
Here’s an explanation from the PHP.net webpage for sys_get_temp_dir (i.e., the top comment):
If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return «/tmp», not the true, much longer, somewhat dynamic path.
This SO post delves into the issue, as well:
file — Читает содержимое файла и помещает его в массив
Описание
Читает содержимое файла и помещает его в массив.
Можно также использовать функцию file_get_contents() для получения файла в виде строки.
Список параметров
В качестве необязательного параметра flags может можно указать одну или более следующих констант: FILE_USE_INCLUDE_PATH Ищет файл в include_path. FILE_IGNORE_NEW_LINES Не добавлять новую строку к концу каждого элемента массива FILE_SKIP_EMPTY_LINES Пропускать пустые строки
Замечание: Поддержка контекста была добавлена в PHP 5.0.0. Для описания контекстов смотрите раздел Потоки.
Возвращаемые значения
Замечание: Если у вас возникают проблемы с распознаванием PHP концов строк при чтении или создании файлов на Macintosh-совместимом компьютере, включение опции auto_detect_line_endings может помочь решить проблему.
Список изменений
| Версия | Описание |
|---|---|
| 4.3.0 | file() стала безопасной для обработки бинарных данных |
Примеры
Пример #1 Пример использования file()
// Получает содержимое файла в виде массива. В данном примере мы используем
// обращение по протоколу HTTP для получения HTML-кода с удаленного сервера.
$lines = file ( ‘http://www.example.com/’ );
Примечания
При использовании SSL, Microsoft IIS нарушает протокол, закрывая соединение без отправки индикатора close_notify. PHP сообщит об этом как «SSL: Fatal Protocol Error» в тот момент, когда вы достигнете конца данных. Чтобы обойти это, вы должны установить error_reporting на уровень, исключающий E_WARNING. PHP версий 4.3.7 и старше умеет определять, что на стороне сервера находится проблемный IIS при открытии потока с помощью обертки https:// и не выводит предупреждение. Если вы используете fsockopen() для создания ssl:// сокета, вы сами отвечаете за определение и подавление этого предупреждения.






