php - 如果文件大于给定大小,则阻止从远程源加载

标签 php domdocument filesize

假设我只想从远程服务器加载最多 10MB 的 XML 文件。

类似于

$xml_file = "http://example.com/largeXML.xml";// size= 500MB

//PRACTICAL EXAMPLE: $xml_file = "http://www.cs.washington.edu/research/xmldatasets/data/pir/psd7003.xml";// size= 683MB

 /*GOAL: Do anything that can be done to hinder this large file from being loaded by the DOMDocument without having to load the File n check*/

$dom =  new DOMDocument();

$dom->load($xml_file /*LOAD only IF the file_size is <= 10MB....else...echo 'File is too large'*/);

如何才能实现这个可能?...有什么想法或替代方案吗?或实现这一目标的最佳方法将受到高度赞赏。

我检查了PHP: Remote file size without downloading file但是当我尝试使用类似的东西时

var_dump(
    curl_get_file_size(
        "http://www.dailymotion.com/rss/user/dialhainaut/"
    )
);

我得到字符串“未知”(长度=7)

当我按照下面的建议尝试使用 get_headers 时, header 中缺少 Content-Length,因此这也无法可靠地工作。

请告知如何确定长度,并避免在超过10MB时将其发送到DOMDocument

最佳答案

好的,终于可以工作了。 header 解决方案显然不会广泛工作。在此解决方案中,我们打开一个文件句柄并逐行读取 XML,直到达到 $max_B 的阈值。如果文件太大,我们仍然需要读取它直到 10MB 标记,但它会按预期工作。如果文件小于 $max_B,则继续...

$xml_file = "http://www.dailymotion.com/rss/user/dialhainaut/";
//$xml_file = "http://www.cs.washington.edu/research/xmldatasets/data/pir/psd7003.xml";

$fh = fopen($xml_file, "r");  

if($fh){
    $file_string = '';
    $total_B = 0;
    $max_B = 10485760;
    //run through lines of the file, concatenating them into a string
    while (!feof($fh)){
        if($line = fgets($fh)){
            $total_B += strlen($line);
            if($total_B < $max_B){
                $file_string .= $line;
            } else {
                break;
            }
        }
    } 

    if($total_B < $max_B){
        echo 'File ok. Total size = '.$total_B.' bytes. Proceeding...';
        //proceed
        $dom = new DOMDocument();
        $dom->loadXML($file_string); //NOTE the method change because we're loading from a string   

    } else {
        //reject
        echo 'File too big! Max size = '.$max_B.' bytes.';  
    }

    fclose($fh);

} else {
    echo '404 file not found!';
}

关于php - 如果文件大于给定大小,则阻止从远程源加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761377/

相关文章:

php - 将 MySQL 查询的结果动态显示到 HTML 页面中

php - 无法打印_r domDocument

php - 使用 PHP 下载时文件大小是否有限制?

php - 你将如何在 php 5.4 中实现一个基本的文件上传进度条?

php - Custom Drupal 7 Field 只保存第一个字符

php - 在 PHP 中使用 Dom 对象,在某些节​​点中重新声明默认命名空间

javascript - 如何在函数上创建数组显示?

德尔福剪贴板: Read file properties of a file copied

python - 安全与文件大小

php - 从选项中选择多个选项