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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)