0x0001
0x0001

Reputation: 255

PHP unlink(); No such file or directory

I searched everywhere for this problem and can't find the solution. I have this:

<?php
  $file_name = $_GET['name'];
  $file_delete = '../u/' . $file_name;
  unlink($file_delete);
  //header("location: $file_delete");
?>

unlink returns the error: No such file or directory, but if I try header("location: $file_delete"); it opens the file (picture in this case).

Where may I be wrong?

Upvotes: 3

Views: 30262

Answers (4)

Sandhya Nair
Sandhya Nair

Reputation: 157

Get Absolute path first for the file to be deleted and check file exist before delete:

 $file_name = $_GET['name'];
 $base_dir = realpath($_SERVER["DOCUMENT_ROOT"]);
 $file_delete =  "$base_dir/your_inner_directories_path/$file_name";
 if (file_exists($file_delete)) {unlink($file_delete);}

Upvotes: 5

Robert Sinclair
Robert Sinclair

Reputation: 5406

Took me a couple of hours to figure out. As mentioned above unlink() is picky when it comes to paths.

Solution is:

1st) Define the path (this is how Wordpress does it btw):

define( 'ROOTPATH', dirname(dirname(__FILE__)) . '/' );

2) Do:

unlink(ROOTPATH.'public_html/file.jpg');

Upvotes: 0

webdev
webdev

Reputation: 13

I also had same issue with my code. What I did to solve the issue is:

First execute:

            var_dump($image_variable) // var_dump($file_delete) in your case.

It outputs: string(23)(my-image-path )

When I started counting string I just found 22 characters. I wondered where is the 23rd? I checked and count carefully, at the end I found that there is space at the end of my image path. So I used php trim() function to remove white spaces. Like,

            $trimed_path = trim($image_variable)  // trim($file_delete) in your case.

Second: Now execute,

            unlink($trimed_path).

OR CHECK LIKE

            if(unlink($trimed_path))
            {
               echo "File Deleted";
            }
            else
            {
               echo "Error Deleting File";
            }

Upvotes: 0

Matiboux
Matiboux

Reputation: 112

After some research, unlink() doesn't seem to allow you to use relative paths (with "../").

Here's an alternative:

<?php
  $file_name = $_GET['name'];
  $file_delete = dirname(__FILE__, 2) . '\\u\\' . $file_name;
  unlink($file_delete);
?>

$file_delete here is the absolute path to the file you want to delete.

Reminder: / is used for Unix systems, \ for Windows.

PHP doc:
- http://php.net/manual/en/function.unlink.php
- http://php.net/manual/en/function.dirname.php

Upvotes: 0

Related Questions