How to test if a user has SELECTED a file to upload? - php

on a page, i have :
if (!empty($_FILES['logo']['name'])) {
$dossier = 'upload/';
$fichier = basename($_FILES['logo']['name']);
$taille_maxi = 100000;
$taille = filesize($_FILES['logo']['tmp_name']);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['logo']['name'], '.');
if(!in_array($extension, $extensions)) {
$erreur = 'ERROR you must upload the right type';
}
if($taille>$taille_maxi) {
$erreur = 'too heavy';
}
if(!empty($erreur)) {
// ...
}
}
The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'
So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.
i tested :
if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])
but both doesn't seems to work.
Any ideas?
edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.
thanks.

You can check this with:
if (empty($_FILES['logo']['name'])) {
// No file was selected for upload, your (re)action goes here
}
Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.

There is a section in php documentation about file handling. You will find that you can check various errors and one of them is
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
In your case you need code like
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
or
if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... }
You should consider checking (and probably providing appropriate response for a user) for other various errors as well.

You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.

I would test if (file_exists($_FILES['logo']['tmp_name'])) and see if it works.
Or, more approperately (thanks Baloo): if (is_uploaded_file($_FILES['logo']['tmp_name']))

We Could Use
For Single file:
if ($_FILES['logo']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
For Multiple files:
if ($_FILES['logo']['tmp_name'][0] == "") {
// No files were selected for upload, your (re)action goes here
}

if($_FILES["uploadfile"]["name"]=="") {}
this can be used
No file was selected for upload, your (re)action goes here in if body
echo "no file selected";

if ($_FILES['logo']['error'] === 0)
is the only right way

Related

Uploading files using php very slow in xampp

I am new for developing.I have opted for php to learn coding.So I might make mistake as I learn by myself, kindly clarify my doubts.
I have problem in uploading files using php to a folder.What I really do is, I upload a file and the file is saved in a folder and the name of the file alone inserted in the database. While uploading the file I do copy the file to another folder which will be used for the editing purpose so that the original file will not be disturbed.Here the problem I get is, the file is uploaded successfully as well as the name too inserted in database. But it take much time to get upload even the size of the file is small.It works good while I test using my local but when I come in real time this issue(slow uploading) I face. What the person incharge in uploading do is, uploading a file and opening a new browser and upload another file. When the new browser is opened the files get uploaded but in the previous browser it is still in process. The code I have written to copy the file to another folder is not executed as the new browser is opened to upload another set of files. I am using xamp cp v3.2.1.To minimize the execution time I have set the default Maximum execution time to 30. But unable to upload file fastly.
Below is my php coding:
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
?>
It takes much time because, each and everytime all the files are copied to the newfolder. This exceeds the execution time.Only copying the uploaded files makes uploading and copying files fast.

PHP uploading issues

I'm having strange issues when uploading to the server via PHP.
I get the type of the file (working properly, it shows them via echo)
$file = $_FILES['file'];
$typeFile = end(explode(".", $file['name']));
Then I make some comparasions to let them upload it or not, here are the fille types allowed
if($file['size'] <= 52428800) { //50MB, and my file is about 2,5MB
if($fileType == "nlpack" || $fileType == "nl2pkg" || $fileType == "nlpark") {
$id = add_to_db($file['name']); //Adding to database the name, this will return an id, it works
if($id) {
mkdir("uploads/".$id); //create a folder where to add the file, working fine!
if(move_uploaded_file($file['tmp_name']), ".uploads/".$id."/".$file['name']) {
echo "file uploaded correctly";
}
else {
echo "has been an error"; //it enters here, while the other file types enters in the if()
}
}
else {
echo "Has been an error";
}
} else {
//alert an error
}
}
The thing is, that "nlpack" file type doesn't uploads, and it enters the if() because I checked it with echos, while the other two are uploaded without problem.
I also check the file size, but that's running fine.
Any ideas of what is going on?
Thanks in advance
Make sure the filesize isn't exceeding the settings in your php.ini or the file will just fail to upload.
upload_max_filesize integer
The maximum size of an uploaded file.
When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
AND if muliple:
max_file_uploads integer
The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

How can I check that at-least one file is selected for upload

how can I check that user has selected at-least one file for upload in below code ?
i have tried with in_array, isset, !empty functions but no success
please note that userfile input is array in html
if(!empty($_FILES['userfile']['tmp_name'])){
$upload_dir = strtolower(trim($_POST['name']));
// Create directory if it does not exist
if(!is_dir("../photoes/". $upload_dir ."/")) {
mkdir("../photoes/". $upload_dir ."/");
}
$dirname = "../photoes/".$upload_dir;
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file selected for no. '.$i.'field';
}
/*** check if the file is less then the max php.ini size ***/
if($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
// check the file is less than the maximum file size
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['userfile']['tmp_name'][$i],$dirname.'/'.$_FILES['userfile']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
}
}
}
}else{
$messages[] = 'No file selected for upload, Please select atleast one file for upload';
dispform();
}
Here's how I do it its a couple of if's and I use a for loop as I allow multiple file uploads from a single drop down but its the if's that are more important to you
$uploaded = count($_FILES['userfile']['name']);
for ($i=0;$i<$uploaded;$i++) {
if (strlen($_FILES['userfile']['name'][$i])>1) {
// file exists so do something
} else {
//file doesn't exist so do nothing
}
}
You'll note I compare against the name element of the global $_FILES this is because you should never be able to upload a file without a name which also applies for no file uploaded
Don't do it client side thats a dumb place to do validation as the user can simply turn js processing off in the browser or it can be blocked by certain addons etc or intercepted and altered via firebug and various browser search hijacking toolbars etc.
Anything like this should always be done server side!
finally I found the answer, I am giving it here for other users,
I have 5 keys in html input array so array index is up to 4
if(!empty($_FILES['userfile']['tmp_name'][0]) or !empty($_FILES['userfile']['tmp_name'][1]) or !empty($_FILES['userfile']['tmp_name'][2]) or !empty($_FILES['userfile']['tmp_name'][3]) or !empty($_FILES['userfile']['tmp_name'][4])){
//at-least one file is selected so proceed to upload
}else{
//no file selected, notify user
}
There are several methods of doing this with PHP (e.g. Check if specific input file is empty), but with JS it's faster and less expensive on the server. Using jQuery you can do this:
$.fn.checkFileInput = function() {
return ($(this).val()) ? true : false;
}
if ($('input[type="file"]').checkFileInput()) {
alert('yay');
}
else {
alert('gtfo!');
}

