Check if specific input file is empty - php

In my form I have 3 input fields for file upload:
<input type=file name="cover_image">
<input type=file name="image1">
<input type=file name="image2">
How can I check if cover_image is empty - no file is put for upload?

You can check by using the size field on the $_FILES array like so:
if ($_FILES['cover_image']['error'] == 4 || ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0))
{
// cover_image is empty (and not an error), or no file was uploaded
}
(I also check error here because it may be 0 if something went wrong (ie. a file was selected, but there's no data received). I wouldn't use name for this check since that can be overridden). error with a value of 4 is UPLOAD_ERR_NO_FILE, so we can check for that too.

Method 1
if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
Method 2
if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}

You can check if there is a value, and if the image is valid by doing the following:
if(empty($_FILES['cover_image']['tmp_name']) || !is_uploaded_file($_FILES['cover_image']['tmp_name']))
{
// Handle no image here...
}

if (empty($_FILES['cover_image']['name']))

simple :
if($_FILES['cover_image']['error'] > 0)
// cover_image is empty

check after the form is posted the following
$_FILES["cover_image"]["size"]==0

if (!$_FILES['image']['size'][0] == 0){ //}

if( ($_POST) && (!empty($_POST['cover_image'])) ) //verifies if post exists and cover_image is not empty
{
//execute whatever code you want
}

if(!empty($_FILES)) { // code if not uploaded } else { // code if uploaded }

$_FILES is an associative POST method array, if You want to check anything about $_FILES You must take into account the index... I tried a lot of suggested options, and the only method that worked for me, was when I included an index in my verification method.
$_FILES['Your_File']['name'][0];
So bye doing this:
if(empty($_FILES['Your_File']['name'][0])){
print('this thing is empty');
}else{
print('Something, something, something');
}
There's nothing like good old experimentation and lots of reading.

if($_FILES['img_name']['name']!=""){
echo "File Present";
}else{
echo "Empty file";
}

if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
// Code comes here
}
This thing works for me........

<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]" multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >
if($_FILES['imagefile']['name'] == '')
{
$img = $_POST['hidden_imagefile'];
}
else{
$img = '';
$uploadFolder = 'uploads/gallery/';
foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
$imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
$imageName = time() .$_FILES['imagefile']['name'][$key];
$img .= $imageName.',';
$result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
}
}

if ($_FILES['cover_image']['error'] == 4){
// the user did not choose any file
}else{
// the user chose a file to be uploaded
}

This will work
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
// checking if file is selected and not an error
{
// file is not selected and it is not an error
}

