I have setup a simple while loop which returns all images in a table along with their respective title and description so that users can update the details accordingly for each image.
The images are returned with a checkbox which allows user to delete images as per php code
if($_POST['doDelete'] == 'Delete') {
if(!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
mysql_query("delete from landscape where id='$id'");
}
}
$ret = $_SERVER['PHP_SELF'] . '?'.$_POST['query_str'];;
header("Location: $ret");
exit();
}
How do I incorporate the unlink() function into the page so that the file is also removed from the server?
Just use Unlink() with in loop like :
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
if(mysql_query("delete from landscape where id='$id'")){
unlink( '/path/to/images/' . $id);
}
}
I have used If because if the file deleted successfully from the database only then it will be deleted from the server.
Also If you have moved the file into folder by the name of file then First get information about file from database by $id and then use
unlink( '/path/to/images/' . $file_name);
instead
unlink( '/path/to/images/' . $id);
Hope it will help you.
If the images are named in accordance with the ID:
foreach ($_POST['u'] as $uid) {
$id = filter($uid);
mysql_query("delete from landscape where id='$id'");
unlink( '/path/to/images/' . $id);
}
Be sure to properly escape $id before using it in your query or in the unlink statement.
Well, where are the files stored on the server? How are they stored? Just call unlink with the file path that leads to where the image is stored.
Related
How do I delete a single file from a folder? When I click my delete link, it removes all uploaded files from the folder.
The link:
<td>Delete
The code:
<?php
// Including the database connection file
include_once 'Ad_updbconnect.php';
// Getting Id of the data from url
$Id = $_GET['Id'];
$Del = glob('uploads/*'); // Get all file names
foreach ($Del as $File) {
if (is_file($File)) {
unlink($File); // delete file !
}
}
// Deleting the row from table
$Result = mysqli_query ($Con, "DELETE FROM ibgsec_uploads WHERE Id=$Id");
$Row = mysqli_fetch_array($Result);
// Redirecting to the display page.
header("location: Ad_uploads.php");
?>
This is the only thing left I'm working on, I've tried lots of ways to properly execute the command but it does not work.
Your code explicitly deletes every file in uploads. What did you expect?
$Del = glob('uploads/*'); // Get all file names
foreach ($Del as $File) {
if (is_file($File)) {
unlink($File); // delete file !
}
}
Is $Id a file name? Seems risky but all the same you would want to try comparing that to $File. Compare something to $File otherwise you're just deleting them all.
You also are naming your param in the link $Id: <a href="Ad_delete.php?$Id=<?php echo $Row['Id'];?>" but fetching it as Id: $Id = $_GET['Id'];. Then you open yourself up to SQL injection by including that in the database query.
I have a problem with unlink or delete file with codeigniter
Here is my controller
function delete($id_post=''){
$this->home_model->delete($id_post);
$this->session->set_flashdata('danger', "Your photo has been deleted...");
redirect("home");
}
And this is my model
function delete($id_post=''){
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
unlink(base_url("uploads/" . $file_name));
$sql = "DELETE FROM post WHERE id_post=?";
$outp = $this->db->query($sql,array($id_post));
}
Doc is the name of column that contain image.
If i click button delete, it delete a data in database and works successfully but not the image in file folder. I want, when i delete a data it is also delete image in file folder uploads. Uploads folder is in the root aplication system.
Any answer?
Many thanks...
The query() function returns a database result object. So replace your model code with:
function delete($id_post=''){
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
$row = $file_name->row();
$file_name = $row['doc'];
unlink(base_url("uploads/" . $file_name));
$sql = "DELETE FROM post WHERE id_post=?";
$outp = $this->db->query($sql,array($id_post));
}
Try this:
$this->load->helper("url");
unlink(base_url("uploads/" . $file_name));
function delete($id_post=''){
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
$res = $this->db->result(); // this returns an object of all results
$row = $res[0];
$filename = $row['doc']; // get the file name from array
// do the delete after getting the filename
}
Instead of this
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
please replace this
$file_name = $this->db->query("SELECT doc FROM post WHERE post.id_post='".$id_post."'")->row()->doc;
This is because you does not fetch your result resource.
Use:
$query = $this->db->query("SELECT doc FROM post WHERE post.id_post='$id_post'");
$row = $query->result();
$file_name = str_replace('localhost/latihan/uploads/','',$this->db->query("SELECT doc FROM post WHERE post.id_post='".$id_post."'")->row()->doc);
unlink("uploads/" . $file_name);
can use this using directory path
unlink(FCPATH.'uploads/yourfile');
You are trying to delete your file with URL address you have to specifiy local document address like this:
unlink($_SERVER['DOCUMENT_ROOT']."uploads/".$filename);
here is similiar question:
Cannot unlink file in Codeigniter
I am trying to delete a photo from upload folder when i press delete all records are deleted except the picture in upload folder here is my delete, how to i code the snippet to delete from upload folder
//trigger
<?php
echo '<td><a href="delete.php?staff_id=' . $row['staff_id'] . '"><input type="button" onclick="confirmDelete(event)" value="delete">';
// check if the 'staff_id' variable is set in URL, and check that it is valid
if (isset($_GET['staff_id']) && is_numeric($_GET['staff_id']))
{
// get staff_id value
$staff_id = $_GET['staff_id'];
// delete the entry
$result = mysql_query("DELETE FROM development WHERE staff_id=$staff_id") or die(mysql_error());
}
In your delete.php script you would need a line like this :
unlink( "path_to_your_upload_directory/".$staff_id.".jpg" );
If you have various file extensions : One way to achieve it is to first save the filename with extension in an appropriate database table when the user/staff uploads the file . Retrieve the same and use it when deleting the file :
$filename_with_extension = 'retrieve this from database table where it is stored';
unlink( "path_to_your_upload_directory/".$filename_with_extension );
unlink() function in PHP. You have to provide full path to that file in parameter.
NOTE: Do not give http:// path.
Use unlink function. This will remove a file from the specified directory
if(isset($_GET['staff_id'])&&is_numeric($_GET['staff_id']))
{
$Staff_Id = mysql_real_escape_string($_GET['staff_id']);
if($Staff_Id != '.' || $Staff_Id != '..')
{
$extension = '.jpg';
if(unlink('uploads/'.$Staff_Id.$extension))
{
$result = mysql_query("DELETE FROM development WHERE staff_id=$staff_id")or die(mysql_error());
}
}
}
I am trying to develop a user page for a forum and I'm kinda struggling with the image upload.
The problem is that I would like to limit the user to only be able to upload one single image, but be able to change it anytime. so basically, I would like to either overwrite the existing file either delete the old picture and add a new one instead.
At this point I have a piece of code that adds a timestamp at the end of the file (which I don't really need actually).
CODE:
if(isset($_POST['upload']))
{
$extension=strstr($_FILES['uploadedfile']['name'], ".");
$filename = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name'],
$extension);
$target = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name']);
$valid = true;
if(file_exists($target))
{
$filename = $filename . time();
$target = $filename . $extension;
}
if($valid)
{
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
Make use of unlink() in PHP Manual.
if(file_exists($target))
{
unlink($target); // deletes file
//$filename = $filename . time();
//$target = $filename . $extension;
}
I think this might be a bit better suited for you. You might have to edit it a tad.
if($valid)
{
// Check if user has a file.
$img_check = mysql_query("SELECT * FROM sp_userimage WHERE id = " . (int) $_SESION['user_id']);
if( mysql_num_rows($img_check) > 0 ){
$row = mysql_fetch_object($img_check);
// Delete the file.
unlink($row->path);
}
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
It might be easier to normalize the image type (e.g. only jpegs) and then name the file as the userid. For example:
$target = 'userpics' . DIRECTORY_SEPARATOR . $_SESSION['userid'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
This will simply overwrite the old picture with the new one. Given that this type of filename is deterministic, you also don't need to store the filename in the database.
Use unlink() function
read more here PHP unlink
okay ,if u want to delete the file for that particular user only.
then store the filename vs user in some MapTable in db.
mysql_query("CREATE TABLE t_usr_file_map(
usr_id INT NOT NULL ,
file_name VARCHAR(100),
)")
or die(mysql_error());
and at the time of reupload , fetch the filename from the table for that user , unlink it and reupload the fresh one again.
OR,
or u can use PHP file_rename function at the time of upload. rename filename to the userid
rename ( string $oldname , string $newname [, resource $context ] )
and u can always do unlink based on user-id
Its very simple by unlink()
as:
unlink(dirname(__FILE__) . "/../../public_files/" . $filename);
if (file_exists($path))
{
$filename= rand(1,99).$filename;
unlink($oldfile);
}
move_uploaded_file($_FILES['file']['tmp_name'],$filename);
i upload image to the server and save the path in data base. Now i want to delete that record and also the image with that record
my code is
$id=$_GET['id'];
$select=mysql_query("select image from table_name where question_id='$id'");
$image=mysql_fetch_array($select);
#unlink($image['image']);
$result=mysql_query("delete from table_name where question_id='$id'");
when i echo $image['image']; this will give me http://www.example.com/folder/images/image_name.jpeg
The record is deleted successfully but the image remains there on server.
You'll have to use the path on your server to delete the image, not the url.
unlink('/var/www/test/folder/images/image_name.jpeg'); // correct
you should remove the # before unlink(), in that case you would have seen the error-message saying "file not found" or something like that.
Simply if you use folder/images/image_name.jpeg in place of whole url inside unlink it will work fine
e.g.
unlink("http://www.example.com/folder/images/image_name.jpeg");
should be replaced with
unlink("folder/images/image_name.jpeg");
you should use the relative path for delete a file from the server with unlink. If you save the absolute path in your database, first you have to see from what folder you delete the image. so if you delete image from "delete.php" that is in www.example.com/folder/delete.php than you should do something like this:
$db_path = "http://www.example.com/folder/images/upArrow.png";
$len = strlen("http://www.example.com/folder/");
$new_path = substr($db_path, $len, strlen($db_path)-$len); echo " -> ".$new_path;
if(isset($_POST['Submit'])){
$return = unlink($new_path);
if($return){echo "Succes";}else{echo "Fail";}
}
whenever you select the your code in delete link.
like:<a href=addproduct.php?action=delete&pid=$get_info[pid]>Delete</a>
then you have to check the condition using cuurent select item.
if(isset($_GET['action']) && $_GET['action']=='delete' && isset($_GET['pid']))
{
$query1=("select * from tablename where id='".$_GET['id']."'");
$result1=mysql_query($query1);
while($data=mysql_fetch_array($result1))
{
$delete=$data['file'];
unlink("../upload/$delete");
}
$query=("delete from tablename where id='".$_GET['id']."'");
$result=mysql_query($query) or die("not inserted". mysql_error());
if($result==TRUE)
{
$_SESSION['msg']="product successfully deleted";
header("Location:addproduct.php");
exit;
}
else
{
$_SESSION['msg']="error in deleting product";
header("Location:addproduct.php");
exit;
}
}
//http://www.example.com/folder/images/image_name.jpeg
define("BASE_URL", DIRECTORY_SEPARATOR . "folder" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);
$folder_upload = "images/";
$image_delete = ROOT_PATH . $folder_upload . pathinfo($image['image'], PATHINFO_BASENAME);
if (!empty($image['image'])) {
/* Delete */
if (unlink($image_delete)) {
echo "<b>{$image_delete}</b> has been deleted";
} else {
echo "<b>{$image_delete}</b> error deleting ";
}
} else {
echo "File image not exist";
}
// http://localhost/folder/images/image_name.jpeg