How to unlink image in php

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");

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;
                                    }
                            }

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";}
    }

Tags:

Php