dongnao2048 2017-06-11 04:08
浏览 34
已采纳

可以使用此方法下载PHP脚本。 预防?

I am writing my app with this method. I want a private directory where cant be accesible via URL. So i have a htaccess where successfully redirect when you visit the photos folder. I have my files with this structure.

myApp | []photos | .htaccess | loadthephoto.php | home.php

when you visit the home.php, at one line i serve the image through loadthephoto.php. The code inside there is

    $resultLoad = getUserDetails($db,"photo","user_details",$_SESSION['theUserskey']);

    $photosName = $resultLoad['photo'];
    $file = 'photos/'.$photosName;
    $temp = explode(".", $photosName);
    $type = 'image/'.end($temp);

    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit();

It works fine. The problem is that it produce a html like this <img src="loadthephoto.php"> , and if you visit the url/loadthephoto.php make this downloadable. I do not want this.

First, is this way correct for serving "private" images ? If it can be implemented with this way, how can i make the loadthephoto.php for not be downloadable ?

Another way is to make the photos folder be accesible from url and producing the images with the classic URLs way.

  • 写回答

1条回答 默认 最新

  • duanjizi9443 2017-06-11 04:16
    关注

    You should check the file mime type and/or extension before serving it. Checking an extension is not recommended as anyone could upload an image with a txt extension.

    You're halfway there with your code but you're making a mime type from an extension which is also unwise as image/jpg isn't a proper mime type it should be image/jpeg.

    $resultLoad = getUserDetails($db,"photo","user_details",$_SESSION['theUserskey']);
    
    $photosName = $resultLoad['photo'];
    $file = 'photos/' . $photosName;
    
    // Check mime type
    $mime = mime_content_type($file);
    
    $validMimes = ['image/jpeg', 'image/gif', 'image/png', 'image/svg+xml'];
    
    // Refuse to serve invalid files
    if (!in_array($mime, $validMimes)) {
        die('Invalid file type');
    }
    
    header('Content-Type:' . $mime);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!