Reputation: 41
Trying to read if user had uploaded file or not.
HTML:
<input type="file" name="img" id="img">
PHP:
if(isset($_FILES['img'])) {
$upload = 1;
echo "upload 1";
}
else{
$upload = 0;
echo "upload 0";
}
I want to see if user had selected file to be uploaded or not. In my code program goes every time to $upload = 1; even there is no file included.
Upvotes: 0
Views: 54
Reputation: 146350
As per the docs:
if (isset($_FILES['img']) && $_FILES['img']['error'] === UPLOAD_ERR_OK) {
$upload = true;
echo "upload true";
} else {
$upload = false;
echo "upload false";
}
My example also uses actual booleans. In fact you can also do:
$upload = isset($_FILES['img']) && $_FILES['img']['error'] === UPLOAD_ERR_OK;
Upvotes: 0
Reputation: 2111
Don't check only isset($_FILES['img'])
, check what's the value of $_FILES['img']['error']
. If it's 0, there was no error, and the file should be there - but this should also be verified with is_uploaded_file($_FILES['img']['tmp_name'])
.
You can check list of potential upload errors
More details about file upload handling
Upvotes: 0
Reputation: 23948
You can use file_exists
and is_uploaded_file
functions of PHP to check if file is uploaded.
if (!file_exists($_FILES['img']['tmp_name']) || !is_uploaded_file($_FILES['img']['tmp_name'])) {
$upload = 1;
echo "upload 1";
} else {
$upload = 0;
echo "upload 0";
}
Upvotes: 1