Skip to content

Instantly share code, notes, and snippets.

@jimgwhit
Created May 26, 2020 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimgwhit/90faa6dfbbde72a9901562a5fe4f431e to your computer and use it in GitHub Desktop.
Save jimgwhit/90faa6dfbbde72a9901562a5fe4f431e to your computer and use it in GitHub Desktop.

At times on a shared host you may not be able to use a symbolic link. I sometimes just display from a folder outside of web folder:

A bare basic example, this file just name it DisplayImage.php

<?php
$basedir = '/some_folder/images'; // on hard drive
$imagedir = $_GET['dir'];
$image = $_GET['img'];

$file = $basedir.'/'.$imagedir.'/'.$image;

header('Content-Type: image/jpeg');
ob_clean();

readfile($file);
exit(0);

?> 

Note '/some_folder/images' name with your folder names.

Basic usage:

<img src="<?php echo 'http://site.com/project/DisplayImage.php?dir=imgdogs&img=' .  $row->dogpic; ?>" alt="" class="image">

Where imgdogs is a subfolder under images. Change names as needed.

@jimgwhit
Copy link
Author

And note, it's a basic example, You can enhance it by filtering allowed file types, limit size if needed, etc.

Example of file types:

$ext = array_pop(explode ('.', $file));
$allowed['gif'] = 'image/gif';
$allowed['png'] = 'image/png';
$allowed['jpg'] = 'image/jpeg';
$allowed['jpeg'] = 'image/jpeg';

if(file_exists($file) && $ext != '' && isset($allowed[strToLower($ext)])) {
    $type = $allowed[strToLower($ext)];
} else {
    $file = $fallback;
    $type = 'image/gif';
}

To get size:

$size = filesize($file);

And you can put custom headers:

header("Accept-Ranges: bytes");
header("Cache-Control: public");
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $length);
header('Content-Disposition: inline; filename="' . $image . '"');
header("Last-Modified: " . date('r', filemtime($file)));

Above are just examples.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment