I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so I want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check whether he uploaded something or not? Will $_FILES['myflie']['size'] <=0
work?
Answers
For a simple fix that would require no server side changes, I would use the HTML5 File API to check the size of the file before uploading. If it exceeds the known limit, then cancel the upload. I believe something like this would work:
function on_submit()
{
if (document.getElementById("upload").files[0].size > 666)
{
alert("File is too big.");
return false;
}
return true;
}
<form onsubmit="return on_submit()">
<input id="upload" type="file" />
</form>
Obviously it's just a skeleton of an example, and not every browser supports this. But it wouldn't hurt to use this, as it could be implemented in such a way that it gracefully degrades into nothing for older browsers.
Of course this doesn't solve the issue, but it will at least keep a number of your users happy with minimal effort required. (And they won't even have to wait for the upload to fail.)
--
As an aside, checking $_SERVER['CONTENT_LENGTH']
vs the size of the post and file data might help detect if something failed. I think it when there is an error it will be non zero, while the $_POST
and $_FILES
would both be empty.
Here's what worked best for me when trying to script this (in case anyone else comes across this like I did):
$ pecl -d php_suffix=5.6 install <package>
$ pecl uninstall -r <package>
$ pecl -d php_suffix=7.0 install <package>
$ pecl uninstall -r <package>
$ pecl -d php_suffix=7.1 install <package>
$ pecl uninstall -r <package>
The -d php_suffix=<version>
piece allows you to set config values at run time vs pre-setting them with pecl config-set
. The uninstall -r
bit does not actually uninstall it (from the docs):
vagrant@homestead:~$ pecl help uninstall
pecl uninstall [options] [channel/]<package> ...
Uninstalls one or more PEAR packages. More than one package may be
specified at once. Prefix with channel name to uninstall from a
channel not in your default channel (pecl.php.net)
Options:
...
-r, --register-only
do not remove files, only register the packages as not installed
...
The uninstall line is necessary otherwise installing it will remove any previously installed version, even if it was for a different PHP version (ex: Installing an extension for PHP 7.0 would remove the 5.6 version if the package was still registered as installed).
Never used any of those, but they look interesting..
Take a look at Gearman as well.. more overhead in systems like these but you get other cool stuff :) Guess it depends on your needs ..
You can use
is_uploaded_file()
:From the docs:
EDIT: I'm using this in my FileUpload class, in case it helps: