PHP - security when accessing files outside the web root

I have a php file called gallery.php, which is a page for a specific image gallery. For security, user images are stored outside the root website.

To get the appropriate files for each user, I use the getimage.php file, which serves the images from their location. In general, the directory structure looks like this:

  • UserImages
    • User1
      • User1 Image List
    • User 2
      • User2 image list
  • public_html
    • gallery.php
    • getimage.php

getimage.php is written as follows:

$imgString = realpath('/UserImages/' . $_SESSION['username'] . '/' . $_GET['img']);
if (!startsWith($imgString, '/UserImages/' . $_SESSION['username'] . '/')
    || !(endsWith(strtolower($imgString), '.jpg') || endsWith(strtolower($imgString), '.jpeg')))
{
    header('HTTP/1.0 403 Forbidden');
    die();
}

$img = file_get_contents($imgString);
header("Content-type: image/jpeg");
echo($img);
exit();

$_GET ['img'], , , ( ). , , realpath, , , script.

, getimage.php webroot , , , ( gallery.php, img ).

, getimage.php oustide public_html, , gallery.php. getimage.php :

<img src=getimage.php?img=IMG_FILENAME.jpg />

getimage.php , - public_html.

, : , getimage.php?

+4
3
+1

- $_GET ['img'] , .

, , , , , .

...

$imgString = realpath('/UserImages/' . $_SESSION['username'] . '/' . preg_replace("/[^a-zA-Z0-9._-]/", "", $_GET['img']));

, $_GET ['img'] If .

if(preg_replace("/[^a-zA-Z0-9._-]/", "", $_GET['img']) != $_GET['img']){
    // Throw an error
    exit();
}

PS: , . .

+1

- URL- $_GET ['img'], .

-, $_GET ['img'] URL- , _get_contents .

-, -, URL- -:

<img src="http://www.yourwebsite.com/getimage.php?img=[external_image_url]">

1) , . , URL-:

$imageID = $_GET['image'];
.... your sql query here to retrieve the image....
$img = file_get_contents($imgString);

2) , $_GET ['image'] , :

if( !preg_match("/^[0-9]+$/", $_GET['image']) )
{
    header('HTTP/1.1 404 Not Found');
    exit();    
}

3) SQL :

$sql = "SELECT image_path from images WHERE id = ?";

4) , getimage.php root, Apache Alias ​​ . Apache Virtualhost :

Alias /getimage.php /path/to/getimage.php

5) 404 , 403, , .

+1

Source: https://habr.com/ru/post/1568694/


All Articles