Php unlink. does not return an error message and does not delete my file

I am just trying to delete a file using PHP unlink. I found an answer here that told me that this is the best way to do this, and I implemented it. Here is the code I'm using.

$log_path = realpath($log_file); if (is_readable($log_path)){ print file_exists($log_path); $deleted = unlink($log_path); print "Deleted:".$deleted; print "Exists:".file_exists($log_path); } 

It just prints 1Deleted:exists:1 . I also tried adding to print_r(error_get_last()); under unlink, but that also returned nothing. All files in the chmod 777 * directory, and no other file handlers open ..... what the hell ...

+4
source share
6 answers

The code you use is unnecessarily cumbersome. A simple unlink call should do the trick:

 unlink( $log_file ); 

But let's find out what is going wrong. The file exists because you enter a loop in which print instructions are executed. It seems that calling unlink returns false, because the output is "11", not "111".

So, my gut says this should be a file permissions issue. Are you sure the web user has permission to delete the file? Can you show us permissions to access the folder, for example by running ls -la on the command line and pasting the output?

+3
source

unlink returns either true or false . If you try to print false ( print $deleted; ), this will print an empty line.

Try this instead:

 print $deleted ? "The file was deleted" : "The file was not deleted"; 
+3
source

I think you need to check if the file is $ log_path . Using:

 if( is_file( $log_path ) AND is_readable( $log_path ) ) 

Also add the following line to start your script to show all errors and warnings:

 ini_set( 'error_reporting', E_ALL ); 
+3
source

I do not know this problem, but you should check if the file can be written, but not readable:

 <?php $log_file = "/tmp/test.log"; $log_path = realpath($log_file); echo "Testing: ". $log_path."\n"; if (is_writable($log_path)) { echo "exists? "; echo (file_exists($log_path))?"yes\n":"no\n"; $deleted = unlink($log_path); echo "deleted? "; echo ($deleted)?"yes\n":"no\n"; echo "exists? "; echo (file_exists($log_path))?"yes\n":"no\n"; } else { echo "file unwritable\n"; } 

This code works fine for me (yes, it is also dirty;)).

+2
source

file_exists caches the result of the operation, you must call clearstatcache () before the second call

+1
source

Not that your files should be 0777. It is also necessary that your directory can be accessed. What is the mod of your catalog?

Next: print $deleted; apparently prints false, which displays as nothing. Try the following: echo $deleted ? 1 : 0; echo $deleted ? 1 : 0;

0
source

All Articles