Sanitize file path in PHP

后端 未结 7 1074
夕颜
夕颜 2020-12-01 11:00

Greetings, I\'m hoping to make my tiny program secure so that potential malicious users cannot view sensitive files on the server.

    $path = \"/home/gsmcm         


        
7条回答
  •  半阙折子戏
    2020-12-01 11:24

    Solution by the OP:

    $baseDir = "/home/gsmcms/public_html/central/app/webroot/"; 
    $path = realpath($baseDir . $_GET['file']); 
    
    // if baseDir isn't at the front 0==strpos, most likely hacking attempt 
    if(strpos($path, $baseDir) !== 0 || strpos($path, $baseDir) === false) { 
       die('Invalid Path'); 
    } elseif(file_exists($path)) { 
       echo file_get_contents($path); 
    } else { 
       header('HTTP/1.1 404 Not Found'); 
       echo "The requested file could not be found"; 
    } 
    

提交回复
热议问题