Get an blank image after updating the form detail - php

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

Related

update issue with image validation in php

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.

How to check mulitple files empty or not in php?

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.';
}
}

Not updating a field if no image is inserted

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);
}
}
}
}

Delete an image in PHP (WordPress)

I have this code which uploads an image from admin and it works well.
add_action('admin_init', 'register_and_build_fields');
function register_and_build_fields() {
register_setting('theme_options', 'theme_options', 'validate_setting', 'delete_file');
}
function validate_setting($theme_options) {
$keys = array_keys($_FILES); $i = 0; foreach ( $_FILES as $image ) {
// if a files was upload
if ($image['size']) {
// if it is an image
if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) { $override = array('test_form' => false);
$options = get_option('theme_options'); echo "<img src='{$options['logo']}' />";
// save the file, and store an array, containing its location in $file
$file = wp_handle_upload( $image, $override ); $theme_options[$keys[$i]] = $file['url']; } else {
// Not an image.
$options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$logo];
// Die and let the user know that they made a mistake.
wp_die('No image was uploaded or invalid format.<br>Supported formats: jpg, jpeg, png, gif.<br> Go <button onclick="history.back()">Back</button> and try again.'); } } // Else, the user didn't upload a file.
// Retain the image that's already on file.
else { $options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$keys[$i]]; } $i++; }
return $theme_options;
}
and now I want the function to delete the current image.
function delete_file($theme_options) {
if (array_key_exists('delete_file', $_FILES)) {
$image = $_FILES['delete_file'];
if (file_exists($image)) {
unlink($image);
echo 'File '.$image.' has been deleted';
} else {
echo 'Could not delete '.$image.', file does not exist';
}
}
}
I added the button in admin but is doing.. nothing.
I'm building a TemplateOptions in WordPress and now I'm trying to make the logo function to be uploaded and deleted from admin. Like I said, uploading the logo works and now I want to make the field "delete" to work.
I found out that you don't need to insert the record in the DB as you only have a single image and whose name and path are also constant . So you simply need to unlink the image from the directory and it will be deleted, nothing else.
say your logo.png is in your themes's img folder then you should unlink it like this. default is your theme name
$path = ABSPATH.'wp-content/themes/default/img/logo.png';
if(file_exists($path))
{
unlink( $path );
}
Note: Remember that you have to pass the absolute path to the unlink() and not the url having http , because it will give you an error , you can't use http with unlink.

GetImageSize() not returning FALSE when it should

Working on a little upload script here. I'm trying to check if the uploaded image really is an image and not just a renamed PHP file.
When the script is posted I can print the array with
foreach ($_FILES['images']['name'] as $key => $value){
print_r(getimagesize($_FILES['images']['tmp_name'][$key]));
That works just fine, so it won't return false. But even if I upload a file that is not an image, it won't give false. It just returns nothing at all, and the rest of my script just processes the thing like an image.
Could anyone tell me what I am doing wrong?
Upload
you can not use getimagesize on $_FILES['images']['tmp_name'][$key] directly .. you need to copy it into your system first before you can use it
Use $_FILES['images']['size'][$key] temporarily
Or
move_uploaded_file($_FILES['images']['tmp_name'][$key], $destination);
print_r(getimagesize($destination));
Fake Image
Please not that $_FILES['images']['type'][$key] can be faked
Using Fake image Headers
Example
file_put_contents("fake.png", base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAABGdBTUEAALGPC/xhBQAAAAZQTFRF////
AAAAVcLTfgAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsSAAALEgHS3X78AAAAB3RJTUUH0gQCEx05cq
KA8gAAAApJREFUeJxjYAAAAAIAAUivpHEAAAAASUVORK5CYII='));
Uploading fake.png
array
'name' =>
array
0 => string 'fake.png' (length=8)
'type' =>
array
0 => string 'image/png' (length=9)
'tmp_name' =>
array
0 => string 'C:\Apache\xampp\tmp\php44F.tmp' (length=30)
'error' =>
array
0 => int 0
'size' =>
array
0 => int 167
Validate Image
Usage
var_dump ( getimagesizeReal ( "fake.png" ) );
Function Used
function getimagesizeReal($image) {
$imageTypes = array (
IMAGETYPE_GIF,
IMAGETYPE_JPEG,
IMAGETYPE_PNG,
IMAGETYPE_SWF,
IMAGETYPE_PSD,
IMAGETYPE_BMP,
IMAGETYPE_TIFF_II,
IMAGETYPE_TIFF_MM,
IMAGETYPE_JPC,
IMAGETYPE_JP2,
IMAGETYPE_JPX,
IMAGETYPE_JB2,
IMAGETYPE_SWC,
IMAGETYPE_IFF,
IMAGETYPE_WBMP,
IMAGETYPE_XBM,
IMAGETYPE_ICO
);
$info = getimagesize ( $image );
$width = #$info [0];
$height = #$info [1];
$type = #$info [2];
$attr = #$info [3];
$bits = #$info ['bits'];
$channels = #$info ['channels'];
$mime = #$info ['mime'];
if (! in_array ( $type, $imageTypes )) {
return false; // Invalid Image Type ;
}
if ($width <= 1 && $height <= 1) {
return false; // Invalid Image Size ;
}
if($bits === 1)
{
return false; // One Bit Image .. You don't want that ;
}
return $info ;
}
I'd like to recommend against trusting the results of getimagesize() when deciding whether to place the uploaded file anywhere in your document root. That's because PHP code embedded in GIF files (titled like image.gif.php) will be identified as images by getimagesize(), but serving them will run the PHP code inside them in addition to displaying the image. Here is some more information on the issue.
The article linked above recommends setting up a separate controller through which all the user uploaded files are served. Files read with readfile() are not parsed when accessed through the local filesystem.
Firstly, you can use getimagesize on $_FILES['images']['tmp_name'], so that's not an issue.
If you want to check if the file is an image, then try this:
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['images']['tmp_name']);
if($check !== false) {
echo 'File is an image - ' . $check['mime'];
}
else {
echo 'File is not an image';
}
}
You can simply use $_FILES['images']['type'] . it'll give you the type of file uploaded. Then check it againt octate stream or other executable file. If so then do not allow it.
#user1362916 If you are uploading multiple images with HTML then perhaps you need to add one more array like this.
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['images']['tmp_name'][$i]);
if($check !== false) {
echo 'File is an image - ' . $check['mime'];
}
else {
echo 'File is not an image';
}
}
Here check [i] because this is for multiple file upload.
Below is full script
<!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
{
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['my_files']['tmp_name'][$i]);
if($check !== false) {
echo 'File is an image - ' . $check['mime'];
}
else {
echo 'File is not an image';
}
}
}
}
}
?>
</body>
</html>

Categories