我使用头请求如下,以检查是否存在一个给定的文件
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
但是,现在我将文件放在一个文件夹中,该文件夹受。htaccess的限制,通过以下规则
deny from all
但是现在看起来像jquery总是返回404 Not Found,因为试图访问一个受限制的文件夹。
我不能放弃限制这个文件夹,因为文件是由用户上传的,我不能确定它们是安全的。
如何检查该文件夹中是否存在文件?
使用php查找文件,并通过jQuery处理…
jQuery$.ajax({
url: "somephpfile.php?file=filename.txt",
success: function(file_exists) {
if(file_exists) {
alert("File Exists");
}
}
});
php <?php
if(file_exists($_GET["file"])) {
echo "1";
} else {
echo "0";
}
确保你在php逻辑中有一些安全,以确保它不能被用来攻击你的服务器!
你不能访问。htaccess后面的文件,除非用户已经登录并有权访问这些文件。你可以创建一个以文件名为参数的公共页面(php),然后在服务器端检查该文件是否存在,并返回一个JSON对象或true/false..像这样:
$.ajax({
url:'http://www.example.com/checkfile.php?locn=somefile.ext',
error: function()
{
//this happens when jquery cant contact your php script or your server threw an error... 404's and 500's... just show a generic "cant connect to server" or something.
},
success: function(data)
{
//this means you got data back from the server as a 200 response.
//it does not say whether or not the file exists.
//to do that, you must examine the JSON response. perhaps like this:
if (data == true)
{
//the file exists
}
else
{
//the file does not exist
}
}
});
你的checkfile.php可能看起来像这样(伪代码):
$fileloc = $_GET["locn"];
if (file_exists($locn))
{
echo "true";
}
else
{
echo "false";
}