Php unlink() dont delete a image file - php

want to delete a procuct and delete the image of the product but don't no what is missing.
The product are deleting fine but don't delete the image
if((isset($_GET["remove"])) && ($_GET["remove"] != "")){
$idproduct = $_GET["remove"];
$sql ="DELETE FROM product WHERE idproduct = '".$idproduct."'";
if(mysqli_query($connect, $sql) or die ("Erro")){
//the part that don't work
$file = $frontpage_url."/images/".$_FILES["imagem"]["name"]; unlink($file);
echo "success";
}
}

Check the unlink docs.
The unlink requires the parameter to be a path to the file on your local filesystem.
From the looks of $frontpage_url you are giving it an url to the image which is not supported by unlink and also makes no sense on why that should work.
Example:
unlink('/home/path/to/image.jpg');

Try this:
unlink("images/".$_FILES["imagem"]["name"]);
If still not working, append your full path to the "images/" folder. E.g.:
unlink("public/uploads/images/".$_FILES["imagem"]["name"]);

try this
$file = "images/".$_FILES["imagem"]["name"];
unlink($file);

Related

How to delete image in database also in source folder

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']);

php - rand() update image with the name of the previous one

I have a table CRUD that display my database.
When I upload an image in my image folder I generate a random name of numbers with that function rand()
Here is what I have coded :
My upload function
function importer_image()
{
if(isset($_FILES["image"]))
{
$extension = explode('.', $_FILES['image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
}
}
My upload php
if($_POST["operation"] == "Ajouter")
{
$image = '';
if($_FILES["image"]["name"] != '')
{
$image = importer_image();
}
The problem is then when I code the update function, the substitued image stays in my folder and the new one has a new name generated. In order to avoid this, I would like to create a condition that says if $image !='' 1/ erase the old file 2/ upload the new file and keep the same name than the deleted image.
So I'm trying to create an update php process that would 1/ delete unlink() 2/ upload the new image with the name of the previous image.
In order to delete the old image and maintain new name of image as previous, you have to take a hidden input in your form which contain your uploaded image name.
For e.g :
<input type="hidden" name="old-image" value="here is your previous image">
Now when your upload function will hit then you can get previous image name by request and can delete or maintain new image as previous.
if($_FILES['image']['name'] != '') {
$old_image = $_POST['old-image']; // get old image
$new_name = $old_image; // make new image name as previous
unlink('/upload/'.$old_image); // remove old image from folder
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
} else {
//if there is no image uploaded in the form then it will maintain old image
return $new_name= $_POST['old-image'];
}
Hope it will help you.
Your code to get extension works only if you have just one dot in the uploaded filename, it won't work for example on image_a.1.jpg. Use instead:
$extension = strrchr($_FILES['image']['name'],'.');
Also, using rand() for naming will eventually give you a headache when it generates the same number the second time and the uploaded image will overwrite the old one or not get saved, possibly producing error showing the user your full server save path. I'd use some hashing, like:
$new_name = md5($_FILES['image']['name'] . time());
If you need to save the file name as int, use crc32() instead of md5(). You could convert md5() result to int, but that would produce a very long int (128bit) that might not fit in your database or even PHP code.

PHP file upload Issues - Can't Move uploaded File

I am trying to upload image to database and getting this PHP error message:
Warning: move_uploaded_file(/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpA9E6.tmp' to '/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg' in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Upload Fail.
Here is my php script:
<?php
require("include/functions.php");
check_session();
$logged_user = $_SESSION['username'];
if(isset($_FILES['avator']['name']) && $_FILES['avator']['tmp_name'] !=""){
//setting file properties
$fileName = $_FILES['avator']['name'];
$filetmpLoc = $_FILES['avator']['tmp_name'];
$fileType = $_FILES['avator']['type'];
$filesize = $_FILES['avator']['size'];
$fileErrMsg = $_FILES['avator']['error'];
//explose the filename extention into an array
$kaboom = explode('.',$fileName);
$fileExt = end($kaboom);
list($width ,$height) = getimagesize($filetmpLoc);
if( $width <10 || $height <10 ){
//the image has not dimenssion
echo 'The Image has no dimension.Try again!';
exit();
}else{
// The image is has dimension so its OK
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
//check the size of the image
if($filesize > 1048576){
echo 'Your avator file size was larger than 1mb.';
exit();
}else if(!preg_match('/\.(gif|png|jpg)$/i',$fileName)){
echo"Your avator file was not JPG,PNG or GIF type.Try again.";
exit();
}else if($fileErrMsg == 1){
echo "Unknoan Error occured. Upload Fail.";
exit();
}
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
if( $moveResult !=true){
echo 'Upload Fail.';
exit();
}else{
//resize the image
include_once("include/resizeimage.php");
$target_file = "user/$logged_user/$db_file_name";
$resize_file ="user/$logged_user/$db_file_name";
$wmax = 200;
$hmax = 230;
img_resize($target_file,$resize_file,$wmax,$hmax,$fileExt);
$sql = "UPDATE mygust SET avatar = '$db_file_name' WHERE username='$logged_user' LIMIT 1";
$query = mysqli_query($con,$sql);
mysqli_close($con);
exit();
}
}
}
?>
My HTML code is:
<form id="u_pro_pic" method="post" enctype="multipart/form-data" onSubmit="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<h2>Set your Profile Avator</h2><br>
<div id="av_wrap"><div id="avator_div"><img src="image/blank-profile.png" class="avator" title="Chose a file to upload" onClick="triggerUpload(event,'avator')"></div>
<div id="ad_clarleft">
<input type="button" class="add" title="Choose a file to upload" onClick="triggerUpload(event,'avator')" value="Add Avator"><br>
<hr>
<p>These brethren have uploaded their's and you should too. </p>
</div>
</div>
<input name="avator" type="file" id="avator" form="u_pro_pic" onChange="readURL(this)">
<input type="submit" name="u_avator" id="sumit" class="avt" value="Upload">
</form>
Please any help would be much appreciating.
PHP tries to move your uploaded file to a folder that does not exist:
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
The path "/upload" does not look like a correct windows path. Change it to something like "C:\xampp\htdocs\learnphp\upload". Create this folder manually if it does not exist.
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"C:/xampp/htdocs/learnphp/upload/$logged_user/$db_file_name");
The reason why you're getting an error on the upload, is that the folder itself does not exist; least that's the impression I am getting from it and to be honest, we don't know if efc5ad334bca9f31b19d85a6cc2ada57 exists or not.
Sidenote: Use file_exists() which is referenced further down in this answer.
Since you are using sessions for $logged_user as the username session array, make sure the session was started inside all files using sessions. session_start(); must reside inside all files, and at the top of your code.
It is good practice to check if the session is also set using isset() or !empty().
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
If not (which am pretty sure it doesn't), you would first need to create it using the mkdir() function.
http://php.net/manual/en/function.mkdir.php
The syntax is: mkdir("/path/to/my/dir", 0700); - 0700 can be changed to 0755 which is the usual setting for folders and it must be set so that the folder can be written to, using chmod.
http://php.net/manual/en/function.chmod.php
The syntax being, one of the 3 listed from the manual:
chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode
So, you will need to use the mkdir() function after the session file and before "moving" it to the folder created by $logged_user and its associated name.
I.e.:
mkdir("/path/to/your/dir", 0700); // you can use variables here
$moveResult = move_uploaded_file(...);
This part of your code /upload/ suggests using a full server path syntax.
move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name")
Either you use what your full server path is, for example:
/var/usr/public/upload/
or as referenced in another answer given C:/xampp/htdocs/learnphp/upload/
or a relative path:
I.e.:
upload/ or ../upload/ depending on the execution location of your script. The former being if executed from the root of the public area.
Nota: I am unsure if -416649605.jpg is the actual filename being uploaded, or if there is anything missing before the hyphen, or the hyphen is being added somewhere. You will need to look into that.
Pulled from my comment:
Now, if you're going to use a BLOB, that may not be big enough and may have to use a LONGBLOB https://dev.mysql.com/doc/refman/5.0/en/blob.html.
However, when using a BLOB to insert into the db directly, you will have to use mysqli_real_escape_string() for that, otherwise it won't work; you will get a syntax error thrown back.
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
So, keep on using error reporting until you can figure out where the problems may be occuring.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// if using MySQL
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysqli_error($con)) to $query = mysqli_query($con,$sql); to check for database errors.
Reference:
http://php.net/manual/en/mysqli.error.php
Additional reference:
http://php.net/manual/en/function.file-exists.php (check if a file/folder exists)
Footnotes:
Your code in its present state is open to an SQL injection. Use a prepared statement
References:
https://en.wikipedia.org/wiki/Prepared_statement
How can I prevent SQL injection in PHP?
I believe I have given you enough information in order to point you in the right direction that will and hope will lead you to success, cheers!
Replace your $moveResult statement with the following two statement as you have to store the file in folder with a specific name.
$destination = "./".$_FILES['avator']['name'];
$moveResult = move_uploaded_file( $_FILES['avator']['tmp_name'],$destination);

Can I add user ID to the file name in file upload?

I would like to add user ID to file name in file upload. I tried this:
$date=date("Y-m-d");
$id=mysql_insert_id();
//Abstract File codes
$info = pathinfo($_FILES['abstract']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $id."_Abstract.".$ext;
$target = "application/abstracts/"; $target = $target .$newname;
if (empty($ext))
{ $abstract='' ;}
else $abstract=$newname;
But I only get 0 for ID.
I can display $name but $id is not working. Is it because I do not have an input for $id on my form? Thank you. I should also mention that the user is filling out an application form (for the first time) and attaching files on the same page. I had the file upload after the application was submitted I don;t think I would have problem call the $id. But since everything is on one page I might be calling an empty $id.

White empty images after PHP upload and MySQL insertion

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

Categories