I want to check multiple files name are empty or not in php before inserting the database.
Kindly check what I am doing:
Try 1:
$filename1 = $_FILES['photo1']['name'];
$filename2 = $_FILES['photo2']['name'];
$filename3 = $_FILES['photo3']['name'];
if (empty($filename1 == "" && $filename2 == "" && $filename3 == ""))
{
$errors[] = 'All Images are required.';
}else{
// Files are not empty
}
Try 2:
if (empty($_FILES)) {
$errors[] = 'All images are required.';
}else{
}
if (empty(['photo1']['name'];)) {
$errors[] = 'Kindly Upload Image 1.';
}
if (empty(['photo2']['name'];)) {
$errors[] = 'Kindly Upload Image 2.';
}
if (empty(['photo3']['name'];)) {
$errors[] = 'Kindly Upload Image 3.';
}
For me both are not working as I want,
1)if someone upload image 1 then no error will show.
2)if someone do not upload image 3 then error will show kindly upload image 3
3)If someone do not upload image 2 then error will show kindly upload image 2
4)If someone do not upload all images then error will show all images are required.
Any idea or suggestions would be welcome.
You are not using the empty function correctly. It doesn't support multiple parameters and you have to recall it for every var you need to check.
if (empty($filename1) && empty($filename2) && empty($filename3))
{
btw, I think what you need in this case is the isset function, determining if a variable is set and is not NULL. This time, it support multiple parameters.
if (!isset($filename1, $filename2, $filename3))
{
The time to check for empty or missing values is before you assign to a variable. Trying to assign, for example, $filename1 = $_FILES['photo1']['name'] will result in an undefined index notice, if photo 1 hasn't been uploaded. The following code sets each variable to the appropriate filename, or null if it hasn't been uploaded. Then you can check for each one in turn.
<?php
$filename1 = $_FILES['photo1']['name'] ?? null;
$filename2 = $_FILES['photo2']['name'] ?? null;
$filename3 = $_FILES['photo3']['name'] ?? null;
if ($filename1 && $filename2 && $filename3) {
// do stuff
} elseif (!$filename1 && !$filename2 && !$filename3) {
$errors[] = 'All images are required.';
} else {
if (!$filename1) {
$errors[] = 'Kindly Upload Image 1.';
}
if (!$filename2) {
$errors[] = 'Kindly Upload Image 2.';
}
if (!$filename3) {
$errors[] = 'Kindly Upload Image 3.';
}
}
Related
I am new to PHP web development and making a simple website for adding products and categories and I am facing an issue with the update CRUD operation for the categories
when I upload an image.
Updating the image when less than 2MB is ok and the old image will be deleted, for the other scenarios when image is more than 2MB or upload different image extension than the allowed ones it's not being validated only the image name gets added to the database, below is my code and appreciate the help
include("../config/dbconn.php");
if (isset($_POST['update'])) {
$cat_id = mysqli_real_escape_string($dbconn, $_POST['cat_id']);
$cat_name = mysqli_real_escape_string($dbconn, $_POST['cat_name']);
$pervious_cat_name = filter_var($_POST['pervious_cat_name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$cat_img = $_FILES['cat_img'];
// checking empty fields
if (empty($cat_name) || empty($cat_img)) {
if (empty($cat_name)) {
echo "<font color='red'>category name field is empty!</font><br/>";
}
if (empty($cat_img)) {
echo "<font color='red'>image field is empty!</font><br/>";
}
} else {
//updating the table
if ($cat_img['name']) {
$pervious_cat_path = '../../uploads/' . $pervious_cat_name;
if ($pervious_cat_path) {
unlink($pervious_cat_path);
}
$cat_img_name = $cat_img['name'];
$cat_temp_name = $cat_img['tmp_name'];
$cat_img_destination_path = '../../uploads/' . $cat_img_name;
$allow_files = ['png', 'jpg', 'jpeg','webp'];
$extension = explode('.', $cat_img_name);
$extension = end($extension);
if (in_array($extension, $allow_files)) {
if ($cat_img['size'] < 2000000) {
move_uploaded_file($cat_temp_name, $cat_img_destination_path);
} else {
$_SESSION['category_update'] = "couldn't update category, image size is too large";
}
} else {
$_SESSION['category_update'] = "couldn't update category, image should be png, jpg, jpeg";
}
}
$cat_img_to_insert = $cat_img_name ?? $pervious_cat_name;
$query = "UPDATE category SET cat_name='$cat_name', cat_img='$cat_img_to_insert' WHERE cat_id=$cat_id";
$result = mysqli_query($dbconn, $query);
if ($result) {
//redirecting to the display page. In our case, it is index.php
header("Location: admin_panel.php");
}
}
}
?>
below are a couple of images to see the results:
ok uploaded an image less than 2MB and in the allowed extensions.
image bigger than 2MB and in the allowed extensions.
not allowed image extensions:
appreciate the support.
I am quite new to PHP, but i'm having a problem with my thought process around some code i am writing.
I am trying to get the below to work so that a user can upload two images in a form, which uploads to the server, and updates the field in SQL, but i'm having a hard time working out how to make it so that the SQL field isn't updated unless an image is uploaded - I've managed to make it work with one image using;
$uploadArtwork = $_FILES['asset_name']['tmp_name'];
if($uploadArtwork == null) {
$sql = "";
}
else {
$sql = "";
}
I am struggling to work out, how i can do it for two images (and eventually more than two images?)
Tried a lot of googling, but without much luck yet!
$uploadArtwork1 = $_FILES['asset_name1']['tmp_name'];
$uploadArtwork2 = $_FILES['asset_name2']['tmp_name'];
// Image1 and/or image2 was uploaded successfully
if(($uploadArtwork1 != null) || ($uploadArtwork2 != null)) {
$sql = "";
// No images were selected, or there were problems uploading them
} else {
$sql = "";
}
Though it would be better to check $_FILES['asset_name']['error'] == UPLOAD_ERR_OK to determine if an image was uploaded successfully:
$uploadArtwork1 = $_FILES['asset_name1']['error'];
$uploadArtwork2 = $_FILES['asset_name2']['error'];
// Image1 and/or image2 was uploaded successfully
if(($uploadArtwork1 == UPLOAD_ERR_OK) || ($uploadArtwork2 == UPLOAD_ERR_OK)) {
// Do something with $_FILES['asset_name1']['tmp_name'] and $_FILES['asset_name2']['tmp_name']
$sql = "";
// No images were selected, or there were problems uploading them
} else {
$sql = "";
}
Update:
require_once("Inc/classCloud.php");
$sql = "UPDATE assets SET asset_title='$post_asset_title'";
if ($uploadArtwork != null) {
$getImageID= $res['data'];
$sql .= ", asset_name='$getImageID'";
}
if ($uploadMock != null) {
$getImageID2= $res2['data'];
$sql .= ", product_artwork='$getImageID2'";
}
$sql .= " WHERE asset_id='$post_asset_id'";
Here is a basic structure to work with.
Basically looping through all uploaded files and if they have been found then move them to a new location on the server and write the entry to database.
This code has not been tested.
<?php
// Loops through all possible file uploads.
foreach ($_FILES as $file) {
// Checks a file has been chosen.
if (isset($file['tmp_name']) && !empty($file['tmp_name'])) {
// Checks the uploaded (object) is a file.
if (is_file($file['tmp_name'])) {
// The filepath for the uploaded file.
$destination = 'LOCATION TO MOVE THE UPLOADED FILE TO';
/*
* Perform SQL Write here
*/
if (WRITE WAS SUCCESSFUL) {
// Move FIle
move_uploaded_file($file['tmp_name'], $destination);
}
}
}
}
In this code when I navigate to the update form I get all the details as per database but when I update the form without selecting the image file it shows blank in the table.
if (isset($_POST['update_sub_categories']))
{
$file = $_FILES['Subcategory_image']['tmp_name'];
this are the conditions for update images
if (file_exists($file))
{
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if (($_FILES['Subcategory_image']['size'] >= $maxsize) || ($_FILES["Subcategory_image"]["size"] == 0))
{
$errors[] = 'File too large. File must be less than 2 megabytes.';
// code...
}
if (!in_array($_FILES['Subcategory_image']['type'], $acceptable) && (!empty($_FILES["Subcategory_image"]["type"])))
{
$errors[] = 'Invalid files type. Only JPG, GIF and PNG types are accepted';
}
}
Conditions end at this point
if no errors are found, the file will be uploaded
if (count($errors) === 0)
{
move_uploaded_file($_FILES['Subcategory_image']['tmp_name'], 'images/categories/' . $_FILES['Subcategory_image']['name']);
$Subcategory_image = $_FILES['Subcategory_image']['name'];
// code...
$m->set_data('Category_id', $Category_id);
$m->set_data('Subcategory_description', $Subcategory_description);
$m->set_data('Subcategory_name', $Subcategory_name);
$m->set_data('Subcategory_image', $Subcategory_image);
$a = array(
'Category_id' => $m->get_data('Category_id') ,
'Subcategory_description' => $m->get_data('Subcategory_description') ,
'Subcategory_name' => $m->get_data('Subcategory_name') ,
'Subcategory_image' => $m->get_data('Subcategory_image') ,
);
$q = $d->update("sub_categories", $a, "Subcategory_id='$Subcategory_id'");
if ($q > 0)
{
header("location:Manage_subcategories.php");
}
else
{
echo "Error";
}
}
else
{
header("location:Manage_subcategories.php?msg=invalidfile");
}
}
So how can i solve this?
When i click on the submit button without selecting any image files it shows blank at the table and it does not show the image that is already available
You have to put this condition
$Subcategory_image ="";
if($Subcategory_id){
$sql = $d->select("sub_categories", "Subcategory_id="$Subcategory_id);
if($sql->num_rows>0){
$data=mysqli_fetch_array($sql);
$Subcategory_image = $data["Subcategory_image"];
}
}
$check = getimagesize($_FILES["Subcategory_image"]["tmp_name"]);
if($check!=false){
move_uploaded_file($_FILES['Subcategory_image']['tmp_name'], 'images/categories/' . $_FILES['Subcategory_image']['name']);
$Subcategory_image = $_FILES['Subcategory_image']['name'];
$m->set_data('Subcategory_image', $Subcategory_image);
}
$m->set_data('Category_id', $Category_id);
$m->set_data('Subcategory_description', $Subcategory_description);
$m->set_data('Subcategory_name', $Subcategory_name);
also assign existing image to $Subcategory_image before this condition so that if file control is empty it get old image else of making old image field empty in db table
Yeah this is because the image input is taking as null as uploading it to database .. add a additional condition as when there is no image input assign the previous image input to the variable
if(!empty($employeepic)) {
if ((($employeepic_type == 'image/jpg') ||($employeepic_type == 'image/jpeg') ||($employeepic_type == 'image/gif') ||
($employeepic_type == 'image/png')) && ($employeepic_size <= EMP_MAXSIZE) && ($employeepic_size > 0)){
// Move the file to the target upload folder
$target = (EMP_UPLOADPATH .$firstname.$employeepic);
if(move_uploaded_file($_FILES['employeepic']['tmp_name'],$target)){
$employee = $firstname. " " .$lastname;
}
}else{
$filetoobig =' <p class="error"> There was a problem uploading your picture. Maximum size is 30K and must be in jpg, jpeg or pjpeg format</p>';
#unlink($_FILES['employeepic']['tmp_name']);
}
}
Can anyone see why the validation of file size not working?
(EMP_MAXSIZE = 32768)
Edit: The limit size is set at 32768 but can still upload 2MB files
Edit: The code to assign Employee_pic Size:
$employeepic = mysqli_real_escape_string($dbc, trim($_FILES['employeepic']['name']));
$employeepic_type = $_FILES['employeepic']['type'];
$employeepic_size = $_FILES['employeepic']['size'];
I figured it out. I am probably not doing the "right way of coding" but it nevertheless fixed the problem. I created another variable called $employee_pic = $firstname.$employeepic; in the true section of my validation and added "employee_pic='' ;" under the false result of my validation in order not to save the picture to mysql. This was accomplished by changing the $employeepic variable for $employee_pic in my insert query.
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?
You can use is_uploaded_file():
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
From the docs:
Returns TRUE if the file named by
filename was uploaded via HTTP POST.
This is useful to help ensure that a
malicious user hasn't tried to trick
the script into working on files upon
which it should not be working--for
instance, /etc/passwd.
This sort of check is especially
important if there is any chance that
anything done with uploaded files
could reveal their contents to the
user, or even to other users on the
same system.
EDIT: I'm using this in my FileUpload class, in case it helps:
public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}
This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.
HTML part:
<input name="files[]" type="file" multiple="multiple" />
PHP part:
if(isset($_FILES['files']) ){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(!empty($_FILES['files']['tmp_name'][$key])){
// things you want to do
}
}
#karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.
/**
* Tests all upload fields to determine whether any files were submitted.
*
* #return boolean
*/
function files_uploaded() {
// bail if there were no upload forms
if(empty($_FILES))
return false;
// check for uploaded files
$files = $_FILES['files']['tmp_name'];
foreach( $files as $field_title => $temp_name ){
if( !empty($temp_name) && is_uploaded_file( $temp_name )){
// found one!
return true;
}
}
// return false if no files were found
return false;
}
You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILE if no file was uploaded. Full list: PHP: Error Messages Explained
function isUploadOkay($form_name, &$error_message) {
if (!isset($_FILES[$form_name])) {
$error_message = "No file upload with name '$form_name' in form.";
return false;
}
$error = $_FILES[$form_name]['error'];
// List at: http://php.net/manual/en/features.file-upload.errors.php
if ($error != UPLOAD_ERR_OK) {
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
$error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$error_message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$error_message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error_message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$error_message = 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$error_message = 'A PHP extension interrupted the upload.';
break;
default:
$error_message = 'Unknown error';
break;
}
return false;
}
$error_message = null;
return true;
}
<!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. Thank you.
is_uploaded_file() is great to use, specially for checking whether it is an uploaded file or a local file (for security purposes).
However, if you want to check whether the user uploaded a file,
use $_FILES['file']['error'] == UPLOAD_ERR_OK.
See the PHP manual on file upload error messages. If you just want to check for no file, use UPLOAD_ERR_NO_FILE.
I checked your code and think you should try this:
if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name']))
{
echo 'No upload';
}
else
echo 'upload';
In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully.
https://www.php.net/manual/en/reserved.variables.files.php#109648
if ( boolval( $_FILES['image']['error'] === 0 ) ) {
// ...
}