I'm trying to scan the files in a directory using a php request. This is my code right now:
$.ajax({
type: "POST",
url: "scandir.php",
data: { dirname: "./test" },
success: function( data ) {
console.log( data );
}
error: function() {
console.log( "error" );
}
});
scandir.php:
<?php
$dirname = $_POST[ "dirname" ];
$files = scandir( $dirname ) or die("Unable to scan directory " . $dirname );
foreach ( $files as $filename ) {
echo $filename . "
";
}
?>
Problem is, the request always returns successfully, even if the directory "dirname" doesn't exist (it returns the text of the php directory-not-found messages). How do I make it return with an error when the directory is not found?
if(!empty($_POST["dirname"])) {
$dirname = $_POST["dirname"];
if(!is_dir($dirname)) {
header('HTTP/1.0 404 Not Found');
exit;
}
foreach(scandir($dirname) as $filename) {
echo $filename . "
";
}
}
As you can see here, the error
entry is only for http errors like timeout or 404 not found. If you want to check if the php script failed internally, you either can set a header using php's method header
or you check in the success function whether the php script returned an error. Hope that helps.