-2

php is getting image in following format, while echoing $_POST['img']

http://localhost/uploads/images/1533033949-8.jpg

But why unlink doesn't working -

// Get src.
$img = $_POST["img"];

// Check if file exists.
if (file_exists(getcwd() . $img)) {
  // Delete file.
  unlink(getcwd() . $img);
  echo "Deleted";
}

I tried testing directly, but doesn't work

unlink($img)
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Dipak
  • 931
  • 14
  • 33
  • Does the file exist at `getcwd() . $img` ? Have you printed that out to see what it looks like? And do you/your script/your server have permissions to unlink a file? – brombeer Jul 31 '18 at 11:01
  • 3
    `unlink` works on the file system, not with HTTP URLs. And appending `http://localhost/uploads/images/1533033949-8.jpg` to the current working directory is very unlikely to give you a proper file system path. – CBroe Jul 31 '18 at 11:02
  • 1
    The manual on `getcwd()` http://php.net/manual/en/function.getcwd.php **explicitly** states: *"Returns the current working **directory** on success, or FALSE on failure."**, not a URL. Plus `The above example will output something similar to: /home/didou /home/didou/cvs`. So look at the URL you get now; not the same right? There you go, *wink*. – Funk Forty Niner Jul 31 '18 at 11:02
  • converting url information in variable using `substr, strlen` works. – Dipak Jul 31 '18 at 12:49

2 Answers2

2

unlink works on the file system, not with HTTP URLs. And appending

@CBroe is correct

First get the base path on you live server or manually specify the base path like below example

$base_directory = '/home/myuser/';

then unlink the file that you need to remove.

if(unlink($base_directory))
    echo "File has been Deleted.";

I hope it helps.

Peter
  • 777
  • 2
  • 13
  • 34
  • Thanks, but it doesn't work, After trying many ways, I solved storing url info as variable and path with the help of php `substr, strlen` function, I've posted in answer – Dipak Jul 31 '18 at 12:45
0

Finally I solved storing url information as variable and php substr, strlen function.

$img=$_POST['img'];
$len = strlen("http://localhost/uploads/");
$new_path = substr($img, $len, strlen($img)-$len); 
if(unlink($new_path)){
    echo "Deleted";
}
else{
    echo "Fail";
}
Dipak
  • 931
  • 14
  • 33