I want to use PHP and MySQL to delete an image from a folder inside the server. The image name is inside the database (the format [jpg] is already included on the image name). I tried many ways and the following is one of them, but it's not working yet. Help please.
if(isset($_POST['submit2'])) {
$numeroimagem = $_POST["numero"];
$imagem=mysqli_query($con,"SELECT imagem FROM galeria WHERE numero='$numeroimagem'");
$nomeimagem=mysqli_fetch_row ($imagem);
$target = '../imgs/galeria/'.$nomeimagem;
if (file_exists($target)) {
unlink($target);
}
}
The form:
<form action="" method="post">
<input name="numero" type="text" size="3" maxlength="3"><input type="submit" name="submit2" value="Delete"><br>
</form>
You forgot to delete the file. You can use the function unlink for that:
http://php.net/manual/en/function.unlink.php
We cannot know exactly the error, but the main issue was the File what not with realpath function.
Realpath function resolves if a path is correcty
if you try realpath('../imgs/galeria/') php will resolve full path.
If realpath return false or null, the path cannot be resolved, when you have to try accoplish the right path.
If you are running script from folder scripts/delete-imagem.php, and the files at public/imgs/galeria, you should use realpath('../public/images/) to get full path.
Once you get the full path, you should try to remove it using "unlink()"
$path = realpath('../public/imgs/galeria/');
if(is_dir($path)) {
if(is_file($path.'/'.$fileName)) { //Note that realpath trim the final "/" from filepath.
unlink($path.'/'.$fileName);
{
}
This code will force it works.
I just found out the problem. I was getting Array on the file name it was solved by adding [0] like this:
$target = '../imgs/galeria/'.$nomeimagem[0];
Thanks for the tips anyways :)
Related
I know there are already many similar questions like this and I apologize in advance for adding to the file, but I am a little short on time to do research and I need quick help. I am trying to finish an overdue assignment and my image upload function is working perfectly when I add a product, but not when I update it. I have no idea why. My code to update the image is here:
require_once 'file-util.php'
// Check if the file exists before setting it
if (isset($_FILES['imageFile1'])) {
// Retrieve the name of the file based on what it was called on the client computer
$filename = $codeInput . '.png';
// Make sure the filename exists
if (!empty($filename)) {
// Store the temporary location of where the file was stored on the server
$sourceLocation = $_FILES['imageFile1']['tmp_name'];
// Build the path to the images folder and use the same filename as before
$targetPath = $image_dir_path . DIRECTORY_SEPARATOR . $filename;
// Move file from temp directory to images folder
move_uploaded_file($sourceLocation, $targetPath);
}
}
This is the exact same code that I have in my insert_product file.
And my file_util is here:
$image_dir = 'images';
$image_dir_path = getcwd() . DIRECTORY_SEPARATOR . $image_dir;
Everything else works perfectly, but it is just this little thing that isn't seeming to do anything, so it seems to me like there's a little detail I'm missing for this to work in update_product. Is there something else I need to do to get this to work, or is it something else I'm unaware of?
Edit: Turns out that I just forgot to set the encryption type in my add_product_form. If anyone else has this silly issue, double check your forms for this near the top of the body:
<form action="insert_product.php" method="post"
id="add_product_form"
enctype="multipart/form-data">
You need to check if your updating form tag has the proper enctype attribute value...
and please be aware to use more validation on the uploaded file, your checking for file name exists or not will always be true as you are setting a value for it in the previous line.
Apparently, my code was right but I just forgot to go "enctype="multipart/form-data" in update_product_form.php.
I have a form for users to upload files into the folder.
HTML and PHP codes are as below:
<form enctype="multipart/form-data" method="post" action="test.php">
<input type="text" name="name"/><br/>
<input type="file" name="photo" /><br/>
<input type="submit"/>
</form>
<?php //test.php
move_uploaded_file($_FILES["photo"]["tmp_name"], "testFolder/".$_POST["name"]);
?>
The upload form works well, and uploaded files are in the folder testFolder/ .
Now I want to use glob() function to get all file names in the folder.
<?php
foreach(glob("testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
However, it doesn't echo anything.
The glob() function works well on other folders, which contains existing files, not uploaded files.
But why doesn't it work on this folder with uploaded files ?
Possbile wildcard extension could be the issue.
It may be that glob does not allow wildcard extensions, i dont see any mention of this in the docs. Have you tried a directory iterator?
$dir = new DirectoryIterator(__DIR__.'/testFolder);
foreach ($dir as $file) {
echo $file->getFilename();
}
UPDATE: THE PATH IS NOT THE ISSUE
You are using a relative file path, therefore glob probably isn't finding the directory you are trying to search for.
Either the script calling the function needs to sit inside the parent directory of 'testFolder' or you need to use an absolute path like so.
<?php
foreach(glob("/absolute/path/to/testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
If you do want to use a relative path you could do the following:
<?php
//__DIR__ is a PHP super constant that will get the absolute directory path of the script being ran
// .. = relative, go up a folder level
foreach(glob(__DIR__."/../testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
Obviously the paths above are examples but should get you on the right track.
Hope this helps
Because I didn't give the extension for the uploaded file, that's why glob("testFolder/*.*") doesn't get anything.
Two solutions:
Give uploaded files an extension.
$ext = strrchr($_FILES["photo"]["name"], ".");
move_uploaded_file($_FILES["photo"]["tmp_name"],
"testFolder/".$_POST["name"].$ext);
Then, glob("testFolder/*.*") will be able to get these uploaded files with an extension.
Just change glob("testFolder/*.*") to be glob("testFolder/*")
In my project I have a folder secure in root. The project package looks like:
application
secure
system
...........
Inside secure folder I am uploading some images on form submit using
$config1['upload_path'] = './secure/';
$ext = end(explode(".", $_FILES['thumb_image']['name']));
$config1['file_name'] = time().$_FILES['thumb_image']['name'];
$config1['allowed_types'] = 'jpg|png|jpeg|gif|bmp|jpe|tiff|tif';
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
$this->upload->do_upload('thumb_image');
and it is working properly. Now while on editing the details, using another form, if I am uploading a new image instead of the current image file, I want to unlink the current one and then upload new file.
For this I am using the code:
unlink(base_url("secure/".$data['row']->videothumbnail));
I also tried with
unlink('/secure/'.$data['row']->videothumbnail);
where $data['row']->videothumbnail) is the current image file from database. New file is successfully uploaded. But old file is not getting unlinked. I have set the permission of secure folder to 777. But the images are uploaded with read only permission. Is it because of this, it is not getting unlinked?
Can anyone help me to solve this?
Thanks in advance.
Try this:
Set the permission dynamically using:
#chmod('./secure/'.$data['row']->videothumbnail, 0777);
then try unlink:
#unlink('./secure/'.$data['row']->videothumbnail);
Try echoing the path that you are providing to unlink function.
It should be something like this:
base_url()."secure/".$data['row']->videothumbnail;
I also had this issue even after setting the right permission on the folder. But the following code worked for me.
unlink(realpath(APPPATH . '../uploads').'/'.$ImageName);
Try to use $_SERVER['DOCUMENT_ROOT'] instead of base_url
$this->load->helper("file")
unlink(base_url('folder/file.ext'));
location:
\app\controller
\system\libraries
**folder\file.ext**
$unlinkUrl = "secure/".$data['row']->videothumbnail;
if(file_exists($unlinkUrl)){
unlink($unlinkUrl);
}
else{
echo $unlinkUrl." is not available";
}
I think you are just making a stupid mistake.
Firstly, the first param of unlink should be a relative path or absolute path, but base_url function will return you a path contains domain name, HOW CAN YOU DELETE A FILE ON REMOTE SERVER ?
Secondly, '/secure/'.$data['row']->videothumbnail here is not a relative path but a absolute path
YOU MUST change it into /the/absolute/path/to/secure/ or ./the/relative/path/to/secure/ (DO NOT MISS THE DOT)
use this to unlink
$oldthumb = "secure/".$data['row']->videothumbnail;
#unlink($oldthumb);
First Load the $this->load->helper("file") and then unlink it
unlink("secure/".$data['row']->videothumbnail);
if ($rowAffected > 0) {
if ($isMediaUpload)
if (file_exists('./uploads/' . $this->input->post('img_url')))
unlink('./uploads/' . $this->input->post('img_url'));
redirect('/admin/configration', 'location');
}
Though i came in late but someone might need this .
unlink(FCPATH."secure/".$data['row']->videothumbnail)
**FCPATH** - path to front controller, usually index.php
**APPPATH** - path to application folder
**BASEPATH** - path to system folder.
I try to unlink an image in CodeIgniter, but the unlink function shows:
notice Undefined index: userfile
Here is my code
<?php
function get_from_post(){
$data['logo_name'] = $this->input->post('logo_name',TRUE);
$data['logo_thumb'] = $_FILES['userfile']['name'];
return $data;
}
function deleteconf($data){
$data= $this->get_from_post();
$update_id=$this->uri->segment(3);
#unlink(base_url.'image/logo_thumb'.$logo_thumb);
$query= $this->_delete($update_id);
}
?>
the unlink function shows notice Undefined index: userfile
The upload form, using multipart/form-data
Make sure you've use enctype="multipart/form-data" attribute/value for your upload form.
<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">
From the MDN:
enctype
multipart/form-data: Use this value if you are using an <input>
element with the type attribute set to "file".
If you're going to use CodeIgniter form helper, you could use form_open_multipart() function:
This function is absolutely identical to the form_open() tag above
except that it adds a multipart attribute, which is necessary if you
would like to use the form to upload files with.
Deleting files, File path vs URL address
PHP unlink() function accepts the Path of the file as the first argument. Not the URL Address.
The base_url() helper function returns the URL address of the site, which you've set in the config.php file.
You'll have to use the path of the file on your server, as follows:
unlink('/path/to/image/image_name.jpg'); // This is an absolute path to the file
You could use an Absolute or Relative path, but note that the relative path is relative to the index.php file. i.e. If the image/ folder is placed beside index.php file, you should use image/image_name.jpg as the file path:
unlink('image/image_name.jpg'); // This is a relative path to the file
If you want to upload a photo for user profile and also
at the time the old user photo should be deleted by
using unlink method in codeignitor
$query = $this->db->where('profile_id',$profile_id)->get('users')->row();
$result = $query->photo;
$result = http://localhost/abc/user_photo/FE12563.jpg
if ($result) {
$dd = substr($result, strlen(base_url()));
unlink($dd);
return $this->db->set('photo',$photo)->where('profile_id',$profile_id)->update('users');
}
First check your file input name. Is it "userfile" or not?
if not then add it and then run it once again.
function get_from_post(){
$filename = $_POST['logo_name'];
$path = $_SERVER['DOCUMENT_ROOT'].'/projectname/uploads/'.$filename ;
if(is_file($path)){
unlink($path);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
base_url() function returns url of you project but here you have to use directory path of file which you want to delete.
$path = BASEPATH.'/assets/upload/employees/contracts/';
$get_file = $path.$con_id.'.jpg';
if(file_exists($get_file)){
unlink($get_file);
}
instead of unlink(base_url("/assets/upload/employees/contracts/'.$con_id."));
First unlink function work only with path (without url), so please remove base_url() function.
Then in your first function $_FILES array doesn't contain userfile index, that's why getting error.
NOTE:- Before using unlink i would like to use also file_exists() function, first it will check if file is exist on same path then use unlink function (for error handling).
Like that -
<?php
if(file_exists(filePath))
{
unlink(filePath);
}
?>
Please fix both issue.
Thanks
Suppose you have the file name in the database and your file is abc.jpg. Then to unlink that in Code Igniter just do -
$file = "abc.jpg";
$prev_file_path = "./assets/uploads/files/".$file;
if(file_exists($prev_file_path ))
unlink($prev_file_path );
My file upload path is "public_html/assets/uploads/files/". I am writing the above code in my controller which is "public_html/application/controllers/MyController.php". So the path will be same which I used in my CI file upload section. i.e.
...
$config['upload_path'] = './assets/uploads/files';
...
So we used relative path in both the upload and unlink section. So if the upload works perfectly then this will also work perfectly.
You can do like this, you need to get first the path of directory from where you have uploaded your image.
Exemple:
//this is your url
$mainPath='https://google.com/uploads/image/16.jpeg';
$uploadedDirectory=str_replace("https://google.com/","./", $mainPath);
//now you get path like this ./uploads/image/16.jpeg
if(unlink($uploadedDirectory)) {
$this->db->where('prodId',$id);
$this->db->delete('products');
}
$this->load->helper("file");
just add above line before unlink
unlink($path);
Can you please use this code to remove image on folder.
unlink(realpath('uploads/' . $_image));
"uploads" : Image exist in uploads folder.
"$_image" : Image file name
PHP functions:
1 : unlink()
2 : realpath()
The above code successfully working on my site to delete image on folder.
try this code
unlink(base_url().'/image/logo_thumb'.$logo_thumb);
Note: You didn't assign / declare $logo_thumb in your deleteconf().
Please check your code.
I have a form with the possibility to upload an image from the computer to a server, but it won't work. I don't get any error message, so that's quite annoying. (First I got permission denied, but that was solved by changing the rights), but now when I submit the form, everything goes normally, but the file isn't copied to the destination folder. (The folder exists: I tried it with file_exist()...)
Here's part of the code:
<form action='/changingfruit/index.php?item=bad' name='form' method='post' enctype='multipart/form-data'>
<tr>
<td><input type='text' name='titel_nl' value="titel nl" /><br/><input type='text' name='titel_fr' value="titel fr"/></td>
<td><input type='file' name='text_nl' id='text_nl' accept="image/*"/><br/><input type='file' name='text_fr' id="test_fr" accept="image/*"/></td>
<td class="vTop"><input type="submit" value="Bewaar"/></td>
</tr>
</form>
Part where the values are being send to the db:
$str_titel_nl = $_POST["titel_nl"];
$str_titel_fr = $_POST["titel_fr"];
$str_text_nl = $_FILES["text_nl"]["name"];
$str_text_fr = $_FILES["text_fr"]["name"];
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
(of course the above is just a part of the code: but it's this part that wont work:
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
The code below this part also works fine, so no error, but also no image.
Does someone knows where the problem could be?
Thanks so much in advance!
FOUND THE ANSWER
So it was indeed a permission problem. Everything was 777, but the last folder where the image was put had 755. (/fruits/img/2012/thumb/) the thumb was 755.I just overlooked it. Thanks everyone for the help!
Your upload code is very messy. Instead of using copy you should be using move_uploaded_file, and also validate that it actually worked and then perform whatever actions needed.
I'm also not sure why each of your line is starts with <?php and ends with ?> ?
You can write it all as one block instead, and i think it would also make more sense and would make your code cleaner for sure.
Last thing i would recommend is reading "Handling File Uploads" from the PHP Manual. It might shed some light on the problems you're having.
P.S. Try adding on top ini_set("display_errors","On"); error_reporting(E_ALL); and see if you're getting any error messages.
please have a look on below link.
PHP upload file to web server from form. error message
http://patelmilap.wordpress.com/2012/01/30/php-file-upload/
you can try this
$flag = #copy($temp, $move);
if ( $flag === true )
{
print "Uploaded";
}
I have posted a simple solution for file uploading without worrying about the implementation .
Click to see the thread
image uploading issue in codeigniter 2.1.0
Please read this section
in that $uploader->getMessage(); will return error string related to the upload failure . So you can understand why the uploading failed .
Thanks