check if file exist in folder

ZeroSuf3r picture ZeroSuf3r · Jan 8, 2012 · Viewed 20.2k times · Source

My script:

$secret = check_input($_GET['secret']);
if(isset($_POST['register'])) {
    if (isset($secret) || !empty($secret)) {
        if (file_exists(ROOT . '/intl/codes/' . $secret)) {
            unlink(ROOT . '/intl/codes/' . $secret);
            $trusted = 'yes';
        } else {
            $trusted = 'no';
        }
    }
//$_POST['register'] register details...
}
  1. Is there another way to do it (simplier, etc.)?
  2. If $secret doesn't exist in the /codes/ folder, it produces Warning: unlink Is a directory How to get rid of that?
  3. Why $trusted always gives yes even if the file doesn't exist ?

Answer

Bailey Parker picture Bailey Parker · Jan 8, 2012

To delete a directory, you should be using rmdir() instead of unlink().

$secret = check_input($_GET['secret']);
if(isset($_POST['register'])) {
    if (!empty($secret)) {
        if(file_exists(ROOT . '/intl/codes/' . $secret)) {
            rmdir(ROOT . '/intl/codes/' . $secret);
            $trusted = 'yes';
        } else {
            $trusted = 'no';
        }
    }
    //$_POST['register'] register details...
}

Although, there is a serious security risk here! If your check_input() does not properly sanitize $secret, you could rmdir('/intl/codes/../') which is the same as deleting /intl/. Try something like this:

$allowed = ROOT. '/intl/codes/';
$path = realpath($allowed . check_input($_GET['secret']));

if(strpos($path, $allowed) === 0) {  //Check that $path is within allowed directory
    if(is_dir($path)) {
        rmdir($path);
    } else if(file_exists($path)) {
        unlink($path);
    } else {
        echo "File/folder not found";
    }
} else {
    echo "Untrusted user tried to delete outside of allowed directory";
}