Can any one help me how to delete the image inside the folder?
this my code for deleting the image inside the database and its working
<?php
require('connection/dbconn.php');
if(ISSET($_POST['id'])){
foreach ($_POST['id'] as $id){
$dbconn->query("delete from `uploading` where `id` = '$id'");
}
}
?>
For deleting file with PHP, you have to use unlink function.
But you have to also provide a filepath, which is in your case should consists from upload directory path and fileID (which is $_POST['id']?)
/**
* Do user permissions check for this operation before going further
*/
foreach ($_POST['id'] as $fileId) {
$filePath = "/path/to/upload/dir/$fileId";
if (file_exists($filePath)) {
unlink($filePath);
}
}
Don't forget to make security and data consistency checks. For example, that the user, that sent this request for deleting has enough rights for it.
To delete the image from server, you will have to pass theimageName variable to your PHP script, and then you can delete the file using built-in function unlink():
$path = //your path to the upload images
unlink( $path . $imageName);
unlink( $path . 'Thumbnails/' . $imageName); //if also have thumbnail
You are interacting with your server file system, you'll want to be sure and sanitize the variables (prevent someone from using ../../../ to get to unwanted parts of your file system).
$imageName= str_replace( array( '..', '/', '\\', ':' ), '', $imageName);
You should sanitize the variables to make sure you escape .. characters in the filename otherwise you could something like "../../../public/index.php
Update:
You would have to store the name of an image in the database and create a hidden field in your delete form. While deleting, get the image name as $image = $_POST['image']; and then follow the unlink process.
Select image name from db or send image name with id
Use unlink function to delete file image
unlink('/path-to-upload-dir/' . $_POST['imagename']);
I have created a PHP and MySQL script which successfully uploads submitted images via PHP to a folder on my server, and then adds the filename with extension to my MySQL database.
With an FTP program I can see the submitted image inside the correct folder on my server with its correct file size. However, when I type the file path of the newly uploaded image (http://xxxxxx.com/images/image.jpg) into my browser, I get a blank page. Also when I try to import the image onto a website, nothing shows up.
However, when I re-download the image via the FTP program onto my computer, I can see that the image is TOTALLY OK. What am I missing?
Excerpts of my code are below:
<?php
// getting current post id and slug
$pid = $_POST['pid'];
$slug = $_POST['slug'];
//This is the directory where images will be saved
$target = '../company/'.$slug.'/images/';
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$pic = ($_FILES['image']['name']);
$fileTmpLoc = ($_FILES["image"]["tmp_name"]);
$extract = explode(".", $pic);
$fileExt = end($extract);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$rename = rand(100000000000,999999999999).".".$fileExt;
// check for correct filetype
if (!preg_match("/\.(gif|jpg|png)$/i", $pic) ) {
header("location: ../message.php?msg=ERROR: incorrect filetype");
exit();
}
include_once "../database-connect.php";
//Writes the information to the database
mysqli_query($dbconnection,"UPDATE companies SET picture='$rename' WHERE ID='$pid'") ;
//Writes the photo to the server
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
{
.... etc
What am I missing that it does not show up in the browser?
Maybe the path is not what you think it is when you try to link to the image or when you try to open it.
Note that this looks very wrong:
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
This will add two quotes and two dots to your path, so if $slug is some_company, the path will be:
/company/'.some_company.'/images/123456789.jpg
Perhaps you don't see or didn't notice that in your ftp program.
Also note that you have an sql injection problem, you should switch to prepared statements with bound variables.
Problem was indeed the URL output structure. Have changed it, like jeroen suggested:
if(move_uploaded_file($fileTmpLoc, "../images/$rename"))
Works fine now
I have recently started working on zend framework. I want to upload a profile picture and rename & re-size it. Am using the code below. with this am able to upload but am not able to rename and am not getting a way to re-size the uploaded file.
if($this->getRequest()->isPost())
{
if(!$objProfilePictureForm->isValid($_POST))
{
//return $this->render('add');
}
if(!$objProfilePictureForm->profile_pic->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
}
if($objProfilePictureForm->profile_pic->isUploaded())
{
$values = $objProfilePictureForm->getValues();
$source = $objProfilePictureForm->profile_pic->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'new';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="../uploads/'.$new_image_name.'" />';
$objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
To Rename a file while uploading, you will have to add the "Rename-Filter" to your file-form-element. The class is called Zend_Filter_File_Rename.
// Create the form
$form = new Zend_Form();
// Create an configure the file-element
$file = new Zend_Form_Element_File('file');
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files.
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename
$form->addElement($file);
// Submit-Button
$form->addElement(new Zend_Form_Element_Submit('save');
// Process postdata
if($this->_request->isPost())
{
// Get the file and store it within the specified destination with the specified name.
$file->receive();
}
To make the filename dynamically you may name it with a timestamp or something. You may also apply the Rename-filter within your post-data-processing before the call of $file->receive(). This could be useful if you insert a row into a table and want to name the file with the id of the just inserted row.
Since you want to store a profile picture you could get the id of the user from your db and name the pic with that id.
I am building a site that will show night revelers a listing of night club establishments and events happening in a big city. I'm trying to build a back-end page where an administrator can be able to add clubs and input information such as establishment name, location, relative pricing etc and of course some images of the club.
Each club will have to have at least one image, the main image. There can be an additional 5 but these are optional, ie. database fields can be null.
I have a form that looks like this:
Establishment Main Photo
TextField: name = "establishment_image"
Establishment Photo 1
TextField: name = "establishment_image"
Establishment Photo 2
TextField: name = "establishment_image"
Establishment Photo 3
TextField: name = "establishment_image"
Establishment Photo 4
TextField: name = "establishment_image"
Establishment Photo 5
TextField: name = "establishment_image"
Its kinda like the yahoo mail attach file form. As you can see the textfields have the same textfield name for now.
I need to know what kind of changes I need to make on my submit form to be able to: for instance;
Put a main pic and leave other textfields blank,
Put a main pic, pic 1 and 2 and leave other textfields blank,
Put a main pic, pic 1, 2 and 3 and leave other textfields blank etc.
My establishment_submit.php looks like this:
<?php require_once('../Connections/connections.php'); ?>
<?php //maintain the session
if (!isset($_SESSION))
{
session_start();
}
?>
<?php
//retrieve data from Query String
$establishment_name= $_POST['establishment_name'];
$short_description= $_POST['short_description'];
$long_description= $_POST['long_description'];
$location= $_POST['location'];
$url_link= $_POST['url_link'];
$establishment_address= $_POST['establishment_address'];
$establishment_pricing= $_POST['establishment_pricing'];
$establishment_telephone= $_POST['establishment_telephone'];
$establishment_contact= $_POST['establishment_contact'];
$establishment_email= $_POST['establishment_email'];
$establishment_image = $_FILES['establishment_image']['name'];
//escape User Input to help prevent SQL Injection
$establishment_name= mysql_real_escape_string($establishment_name);
$short_description= mysql_real_escape_string($short_description);
$long_description = mysql_real_escape_string($long_description);
$location= mysql_real_escape_string($location);
$url_link= mysql_real_escape_string($url_link);
$establishment_address= mysql_real_escape_string($establishment_address);
$establishment_pricing= mysql_real_escape_string($establishment_pricing);
$establishment_telephone= mysql_real_escape_string($establishment_telephone);
$establishment_contact= mysql_real_escape_string($establishment_contact);
$establishment_email= mysql_real_escape_string($establishment_email);
$establishment_image= mysql_real_escape_string($establishment_image);
//redirect when successful
$establishmentAddSuccess = "establishment_add_success.php";
?>
<?php
//define a maximum size for the uploaded images
define ("MAX_SIZE","10000");
// note that these dimensions are considered the maximum and are not fixed
// because we have to keep the image ratio intact
//define a maximum size for the uploaded images
define ("LARGE_WIDTH","500");
define ("LARGE_HEIGHT","390");
define ("WIDTH","100"); //set here the width you want your thumbnail to be
define ("HEIGHT","100"); //set here the height you want your thumbnail to be.
// this is the function that will create the appropriately sized images from the upload
// the resize will be done considering the width and height defined, but without deforming the image
function make_largeimage($img_name,$filename,$new_large_w,$new_large_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
if(!strcmp("gif",$ext))
$src_img=imagecreatefromgif($img_name);
//gets the dimensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimensions for the large image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimensions will be from the fixed ones
$ratio1_large=$old_x/$new_large_w;
$ratio2_large=$old_y/$new_large_h;
if($ratio1_large>$ratio2_large)
{
$large_w=$new_large_w;
$large_h=$old_y/$ratio1_large;
}else
{
$large_h=$new_large_h;
$large_w=$old_x/$ratio2_large;
}
// we create a new image with the new dimensions
$dst_large_img=ImageCreateTrueColor($large_w,$large_h);
// resize the big image to the newly created one
imagecopyresampled($dst_large_img,$src_img,0,0,0,0,$large_w,$large_h,$old_x,$old_y);
// output the created image to the file. Now we will have the image into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_large_img,$filename);
else
imagejpeg($dst_large_img,$filename);
if (!strcmp("gif",$ext))
imagegif($$dst_large_img,$filename);
//destroys source and destination images.
imagedestroy($dst_large_img);
imagedestroy($src_img);
}
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
if(!strcmp("gif",$ext))
$src_img=imagecreatefromgif($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2)
{
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}else
{
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the newly created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);
if (!strcmp("gif",$ext))
imagegif($dst_img,$filename);
//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors=0;
// if it is not empty
for($i=0;$i<count($_FILES['establishment_image']["name"]);$i++)
{
// get the original name of the file from the clients machine
$filenames = stripslashes($_FILES['establishment_image']['name'][$i]);
// get the extension of the file in a lower case format
$extensions = getExtension($filenames);
$extensions = strtolower($extensions);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extensions != "jpg") && ($extensions != "jpeg") && ($extensions != "png") && ($extensions != "gif"))
{
$warning = ("File extension of an image(s) not allowed");
header("location:establishment_add.php?warning=$warning");
$errors=1;
exit();
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['establishment_image']['tmp_name'][$i]);
$sizekb=filesize($_FILES['establishment_image']['tmp_name'][$i]);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE*1024)
{
$warning = ("Images have exceeded the size limit of 10MB");
header("location:establishment_add.php?warning=$warning");
$errors=1;
exit();
}
$rand= rand(0, 100000);
//we will give an unique name, for example a random number
$image_name=$rand.'.'.$extension;
//the new name will be containing the full path where the image will be stored (images folder)
$consname="C:/wamp/www/NNL/Administrator/Establishment_Images/".$image_name; //change the image/ section to where you would like the original image to be stored
$consname2="C:/wamp/www/NNL/Administrator/Establishment_Images/Thumbs/".$image_name;
//change the image/thumb to where you would like to store the new created thumbnail of the image
$copied = copy($_FILES['establishment_image']['tmp_name'][$i], $consname);
$copied = copy($_FILES['establishment_image']['tmp_name'][$i], $consname2);
//localhost calling of images
$img_large="../Establishment_Images/".$image_name; //change the image/ section to where you would like the original image to be stored
$img_thumb="../Establishment_Images/Thumbs/".$image_name;
//we verify if the image has been uploaded, and print error instead
if (!$copied) {
$warning = ("Unable to upload image file");
header("location:establishment_add.php?warning=$warning");
$errors=1;
exit();
}else{
// the new large image will be placed in Images/ folder
$imagelarge_name=$consname ;
// call the function that will create the thumbnail. The function will get as parameters
// the image name, the thumbnail name and the width and height desired for the thumbnail
$imagelarge=make_largeimage($consname,$imagelarge_name,LARGE_WIDTH,LARGE_HEIGHT);
// the new thumbnail image will be placed in Images/Thumbs/ folder
$thumb_name=$consname2 ;
// call the function that will create the thumbnail. The function will get as parameters
// the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($consname,$thumb_name,WIDTH,HEIGHT);
}
}
}
?>
<?php
//If no errors registered, redirect page
if(isset($_POST['Submit']) && !$errors)
{
//insert into database
$query2 = "INSERT INTO establishment(establishment_name,
establishment_short_description,
establishment_long_description,
establishment_address,
establishment_telephone,
establishment_contact,
establishment_email,
location_id,
establishment_pricing,
establishment_url_link,
establishment_mainphoto_url,
establishment_thumb_url)
VALUES
('$establishment_name',
'$short_description',
'$long_description',
'$establishment_address',
'$establishment_telephone',
'$establishment_contact',
'$establishment_email',
'$location',
'$establishment_pricing',
'$url_link',
'$img_large[0]',
'$img_thumb[0]')";
//Execute query
$qry_result2 = mysql_query($query2) or die(mysql_error());
header("Location: " . $establishmentAddSuccess);
}
else
{
$establishment_msg = ("Unable to add establishment");
header("location:establishment_add.php?establishment_msg=$establishment_msg");
exit();
}
?>
This worked fine for single image uploads but doesnt work now. I know I need to make changes from the line;
for($i=0;$i<count($_FILES['establishment_image']["name"]);$i++)
{
How do I make this form be able to upload multiple images. I will appreciate any help.
You can use PHP's array notation as you would in regular form fields:
Pic 1: <input type="file" name="establishment_image[]" />
Pic 2: <input type="file" name="establishment_image[]" />
However, the file processing stuff in PHP will handle it a bit differently than you'd expect server-side:
$_FILES = array(
'establishment_image' => array(
'name' => array(
0 => 'name of Pic 1 file',
1 => 'name of Pic 2 file'
),
'error' => array(
0 => error code for pic1 upload,
1 => error code for pic2 upload
etc...
);
It's easy enough to handle, though:
foreach(array_keys($_FILES['establishment_image']['name']) as $idx) {
....
}
The other option is to give each file input a unique name and work with that serverside. If you hard code a numeric "sub key" in each:
<input type="file" name="establishment_image_1" />
<input type="file" name="establishment_image_2" />
Then you can simply do
for ($i = 1; $i <= 5; $i++) {
echo "Name of file is ", $_FILES["establishment_image_$i"]['name'];
...
}
Image upload pages are a lot of brain damage when you consider the quirks of imagick, UI patterns for the upload page, permissions, etc. My shortcut in a situation where an internal admin is doing the page is Gallery.
The admin then uses gallery for upload, resize, cropping, etc. In essence, the basics plus the "extras" that my clients might demand but that I might not be able to justify charging enough to do from scratch. On the user-side, I query out the gallery from the MySQL database and arrange in any manner I wish, normally via a flashy JQuery front-end I've rigged up. But, it could be anything...and I could even use the gallery stock front-end.
Simiplicity-wise, it doesn't get easier for the user to understand. I can have it up and running in under 2 hours start to finish. And since images are being stored statically in the file system, there's no more additional load than expected.
If you do opt to go it alone, there's certainly more than one way to attack this challenge. I'd recommend checking out this popular post: How can I upload files asynchronously?