I’m running a WordPress 2.9.2 Blog with a custom install of Debian in a Amazon Web Services EC2 machine.
Everything was working fine until monday. Then came tuesday, and suddendly, overnight, I can’t upload pictures using the default WP file uploader (either flash or html).
When I try to upload a picture, it displays the following error:
File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini
So I checked out my php.ini, and modified some settings as follows:
- upload_max_filesize: 64M
- post_max_size: 90M
- memory_limit: 128M
- max_excecution_time: 600
- max_input_time: 600
But it didn’t work. Then I tried chmod -ing the wp-content/uploads/ folder and its subfolders to 777. Didn’t work.
Did some research on Google, and added following lines to .htaccess:
<IfModule mod_security.c>
SetEnvIfNoCase Content-Type
"^multipart/form-data;" "MODSEC_NOPOSTBUFFERING=Do not buffer file uploads"
</IfModule>
<IfModule mod_gzip.c>
mod_gzip_on No
</IfModule>
Didn’t work. Finally, increased WPs memory limit in wp-settings.php file. Didn’t work.
So I’m all out of options by now. Anyone has any ideas on how to solve this? It’s really bugging me and my client off!
Thanks in advance!
PHP stores uploads in a temporary location before moving them to their ultimate destination. In your php.ini file, check the value of upload_tmp_dir
If it is not writeable by the WordPress process, you’ll get an indication of a zero-byte upload (and the «substantial» message.)
To help debug this, I’ve (temporarily) added a print_r($file) line to wp-admin/includes/file.php (look for the if ( $test_size && ! ( $test_file_size > 0 ) )
test). When uploading a file, this will indicate what PHP thinks it is getting, and a clue as to where it may be failing.
In our case, we had just applied a set of security patches to our Debian server. In php.ini, the «upload_tmp_dir» directive was commented-out, so PHP was using the system default temp. directory. After the server updates, this directory was no longer writeable by WordPress. Uncommenting upload_tmp_dir and changing it to /var/tmp fixed the problem:
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = /var/tmp
PHP returns an appropriate error code along with the
file array. The error code can be found in the
error
segment of the file array that is created
during the file upload by PHP. In other words, the error might be
found in $_FILES[‘userfile’][‘error’].
-
UPLOAD_ERR_OK
-
Value: 0; There is no error, the file uploaded with success.
-
UPLOAD_ERR_INI_SIZE
-
Value: 1; The uploaded file exceeds the
upload_max_filesize
directive in php.ini. -
UPLOAD_ERR_FORM_SIZE
-
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE
directive that was specified in the HTML form. -
UPLOAD_ERR_PARTIAL
-
Value: 3; The uploaded file was only partially uploaded.
-
UPLOAD_ERR_NO_FILE
-
Value: 4; No file was uploaded.
-
UPLOAD_ERR_NO_TMP_DIR
-
Value: 6; Missing a temporary folder.
-
UPLOAD_ERR_CANT_WRITE
-
Value: 7; Failed to write file to disk.
-
UPLOAD_ERR_EXTENSION
-
Value: 8; A PHP extension stopped the file upload. PHP does not
provide a way to ascertain which extension caused the file upload to
stop; examining the list of loaded extensions with phpinfo() may help.
Viktor ¶
8 years ago
Update to Adams old comment.
This is probably useful to someone.
<?php
$phpFileUploadErrors
= array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
Anonymous ¶
14 years ago
[EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.]
This is a handy exception to use when handling upload errors:
<?php
class UploadException extends Exception
{
public function __construct($code) {
$message = $this->codeToMessage($code);
parent::__construct($message, $code);
}
private function
codeToMessage($code)
{
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
return $message;
}
}
// Use
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
?>
adam at gotlinux dot us ¶
18 years ago
This is probably useful to someone.
<?php
array(
0=>"There is no error, the file uploaded with success",
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);
?>
stephen at poppymedia dot co dot uk ¶
17 years ago
if post is greater than post_max_size set in php.ini
$_FILES and $_POST will return empty
svenr at selfhtml dot org ¶
16 years ago
Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:
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.
In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.
The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.
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).
jalcort at att dot net ¶
3 years ago
When uploading a file, it is common to visit the php.ini and set up upload_tmp_dir = /temp but in the case of some web hostess as fatcow you need to direct not only /tmp but upload_tmp_dir = /hermes/walnaweb13a/b345/moo.youruser/tmp
If not the $_FILES show you an error #6 "Missing a temporary folder
roland at REMOVE_ME dot mxchange dot org ¶
5 years ago
I have expanded @adam at gotlinux dot us's example a bit with proper UPLOAD_FOO constants and gettext support. Also UPLOAD_ERR_EXTENSION is added (was missing in his version). Hope this helps someone.
<?php
class Some {
/**
* Upload error codes
* @var array
*/
private static $upload_errors = [];
public function
__construct() {
// Init upload errors
self::$upload_errors = [
UPLOAD_ERR_OK => _('There is no error, the file uploaded with success.'),
UPLOAD_ERR_INI_SIZE => _('The uploaded file exceeds the upload_max_filesize directive in php.ini.'),
UPLOAD_ERR_FORM_SIZE => _('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'),
UPLOAD_ERR_PARTIAL => _('The uploaded file was only partially uploaded.'),
UPLOAD_ERR_NO_FILE => _('No file was uploaded.'),
UPLOAD_ERR_NO_TMP_DIR => _('Missing a temporary folder.'),
UPLOAD_ERR_CANT_WRITE => _('Cannot write to target directory. Please fix CHMOD.'),
UPLOAD_ERR_EXTENSION => _('A PHP extension stopped the file upload.'),
];
}
}
?>
Jeff Miner mrjminer AT gmail DOT com ¶
12 years ago
One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space. Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context.
So, instead of this:
-----
<?php
if($_FILES['userfile']['error']) {
// handle the error
} else {
// process
}
?>
-----
You have to do this:
-----
<?php
if($_FILES['userfile']['error']==0) {
// process
} else {
// handle the error
}
?>
-----
Also, ctype_digit fails, but is_int works. If you're wondering... no, it doesn't make any sense.
To Schoschie:
You ask the question: Why make stuff complicated when you can make it easy? I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement. In a loop, that would be deadly... try this instead:
-----
<?php
$error_types = array(
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
'The uploaded file was only partially uploaded.',
'No file was uploaded.',
6=>'Missing a temporary folder.',
'Failed to write file to disk.',
'A PHP extension stopped the file upload.'
);
// Outside a loop...
if($_FILES['userfile']['error']==0) {
// process
} else {
$error_message = $error_types[$_FILES['userfile']['error']];
// do whatever with the error message
}
// In a loop...
for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) {
if($_FILES['userfile']['error'][$x]==0) {
// process
} else {
$error_message = $error_types[$_FILES['userfile']['error'][$x]];
// Do whatever with the error message
}
}
// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory
unset($error_types);
?>
jille at quis dot cx ¶
14 years ago
UPLOAD_ERR_PARTIAL is given when the mime boundary is not found after the file data. A possibly cause for this is that the upload was cancelled by the user (pressed ESC, etc).
sysadmin at cs dot fit dot edu ¶
18 years ago
I noticed that on PHP-4.3.2 that $_FILES can also not be set if the file uploaded exceeds the limits set by upload-max-filesize in the php.ini, rather than setting error $_FILES["file"]["error"]
tyler at fishmas dot org ¶
18 years ago
In regards to the dud filename being sent, a very simple way to check for this is to check the file size as well as the file name. For example, to check the file size simple use the size attribute in your file info array:
<?php
if($_FILES["file_id"]["size"] == 0)
{
// ...PROCESS ERROR
}
?>
Tom ¶
12 years ago
Note: something that might surprise you, PHP also provides a value in the $_FILES array, if the input element has no value at all, stating an error UPLOAD_ERR_NO_FILE.
So UPLOAD_ERR_NO_FILE is not an error, but a note that the input element just had no value. Thus you can't rely on the $_FILES array to see if a file was provided. Instead you have to walk the array and check every single damn entry - which can be quite difficult since the values may be nested if you use input elements named like "foo[bar][bla]".
Seems like PHP just introduced you to yet another common pitfall.
admin at compumatter dot com ¶
3 years ago
We use this function to handle file uploads.
Since $_FILES allows for more than a single file, this loops through each file and if there's an error, it is displayed in human readable language to the error log and then returned / exited. You can adjust that to echo's if preferred:
function file_upload_test($messageBefore="CM FILE UPLOAD MESSAGE"){
global $_FILES;
# a single file limit
$upload_max_size = ini_get('upload_max_filesize');
# the combination of a batch o multiple files
$post_max_size = ini_get('post_max_size');
# array of possible fails which are retuned below in if $key=error section
$phpFileUploadErrors = array(
0 => 'There is no error, the file uploaded with success',
1 => 'Exceeds php.ini upload_max_filesize of '.$upload_max_size.'MB',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
error_log("========================================");
error_log("$messageBefore");
error_log("========================================");
foreach ($_FILES['cmmediabrowsedfor'] as $key => $value) {
${$key}=$value;
error_log('$_FILES ['.$key.'] = ['.$value.']');
if(is_array($value)){
foreach ($value as $key2 => $value2) {
error_log(' > $_FILES ['.$key.']['.$key2.'] = '.$value2);
if($key=='error'){
error_log(' ******* CM Failed Upload: '.$phpFileUploadErrors[$value2]);
error_log(' Exit / Return in plugins/cm-alpha/php/images/img-create-tmp.php');
error_log(' ');
exit;
}
}
}
}
if(!file_exists($_FILES["cmmediabrowsedfor"]["tmp_name"][0]) || !is_uploaded_file($_FILES["cmmediabrowsedfor"]["tmp_name"][0])) {
error_log("NO FILE GOT UPLOADED ");
} else {
error_log("SUCCESS FILE GOT UPLOADED ");
}
}
rlerne at gmail dot com ¶
8 years ago
This updates "adam at gotlinux dot us" above and makes it version aware, and also adds newer constants to the array.
The reason we want to check the version is that the constants are not defined in earlier versions, and they appear later in the array. They would effectively overwrite the "0" index (no error) with an error message when the file actually uploaded fine.
It also drops the constant's value (0,1,2, etc) for the errors, in the likely event that they are changed later (the code should still work fine).
<?php
$upload_errors
= array(
0 => "There is no error, the file uploaded with success"
,UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
,UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
,UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded"
,UPLOAD_ERR_NO_FILE => "No file was uploaded"
);
if (
version_compare(PHP_VERSION, '5.0.3') >= 0)
$upload_errors[UPLOAD_ERR_NO_TMP_DIR] = "Missing a temporary folder";
if (
version_compare(PHP_VERSION, '5.1.0') >= 0)
$upload_errors[UPLOAD_ERR_CANT_WRITE] = "Failed to write to disk";
if (
version_compare(PHP_VERSION, '5.2.0') >= 0)
$upload_errors[UPLOAD_ERR_EXTENSION] = "File upload stopped by extension";
?>
belowtherim2000 at yahoo dot com ¶
15 years ago
I've been playing around with the file size limits and with respect to the post_max_size setting, there appears to be a hard limit of 2047M. Any number that you specify above that results in a failed upload without any informative error describing what went wrong. This happens regardless of how small the file you're uploading may be. On error, my page attempts to output the name of the original file. But what I discovered is that this original file name, which I maintained in a local variable, actually gets corrupted. Even my attempt to output the error code in $_FILES['uploadedfiles']['error'] returns an empty string/value.
Hopefully, this tidbit will save someone else some grief.
viseth10 at gmail dot com ¶
5 years ago
[Well just a little note. ]
That UploadException class example posted on top by anonymous is great. It works good. But there is a certain problem. You know there are two sides to generating errors.
First -> for the client side.
Second -> for the developers who will use your script
But i see only one side to generating Exceptions. ie For the developers.
Why ? Because when you generate an Exception, your script will come to an halt and do whatever you have defined in catch clause.
Now you dont want any client to see the Exception, do you ? I will not. The client will want to know what error occured in simple words they can understand instead of wanting their web app crashed if upload fails. So, dont generate exceptions. These errors should be collected and shown to client in an elegant way. That's a little advice.
Keep developing smarter.
krissv at ifi.uio.no ¶
18 years ago
When $_FILES etc is empty like Dub spencer says in the note at the top and the error is not set, that might be because the form enctype isnt sat correctly. then nothing more than maybe a http server error happens.
enctype="multipart/form-data" works fine
roger dot vermeir at nokia dot com ¶
4 years ago
Just found out that it is very important to define the
input type="hidden" name="MAX_FILE_SIZE" value=...
AFTER defining the input type="FILE" name=...
in your html/php.
If you swap them around, you will keep getting the filesize exceeded (error 2)!
Hope this helps.
Roger
Dub Spencer ¶
18 years ago
Upload doesnt work, and no error?
actually, both $_FILES and $_REQUEST in the posted to script are empty?
just see, if "post_max_size" is lower than the data you want to load.
in the apache error log, there will be an entry like "Invalid method in request". and in the access log, there will be two requests: one for the POST, and another that starts with all "----" and produces a 501.
web att lapas dott id dott lv ¶
16 years ago
1. And what about multiple file upload ? - If there is an UPLOAD_ERR_INI_SIZE error with multiple files - we can`t detect it normaly ? ...because that we have an array, but this error returns null and can`t use foreach. So, by having a multiple upload, we can`t normaly inform user about that.. we can just detect, that sizeof($_FILES["file"]["error"]) == 0 , but we can`t actualy return an error code. The max_file_size also is not an exit, becouse it refers on each file seperatly, but upload_max_filesize directive in php.ini refers to all files together. So, for example, if upload_max_filesize=8Mb , max_file_size = 7Mb and one of my files is 6.5Mb and other is 5Mb, it exeeds the upload_max_filesize - cant return an error, becouse we don`t know where to get that error.
Unfortunately we cannot get the file sizes on client side, even AJAX normaly can`t do that.
2. If in file field we paste something, like, D:whatever , then there also isn`t an error to return in spite of that no such file at all.
info at foto50 dot com ¶
15 years ago
For those reading this manual in german (and/or probably some other languages) and you miss error numbers listed here, have a look to the english version of this page ;)
Tom ¶
8 years ago
As it is common to use move_uploaded_file with file uploads, how to get it's error messages should be noted here (especially since it's not noted anywhere else in the manual).
Common code is to do something like:
if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {
echo "<P>FILE UPLOADED TO: $target_file</P>";
} else {
echo "<P>MOVE UPLOADED FILE FAILED!!</P>";
print_r(error_get_last());
}
И ни один из них не работает.
Просто используйте это сначала:
if (filesize('data.txt') == 0){ echo "The file is DEFINITELY empty"; }
если вы все еще сомневаетесь (в зависимости от того, какой пустой смысл для вас), попробуйте также:
if (trim(file_get_contents('data.txt')) == false) { echo "The file is empty too"; }
Обратите внимание на Niels Keurentjes, так как http://php.net/manual/en/function.empty.php сказал:
До PHP 5.5 пустая () поддерживает только переменные; все остальное приведет к ошибке синтаксического анализа. Другими словами, следующее не будет работать: empty (trim ($ name)). Вместо этого используйте trim ($ name) == false.
Прежде всего, равенство – это оператор ==
– вы делаете обратную проверку прямо сейчас. Но даже тогда пустота не является абсолютной, вы можете столкнуться с фальшивым текстовым файлом, который на самом деле имеет новую строку или спецификацию UTF-8 (знак байтового байта).
if(filesize($path) < 16 && empty(trim(file_get_contents($path))) ) die('This works by definition.');
Это должно быть так. Вы проверяете, равен ли размер файла 0. Вам нужен код, если размер файла отличается от 0, а затем он пуст.
if ( 0 == filesize( $file_path ) ) { // file is empty }
if (file_get_contents($file_path) != "") { echo 'file is not empty'; } else { echo 'file is empty'; }
The filesize() function returns the size of the specified file. This function returns the file size in bytes on success or FALSE on failure.
пример
<?php echo filesize("test.txt"); ?>
Я использую file_get_contents для небольших xml-файлов. Следующий код работает для меня, кредит Lex здесь, с объяснением: file_get_contents с пустым файлом, не работающим PHP
if(file_get_contents($file) !== false) { echo 'your file is empty'; } else { echo 'file is not empty'; }
Если файл пуст, файл будет возвращать 0
и мы можем использовать его как boolean
, что-то вроде:
$txtFile = "someFile.txt"; if( filesize( $txtFile ) ) { // EMPTY FILE }
Вот несколько вариантов, которые основываются на ответе Нильса Керентджеса на проверку содержимого по размеру. С этими предложениями, если размер файла удовлетворен, его содержимое «включено» на странице. http://php.net/manual/en/function.include.php
Оба проверяют, существует ли файл, а затем оценивают его на основе размера (в байтах). Если размер файла больше или равен 5 байтам, выводится сообщение об успешном завершении и содержимое файла включено. Если файл не найден или меньше 5 байт (фактически пуст), отображается сообщение об ошибке и файл не включается. При ошибке clearstatcache выполняется для предотвращения останова файла при обновлении страницы. (Я пробовал функции с / без clearstatcache, и это помогает.) http://php.net/manual/en/function.clearstatcache.php
Сам файл можно ввести:
As a string throughout: 'file.txt' As a variable: $file = 'file.txt'; As a constant (per examples): define ('FILE', 'file.txt');
Вариант №1: Функция
<?php define ('FILE', 'file.txt'); function includeFile() { if (file_exists(FILE)) { echo 'File exists!' . '<br>'; if (filesize(FILE) >= 5) { echo 'File has content!' . '<br>'; include FILE; } else { echo 'File is empty.'; clearstatcache(); } } else { echo 'File not found.'; clearstatcache();} } includeFile(); // call the function ?>
Вариант № 2: Если / Else Statement
<?php define ('NEW_FILE', 'newfile.txt'); if (file_exists(NEW_FILE) && (filesize(NEW_FILE)) >= 5){ echo 'File exists and has content!' . '<br>'; include NEW_FILE; } else { echo 'File not found or is empty.'; clearstatcache(); } ?>
Проверки можно удалить:
echo 'File exists!' . '<br>'; echo 'File has content!' . '<br>'; echo 'File is empty.'; echo 'File not found.'; echo 'File exists and has content!' . '<br>'; echo 'File not found or is empty.';
Я запускаю блог WordPress 2.9.2 с пользовательской установкой Debian на машине Amazon Web Services EC2.
Все отлично работало до понедельника. Затем наступил вторник, и suddendly, в одночасье, я не могу загружать фотографии, используя загрузчик файлов WP по умолчанию (либо flash, либо html).
Когда я пытаюсь загрузить изображение, он отображает следующую ошибку:
Файл пуст. Загрузите что-нибудь более существенное. Эта ошибка также может быть вызвана отключением загрузок в вашем php.ini или post_max_size, определяемым как меньше, чем upload_max_filesize в php.ini
Итак, я проверил свой php.ini и изменил некоторые настройки следующим образом:
- upload_max_filesize: 64M
- post_max_size: 90M
- memory_limit: 128M
- max_excecution_time: 600
- max_input_time: 600
Но это не сработало. Затем я попробовал chmod — папку wp-content/uploads/ и ее подпапки в 777. Не работает.
Сделал некоторые исследования в Google и добавил следующие строки в .htaccess:
<IfModule mod_security.c>
SetEnvIfNoCase Content-Type
"^multipart/form-data;" "MODSEC_NOPOSTBUFFERING=Do not buffer file uploads"
</IfModule>
<IfModule mod_gzip.c>
mod_gzip_on No
</IfModule>
Не работает. Наконец, увеличенный предел памяти WP в файле wp-settings.php. Не работает.
Итак, теперь у меня нет опций. У кого-нибудь есть идеи о том, как это решить? Это действительно раздражает меня и моего клиента!
Спасибо заранее!