V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
YAFEIML
V2EX  ›  PHP

[PHP]这样会被黑吗?求改进

  •  
  •   YAFEIML · 2015-05-15 11:33:40 +08:00 · 3195 次点击
    这是一个创建于 3270 天前的主题,其中的信息可能已经有所发展或是发生改变。
    因为有时候拉图片拉的不完整,所以判断下MD5

    <?php
    $target = $_GET['url'];
    $filename = basename($target);
    $tupian = './cache/'.$filename;
    $kzm = explode(".",$filename);
    $tupian_md5 = $tupian.'.txt';

    if (file_exists($tupian_md5) ) {

    if (count(file($tupian_md5)) == '1')
    {
    $md5file = md5_file($tupian);
    file_put_contents($tupian_md5,PHP_EOL.$md5file,FILE_APPEND);
    $content = file_get_contents($tupian);
    }

    else if (count(file($tupian_md5)) == '2' && substr_count(file_get_contents($tupian_md5),mb_substr(file_get_contents($tupian_md5),0,32)) == 2)

    {
    $content = file_get_contents($tupian);
    }

    else if (count(file($tupian_md5)) == '2' && substr_count(file_get_contents($tupian_md5),mb_substr(file_get_contents($tupian_md5),0,32)) != 2)

    {
    @unlink($tupian);
    @unlink($tupian_md5);
    $content = file_get_contents($target);
    }

    else
    {
    $content = file_get_contents($tupian);
    }
    }
    else {
    $md5file_t = md5_file($target);
    file_put_contents($tupian_md5,$md5file_t);

    $content = file_get_contents($target);

    $fp = fopen($tupian, 'w+');
    fwrite($fp, $content);
    fclose($fp);
    }

    header('Content-Type: image/'.end($kzm).'');
    echo $content;
    ?>
    8 条回复    2015-05-17 01:54:07 +08:00
    800126
        1
    800126  
       2015-05-15 11:48:34 +08:00
    你加一句“PHP才是最好的语言”,立马就有人回复你了。
    ichou
        2
    ichou  
       2015-05-15 12:11:23 +08:00
    代码贴到 gist 上再发上来会比较好
    RIcter
        3
    RIcter  
       2015-05-15 12:38:50 +08:00
    会有任意文件读取吧?
    p1n3
        4
    p1n3  
       2015-05-15 12:53:53 +08:00
    xx.php?url=file:///etc/passwd
    extreme
        5
    extreme  
       2015-05-15 13:17:29 +08:00
    用正则表达式对$_GET['url']以及$filename匹配下比较好,例如不允许有'../'之类的。
    例如:preg_match('/^[a-zA-Z0-9\-]+\.(jpg|png|gif)$/', $_GET['url'])
    就只允许文件名有字母,数字和'-',且扩展名仅能为jpg或png或gif。
    对这个php文件设置openbasedir,甚至是chroot,更安全。
    phithon
        6
    phithon  
       2015-05-15 15:27:53 +08:00
    代码不加高亮我就不仔细看了,感觉会出任意文件读取、文件删除漏洞。4楼真相。
    建议:
    参数是url的话,正则判断 |^https?://.*\.(jpg|png|gif)$|is是否非法。
    本地文件名的话,用$name = basename($name);处理一遍,再判断一遍后缀是否是图片就差不多了。
    denghongcai
        7
    denghongcai  
       2015-05-15 16:14:06 +08:00
    4楼的并没有任意文件读取,basename也不是个这种情况都照顾不到的函数的
    ryd994
        8
    ryd994  
       2015-05-17 01:54:07 +08:00 via Android
    chroot 卍解
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3026 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 13:46 · PVG 21:46 · LAX 06:46 · JFK 09:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.