Hello for some reason I can't get my program to see if my file is empty or not if something is selected it should not go through but it is. Here is the code
if (empty($_FILES['file'] ) )
{
echo "testing";
$seterror =1;
returnBack();
}
The language construct empty()
and arrays in PHP do not mix well. In addition, if you have a <input type='file' name='file' />
in your form, you will get a $_FILES[]
array. You should be doing if( !array_key_exists('file', $_FILES) ) { // no file uploaded }
to start with.
In fact, you should be doing several checks:
file
element is populated in $_FILES
$_FILES['file']['error']
== 0)Only of all of those are true will you have a file to process. Otherwise you don't.
I've found following these steps religiously on a file upload handler to be thoroughly reliable.
What do you get if you output the files array? (i.e. print_r($_FILES);
)
Your code won't tell you if the contents of the file called file
is empty, it will tell you if the value of $_FILES['file']
is empty, which might not be what you want. You also might not want the logic of empty
- have you tried this to see if there is a difference?
if (array_key_exists('file', $_FILES)) {
...
}
If you are testing for empty files here is the code
$file = 'test.txt';
if(filesize($file) == NULL) {
echo "empty";
}
I think you can try this
if(empty($_FILES['file']['name']))
{
// not uploaded
}
else
{
// uploded
}
From the var_dump($_FILES) you provided in the comments, it looks like it isn't echoing "testing" (i.e. it's not working) because $_FILE['file'] isn't empty.
from what you provided me:
$_FILES['file'] = array(5) { ["name"]=> string(0) "" ["type"]=> string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(4) ["size"]=> int(0) }
I'm not completely sure how empty() handles arrays (the documentation just says it will return true for an empty array), but at the very least you'd need to either get rid of $_FILES['file']['error'] (which isn't empty since it's an int(4)), or use empty() to check something like $_FILES['file']['name']
so, using my suggestion, here's how the code would look:
if (empty($_FILES['file']['name'])) {
echo "testing";
$seterror = 1;
returnBack();
}
or (since there might be something wrong with my understanding of PHP arrays), try this:
if(empty($_FILES['file']['name'])) {
echo "testing";
$seterror = 1;
returnBack();
}
Okay so what I had to do was check to see if it error - so if it did it would not go through because it would mean its empty
code:
if (!empty($_FILES['file']['error'] ) )
{
echo "file";
$seterror =1;
returnBack();
}
Thank you so much for the help guys!