JavaScript or Query library to work with paths/URIs [closed]
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this questionCould someone suggest a library to work with paths like : /a/b/c.jpg
or http://asdf/sdf/fd.jpg
I need get directory or just filename string, similar to what the following PHP filesystem functons offers:
dirname
basename
Have a look at the parseURI function of Flagrant Badassery's blog. It can parse any well formed URIs.
Using jQuery or any Javascript you cannot list a directory and the files within it for security reasons.
You can get a filename using regex by using:
var path = "/a/b/c.jpg",
filename = path.replace(/^.*(\\|\/|\:)/, '');
To get the extension and basename of a file you can use (Note: you will need to use this with the above code as well):
var basename = filename.substr(0, filename.lastIndexOf( "." )),
extension = filename.substr(filename.lastIndexOf( "." )+1, filename.length);
If you really need to get a directories list, you can get it with PHP and return it to the client with an AJAX request. This is definitely not recommended because it could very easily be abused to list secure or private files. The only instance I would recommend this is if the directory you are listing will definitely only ever contain files you know are safe to display such as a directory of images that have been uploaded. To do this you would do:
PHP file in directory (index.php)
<?
// Set JSON headings
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// The directory to list
$this_directory = opendir(".");
// Loop through each file
while($file_name = readdir($this_directory)) {
// Add the files to an array
if($file_name != "." && $file_name != "..") $return_array[] = $file_name;
}
// Return the array as JSON
echo json_encode($return_array);
// Close the directory
closedir($this_directory);
?>
Javascript
// Get the JSON from the PHP file
$.getJSON("img/", function(data){
// Loop through each file
for(var i = 0, j = data.length; i < j; i++) {
// Do whatever you want with the filename
console.log(data[i]);
}
});
Again, only do this on a directory that you know will contain files that are OK to display to the world. NEVER pass in to the PHP file an option to specify which directory to list. For example, don't allow the PHP to take an input such as "/home/site.com/sensitive_data/" because it will allow an attacker to arbitrarily list any directory on your server.
精彩评论