php script for upload image not working

i have a edit page that allow users to upload a profile image using forms
but the problem is that i keep getting the the format is not acceptable even if the image type is one of the accepted format.
this is the code
if(isset($_POST['parse_var']) == "pic")
{
if(!$_FILES['fileField']['tmp_name'])
{
$errorMSG = '<font color= "#FF0000">Please browse for an Image Before you press the button.</font>';
}
else
{
$maxfilesize = 51200;//in bytes = 50kb
if($_FILES['fileField']['size']>$maxfilesize)
{
$errorMSG = '<font color="#FF0000">Your image was too large, please try again.</font>';
unlink($_FILES['fileField']['tmp_name']);
}
elseif(!preg_match("^.(gif|jpg|png)$/i^",$_FILES['fileField']['name']))
{
$errorMSG = '<font color="#FF0000">Your Image was not one of the accepted format, please try again</font>';
unlink($_FILES['fileField']['tmp_name']);
}
else
{
$newname = "image01.jpg";
$place_file = move_uploaded_file($_FILES['fileField']['tmp_name'],"members/$id/".$newname);
$message='<font color="#00FF00>Your Image has been upload successfully</font>';
}
}//end else
}//end if
Major problems:
a)
elseif(!preg_match("^.(gif|jpg|png)$/i^",$_FILES['fileField']['name']))
^---
you should not be using a regex metachar as the pattern delimiter. Try
preg_match('/\.(gif|jpg|png)$/i', ...) instead.
But in a bigger picture view, you shouldn't be matching on filenames at all. Filenames can be forged. You should be doing server-side MIME-type determination (e.g. via file_info()) instead.
b)
you are NOT properly checking for upload success. The presence of a ['tmp_name'] in the $_FILES array means NOTHING. failed uploads can STILL produce a tmp_name, yet you end up with garbage. Always use something like this:
if ($_FILES['fileField']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileField']['error']);
}
the error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
c) (minor)
you do no need to unlink the temp files. PHP does that automatically when the script exits.
d) (stylistically HUGE error)
font tags? in 2013? The 1990s called and want their HTML 1.0 back...

A way to test for a file upload

I'm writing a script to handle a file upload. I've got the script in place, validating and uploading correctly.
But....the upload is optional. When I submit the form, the $_FILES['field_name'] is always present which consequently forces my validation to kick in.
How can I detect if there is a file upload or not?
Take a look at is_uploaded_file.
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
}
You could use :
if (!empty($_FILES['file']['name'])) {
}
Which amounts to (almost) the same as the other answers on here.
I use:
if(isset($_FILES['file']) && $_FILES['file']['name'] != '') {
Where 'file' is the name of your file field.
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
// Code goes here
}

Categories