How to delete a file via PHP

0 votes
How do I delete a file from my server with PHP if the file is in another directory?

Here is my page layout:

projects/backend/removeProjectData.php (this file deletes all my entries for the database and should also delete the related file)

public_files/22.pdf (the place where the file is located.)

I'm using the unlink function:

unlink('../../public_files/' . $fileName);

But this always gives me an error that the file does not exist. Any ideas?
Sep 17, 2020 in PHP by kartik
• 37,480 points
51 views

1 answer to this question.

0 votes

Hello @kartik,

The following should help

  • realpath — Returns canonicalized absolute pathname
  • is_writable — Tells whether the filename is writable
  • unlink — Deletes a file

Run your filepath through realpath, then check if the returned path is writable and if so, unlink it.

Hope it helps!!

Thank You!!

answered Sep 17, 2020 by Niroj
• 82,540 points

Related Questions In PHP

0 votes
0 answers
0 votes
1 answer

How to prevent direct access to a php include file?

Hello @kartik, Add this to the page that ...READ MORE

answered Oct 1, 2020 in PHP by Niroj
• 82,540 points
75 views
0 votes
2 answers

How to copy a file from one directory to another using PHP?

Simply, $source = 'Source_file_location' ...READ MORE

answered Oct 12, 2020 in PHP by anonymous
• 140 points
55 views
0 votes
1 answer

How to prevent direct access to a php include file?

Hello @kartik, Add this to the page that ...READ MORE

answered Oct 18, 2020 in PHP by Niroj
• 82,540 points
324 views
0 votes
1 answer

Uncaught ReferenceError:Karma: jQuery is not defined

Hii @kartik, You first have to load jQuery ...READ MORE

answered May 12, 2020 in JQuery by Niroj
• 82,540 points
1,301 views
0 votes
1 answer

Error:PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Hello @kartik, 8388608 bytes is 8M, the default ...READ MORE

answered Sep 17, 2020 in PHP by Niroj
• 82,540 points
2,461 views
0 votes
1 answer

How to remove all special characters from a string?

Hello @kartik, This should do what you're looking ...READ MORE

answered Sep 17, 2020 in PHP by Niroj
• 82,540 points
1,233 views
0 votes
1 answer

How to display HTML tags as plain text ?

Hello @kartik, Replace < with &lt; and& ...READ MORE

answered Sep 17, 2020 in PHP by Niroj
• 82,540 points
309 views
0 votes
1 answer

How to delete all files from a folder using PHP?

Hello @kartik, Use this: $files = glob('path/to/temp/*'); // get ...READ MORE

answered Sep 13, 2020 in PHP by Niroj
• 82,540 points
75 views
0 votes
1 answer

How to copy a file from one directory to another using PHP?

Hello @kartik, You could use the copy() function : // Will ...READ MORE

answered Sep 15, 2020 in PHP by Niroj
• 82,540 points
113 views