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.
Related
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
I have a form where a user fills out multiple input fields and they can also upload an image. I recently added another input field where the user can upload an additional image.
<label for="photo">Facility Roof Plan:</label>
<input type="file" id="facilityroofplan" name="facilityroofplan" />
When the user submits my form it should upload this image, as well as store a directory path into a db. The information is being saved into my db properly without any issues, however when I check to see if the image was uploaded it is not there.
$directoryPath = "../images/" . $selectedAssocAccount . "/" . $facilityID;
//create the directory
mkdir($directoryPath, 0775);
//facility roof plan
if(!empty($_FILES["facilityroofplan"]["name"])){
//directory path for the facility photo to reside in
$facilityRoofPlan = "../images/". $selectedAssocAccount ."/" . $facilityID . "/" . basename($_FILES["facilityroofplan"]["name"]);
if($_FILES['facilityroofplan']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityroofplan"]["tmp_name"];
$saved = save_facility_roof_plan($from, $facilityPhoto, $status_msg);
} else{
echo "Error uploading facility image.";
}
//insert into photo table
$photoQuery = "INSERT INTO facility_roof_plan (facility_id, roof_plan) VALUES ('$facilityID', '$facilityRoofPlan')";
mysqli_query($dbc, $photoQuery)or die(mysqli_error($dbc));
}
And this is what my save_facility_roof_plan function looks like:
function save_facility_roof_plan($from, $to, $status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading a photo.";
return false;
}
I have done this in several other places and I have no issues uploading any images.
where am I going wrong here?
In your code, you have the line
$saved = save_facility_roof_plan($from, $facilityPhoto, $status_msg);
But there is no variable $facilityPhoto anywhere in what you posted. My guess is that should be changed to $facilityRoofPlan since you set that path but never use it.
Then the $saved variable is never checked for errors which might have shown you why it isn't working.
Try:
$facilityRoofPlan = "../images/". $selectedAssocAccount ."/" . $facilityID . "/" . basename($_FILES["facilityroofplan"]["name"]);
if($_FILES['facilityroofplan']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityroofplan"]["tmp_name"];
$saved = save_facility_roof_plan($from, $facilityRoofPlan, $status_msg);
if (!$saved) {
echo "Error saving roof plan image: {$status_msg}";
}
} else{
echo "Error uploading facility image.";
}
I am using the library WideImage to resize an uploaded image into two separate sizes then save the images in two separate directories. The problem is that the smaller image is not ALWAYS saving. Here is my attempt:
if(move_uploaded_file($_FILES['image']['tmp_name'], "../images/temp/$id.jpg")){
include '../../WideImage/WideImage.php';
$successfull = 0;
if($image = WideImage::load("../images/temp/$id.jpg")){
if($large=$image->resize(500, 375)){
$large->saveToFile("../images/large/product_$id.jpg");
$successfull = 1;
}
}
if($successfull==1){
$successfull = 0;
if($image_2 = WideImage::load("../images/temp/$id.jpg")){
if($small=$image_2->resize(300, 225)){
$small->saveToFile("../images/small/product_$id.jpg");
$successfull = 1;
}
}
if($successfull!=1){
$showError='style="background:#c60000;"';
$myError="An Error Occured Please Try Again";
}
else {
unlink("../images/temp/$id.jpg");
header("location: products.php");
exit;
}
}
This is always giving me an error. My assumption is that the saving of the image is taking some time. So my question is how can I ensure that all the steps have been successfully completed?
I have a image gallery , users can upload the images, after uploading the image, PHP script create two copy of it - One for thumbnail and another for displaying in gallery in larger size.
The application is working fine, except that , When uploading some PNG pictures , the statement
if($image=#imagecreatefromstring($filedata))
returns false.
Below is the script. Please help.
<!---------------Processing uploaded image----------------->
<?php
if (isset($_FILES['file1']))
{
if($fgmembersite->CheckLogin())
{
if($_FILES['file1']['error']>0)
{
echo "file upload error".$_FILES['file1']['error'];
}
else
{
$allowedtype=array('image/jpg','image/jpeg','image/pjpeg','image/gif','image/png');
$maxsize=10*1024*1024;
$filename= mysql_real_escape_string($_FILES['file1']['name']);
$tmp_name=$_FILES['file1']['tmp_name'];
$size=$_FILES['file1']['size'];
$type=$_FILES['file1']['type'];
$ext=$filename;
if (!in_array($type,$allowedtype))
{
die ('Invalid file type');
}
if ($size>$maxsize)
{
die ('error- file size must be less than'.($maxsize/1024/1024).'MB');
}
filedata=file_get_contents($tmp_name);
if($image=#imagecreatefromstring($filedata))
{
$width=imagesx($image);
$height=imagesy($image);
//creating images
$large=imagecreatetruecolor(445,380);
imagecopyresampled($large,$image,0,0,0,0,445,380,$width,$height);
$largepath = 'image/large/' . uniqid('img',true) . '.jpg' ; //assigning file location and path
$thumb=imagecreatetruecolor(54,54);
imagecopyresampled($thumb,$image,0,0,0,0,54,54,$width,$height);
$thumbpath = 'image/thumb/' . uniqid('thumb',true) . '.jpg' ;
if (imagejpeg($thumb,$thumbpath) && imagejpeg($large,$largepath))
{
$con = connect();
query("INSERT INTO gallery (caption,thumbpath,largepath) values ('$caption','$thumbpath','$largepath')");
}
header('location:'.$_SERVER["PHP_SELF"]);
}
else
echo "failed";
}
}
}
?>
Check the manual on imagejpeg, it takes an optional third parameter that is the quality (0 - 100):
if (imagejpeg($thumb,$thumbpath, 92) && imagejpeg($large,$largepath, 96))