Search code examples
phpimageloadingusing

Displaying Lots of Images Using One PHP File


I hope someone will help me with this. Namely, I need a PHP code which will display images in a HTML/PHP page based on their id. For example: the file ShowPicture.php, and the code in it something like this:

PictureID = "MyPicture1"
MyPicture1_Source = "/Pictures/Picture1.jpg";
PictureID = "MyPicture2"
MyPicture2_Source = "/Pictures/Picture2.png";
PictureID = "MyPicture3"
MyPicture3_Source = "/Pictures/Picture3.gif";
PictureID = "MyPicture4"
MyPicture4_Source = "/Pictures/Picture4.bmp";

Example of usage on the pages:

HTML/PHP PAGE 1: <IMG src="ShowPicture.php?id=MyPicture4">
HTML/PHP PAGE 4: <IMG src="ShowPicture.php?id=MyPicture2">
HTML/PHP PAGE 2: <IMG src="ShowPicture.php?id=MyPicture3">
HTML/PHP PAGE 3: <IMG src="ShowPicture.php?id=MyPicture1">

I don't currently use any code since I didn't find good enough which will suit this particular need of mine. The file should be something like Facebook's rsrc.php file, which fetches all the graphics for the site whilst hiding the real source path.

EDIT: I do not need Sessions nor Cookies, I want the pictures to be displayed permanently on pages through PHP, even after the user refreshes/reloads the pages.

EDIT 2: No (My)SQL. The PHP file itself and alone must be sort of a database for storing and displaying images.


Solution

  • I wanted you to put efford in it yourself. Stack Overflow is ment to help you when you have issues with your code. It's not ment for people that just want some programmer to do all the work for them. Anyway, I've taken a few minutes to do it for you now, so here it is:

    <?php
    
    $id = $_GET["id"];
    
    switch($id){
        case "MyPicture1":
            $file = "img/img1.jpg";
            break;
        case "MyPicture2":
            $file = "img/img2.jpg";
            break;
        case "MyPicture3":
            $file = "img/img3.jpg";
            break;
        case "MyPicture4":
            $file = "img/img4.jpg";
            break;
        default:
            echo "Invalid ID given!";
            exit;
    }
    
    if(file_exists($file)){
        $size = getimagesize($file);
        $fp = fopen($file, 'rb');
    
        if($size and $fp){
            header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
            header('Content-Type: '.$size['mime']);
            header('Content-Length: '.filesize($file));
    
            fpassthru($fp);
        }
    
        exit;
    } else {
        echo "File not found!";
    }
    
    ?>
    

    You can modify it any further yourself.