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 in PHP by kartik
• 31,650 points
38 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 by Niroj
• 68,520 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 in PHP by Niroj
• 68,520 points
54 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 in PHP by anonymous
• 140 points
31 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 in PHP by Niroj
• 68,520 points
107 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 in JQuery by Niroj
• 68,520 points
861 views
0 votes
1 answer
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 in PHP by Niroj
• 68,520 points
77 views
0 votes
1 answer

How to display HTML tags as plain text ?

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

answered Sep 17 in PHP by Niroj
• 68,520 points
93 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 in PHP by Niroj
• 68,520 points
40 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 in PHP by Niroj
• 68,520 points
32 views