Hamed Azimi Hamed Azimi - 2 years ago 137
PHP Question

Delete a file using php

I use this code to show a list of files in user's profile page:

public static function getUserProfilemusic() {
$path = Xenforo_Application::getInstance()->getRootDir() . '/styles/default/dadparvar/profilemusic/songs/';
$directoryList = scanDir($path.'/'.func_get_arg(1));
$string = '';
foreach ($directoryList as &$listEntry) {
$songURL = /*$path*/ '/styles/default/dadparvar/profilemusic/songs/' . func_get_arg(1) . '/'. $listEntry;
$string .= "<a href='$songURL' class='Tooltip' title='Click to Download $listEntry'> $listEntry </a>
| <a href='#' class='Tooltip' title='Click to Remove $listEntry' target='_blank'> X </a>
return $string;

How can I set, when user clicked on X the file be deleted?

Any opinion will be appreciated.

Answer Source

That depends a bit on your structure but the easiest way is to send the filename to a new script for example deletefile.php in that file you first check if you're logged in. Then you can check if the file exist and make an unlink on that file.

if(is_file($pathtofile."/".$filename)) {

Be patient that you check the input filename that you don't have an security hole in your application. To prevent some problems you should use the complete path the file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download