UPDATED:
Use this method:
First check if 'cover_image' key exists in $_FILES then check other file errors
if (in_array('cover_image', array_keys($_FILES) && $_FILES['cover_image']['error'] == 0) {
// TODO: write your code
} else {
// return error
}

Related

Why cant I check if something is not empty

I'm trying to validate if a image is uploaded or not.
But I can't figure this out since 2 hours...:
Input: ""
My Code:
$_SESSION["errorMessage"] = empty($image);
Output: 1 (true)
Then I want to check if it isnt empty:
$_SESSION["errorMessage"] = !empty($image); // Or empty($image) == false
But then The Output is nothing?!?!
Even If I try the first one out it, when it should be true, gives out: ""
Can anyone help me with this problem?
When you echo a false value, it won't echo anything. You have to tell php what to show, e.g. echo $_SESSION["errorMessage"] ? 'true' : 'false'; In your case you may want to cast it to an int: $_SESSION["errorMessage"] = (int)empty($image); You could also use var_dump to verify, i.e. var_dump( $_SESSION["errorMessage"] );
You can use the UPLOAD_ERR_NO_FILE value:
function isset_file($file) {
return (isset($file) && $file['error'] != UPLOAD_ERR_NO_FILE);
}
if(isset_file($_FILES['input_name'])) {
// It's not empty
}
Since sending $_FILES['input_name'] may throw a Notice
function isset_file($name) {
return (isset($_FILES[$name]) && $_FILES[$name]['error'] != UPLOAD_ERR_NO_FILE);
}
if(isset_file('input_name')) {
// It's not empty
}
Another example to try:
if ($_FILES['theFile']['tmp_name']!='') {
// do this, upload file
} // if no file selected to upload, file isn't uploaded.

Why my code not recognizing the file type?

I am new to php. I am writing a php script which will take only c, cpp and java files and upload them to a server.
Here is my code:
<?php
if(!empty($_POST["file_submit"]))
{
$allowed_xtensions = array("c","cpp","java");
$tmp_xtension_array = explode(".",$_FILES["file_name"]["name"]);
$xtension = end($tmp_xtension_array);
$type = $_FILES["file_name"]["type"];
if((($type == "text/x-java-source") || ($type == "text/x-csrc") || ($type == "text/x-c")) && in_array($xtension,$xtensions))
{
if($_FILES["file"]["error"] > 0)
{
exit( "Unable to process file.\nError : ".$_FILES["file_name"]["error"]);
}
else
{
if(!file_exists("/code/test.",$xtension))
{
if(move_uploaded_file($_FILES["file_name"]["tmp_name"],"/code/test.",$xtension) == false)
{
exit("Unable to process the file.\n");
}
}
}
}
else
{
exit("Invalid File.");
}
}
else
{
$file_form = ' <html>
<body>
<form action="test.php" method="post" enctype="multipart/form-data">
<label for="file"> Select File : </label>
<input type="file" name="file_name" id="file_id"/><br />
<input type="submit" name="file_submit" value="Submit">
</form>
</body>
</html>';
echo $file_form;
}
?>
But whenever I upload c,cpp or java files, I get INVALID FILE in response, although I have uploaded the correct file. Can anyone tell me why my code is showing this behaviour?
shouldn't that be
... && in_array($xtension,$allowed_xtensions) ...
instead of
.... && in_array($xtension,$xtensions) ...
Otherwise, second parameter isn't an array and you might get an error on that and it's always false?
It appears that your variable $type is not being set.
As a test, you might want to stick in this statement near the beginning of your script:
print_r($_FILES);
I suspect that there is no key ['file']['type'] in what's being passed to your script (or at least the values aren't what you're expecting). You can also test for existence using isset($_FILES['file']['type']).
It is also possible that $_FILES is empty. If it is, then try adding enctype="multipart/form-data" to the form tag and make sure file uploads are enabled.

ignoring blank file upload field

I've a form with upload field, it works fine. it uploads and everything is good, except that when the upload field is empty. the field in the database table goes blank as well, nothing in it, not even the old image entry!
My Form:
<form enctype="multipart/form-data" action="add.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="site_logo"><br>
<input type="submit" value="Add">
</form>
The PHP code:
<?php
$target = "../upload/";
$target = $target . basename($_FILES['site_logo']['name']);?>
<?php
move_uploaded_file($_FILES['site_logo']['tmp_name'], $target);
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
the query:
$site_logo=($_FILES['site_logo']['name']);
$query = "UPDATE ss_settings SET
site_logo = '{$site_logo}'
WHERE id = 1 ";
$result = mysql_query($query, $connection);
I've set the database connection and the update query and everything. just posted the process code so it be clear to you guys. I just want it to do nothing when the field is empty.
Check out the error messages explained http://www.php.net/manual/en/features.file-upload.errors.php
To check if a file wasn't uploaded:
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_NO_FILE)
A better way, is to check if there were no errors.
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)
If your query is an UPDATE statement you should not change it, also you can try with
<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
// do stuff when no file field is set
}else{
// do stuff when file is set
}
// ...
?>
Personally I would not use an un-sanitized name for a file, but all you need to do in your case, is check for a valid file-upload before you do your query.
So something like (in PDO as the mysql_* functions are deprecated):
// first line borrowed from #DaveChen, +1 for that
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)
{
$stmt = $db->prepare("UPDATE `ss_settings` SET
`site_logo` = :site_logo
WHERE `id` = :id ";
// bind variables
$stmt->bindValue(':site_logo', $_FILES['site_logo']['name'], PDO::PARAM_STR);
$stmt->bindValue(':id', $the_ID, PDO::PARAM_INT);
// execute query
$stmt->execute();
}
Perhaps try something like this to prevent processing of blank uploads:
if($_FILES['site_logo']['error']==0) {
// process
} else {
// handle the error
}
http://php.net/manual/en/features.file-upload.errors.php
Your problem is that you're simply assuming that a successful upload has taken place. NEVER assume success. ALways check for failure. PHP provides the ['error'] parameter in $_FILES for a reason. use it:
if ($_FILES['site_logo']['error'] == UPLOAD_ERR_OK) {
... upload was successful
} else {
die("Upload failed with error code: " . $_FILES['site_logo']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
You'll wan to check for code 4 (UPLOAD_ERR_NO_FILE), which means the user didn't upload anything at all.

How to check if file field is empty in codeigniter?

I have a form with a file field called image, but this field is not required.
When user don't choose any file in form, the do_upload() always return a error.
How can I check if user chosen a file before perform the upload action in my controller?
Please use empty()
if (empty($_FILES['userfile']['name'])) {
}
Try to check if the file is valid using is_uploaded_file(). For example:
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
do_upload();
}
In your controller, on the function that receives the submitted form:
if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
// do_upload
}
Here is full script to check if file field is empty or not in php
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations.
refer http://www.techzigzag.com/how-to-check-that-user-has-upload-any-file-or-not-in-php/
Hope it will help you.
Just use native php code to check file upload.
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
use empty() empty function does check if the file field is empty or not
if ( ! empty($_FILES)) {...}
if(!empty($_FILES['myFileField'])) {
// file field is not empty..
} else {
// no file uploaded..
}
As file upload error "No file selected" is number 4, correct way of doing this is:
if ($_FILES['my_image_field_name']['error'] !== 4){
if ($this->upload->do_upload('my_image_field_name')) { ...
When checking by name or tmp_name, there might be other reasons why these fields didn't get populated, and you may miss these.
if(!empty($_FILES[$file_name]['name'])){
// TODO your logic
}else{
echo "empty";
}
$file['file']->isValid()
CI4 user guide link

Problem with uploading multiple files PHP

On my site I have a page where users can upload files to go with the news post they're adding. I allow them to upload one image and one sound file. They don't have to add files if they don't want to, or they can just add one if they want. Problem I'm having is that my script only works if the user selects both files. If they choose none, or only one, then the script spits out 'Invalid File' as it can't find a file where one hasn't been selected.
I tried using:
if (isset($_FILES['filetoupload1'])) {
if (($_FILES["filetoupload1"]["type"] == "image/gif")
|| ($_FILES["filetoupload1"]["type"] == "image/jpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/pjpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/png")
|| ($_FILES["filetoupload1"]["type"] == "image/jpg")
) {
if ($_FILES["filetoupload1"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload1"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload1"]["name"])) {
echo $_FILES["filetoupload1"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload1"]["tmp_name"],
"media/" . $_FILES["filetoupload1"]["name"]
);
}
} else {
echo "Invalid file";
}
}
if (isset($_FILES['filetoupload2'])) {
if ($_FILES["filetoupload2"]["type"] == "audio/mp3") {
if ($_FILES["filetoupload2"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload2"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload2"]["name"])) {
echo $_FILES["filetoupload2"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload2"]["tmp_name"],
"media/" . $_FILES["filetoupload2"]["name"]
);
}
} else {
echo "Invalid file";
}
}
and then
if((isset($_FILES['filetoupload1'])) && (isset($_FILES['filetoupload2']))) { }
before both first and second upload scripts if the user had selected both image and audio file. In other words it did this:
if filetoupload1 isset then run upload script that filters images.
if filetoupload2 isset then run upload script that filters audio.
if filetoupload1 AND filetoupload2 isset then run both upload scripts.
I have it set like that. The above should allow for all combinations of file uploads. right? but it doesnt work so..
Now I have no idea what to do. Here's the upload script for the audio, the image one is pretty much the same:
Can someone tell me what I'm doing wrong please!
"I get the error: Invalid file"
This is correct, since your code just does this.
Do not check if the file is set but if i.e. $_FILES["filetoupload1"]["type"] is not empty.
Your script makes your server vulnerable to a malicious user being able stomp on any file the webserver has access to:
$_FILES[...]['name'] - user supplied
$_FILES[...]['type'] - user supplied
You're trusting that the client has supplied the proper MIME type for the file, but nothing stops someone from forging a request and uploading "virus.exe" and setting the mime type to 'image/jpeg'. As well, since the remote filename is under user control, it can be subverted with malicious data. Consider:
$_FILES['picture']['type'] = 'image/gif'
$_FILES['picture']['name'] = 'remote_server_control.php'
Completely legitimate according to your script, because the mime type is "right", and yet you've now put a user-supplied PHP script on your server and with that they can take total control of your site and/or server.
Never EVER trust the data in the $_FILES array. Always determine MIME types via server-side utilities. If the script is only supposed to handle images, then use getimagesize(). As well, never use user-supplied filenames. Use something determined server-side to give the file a name, like a databasde auto_increment ID number. Even though your code doesn't allow for overwriting existing files, it's trivial to just come up with a new name and boom... new version of the remote takeover script.
I suggest to you to add a hidden text, this hidden will check witch upload fields are active, you make this check with javascript:
<html lang="en">
<head>
<meta charset="utf-8">
<style>
</style>
<script type="text/javascript">
function uploadForm()
{
var size = 0;
var x = document.forms["myForm"]["upload1"].value.length;
var y = document.forms["myForm"]["upload2"].value.length;
if (x > 0)
{
size = 3;
}
if (y > 0)
{
size += 2;
}
return size;
}
</script>
</head>
<body>
<form name="myForm" action="" method="GET" onsubmit="chose.value = uploadForm()">
<input type="file" name="upload1"><br>
<input type="file" name="upload2"><br>
<input type="hidden" name="chose" value=""><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Now, when you receive the form, you have to check the value of chose filed, if its 2, that is mean the image field is not empty, 3 audio filed is not empty, 5 both not empty:
<?php
switch($_GET["chose"])
{
case 2:
//
break;
case 3;
//
break;
case 5:
//
break;
default:
// here the user doesn't use any field
}
?>

Categories