How can I load an image from a local directory in PHP?

5.8k Views Asked by At

My setup (or path) is as follows:

 |Home
    |ftpUsername
        |assets
           |images.png
           |script.php
        |mydomain.com
           |index.php

index.php is located in mydomain.com, which includes script.php in /home/ftpUsername/assets without a problem.

script.php is included in index.php using the include() function. My question is, how can I get PHP to load the images (png format) which are in /home/ftpUsername/assets/ through script.php?

In other words: How can I load /home/ftpUsername/assets/myimage.png in script.php?

Note: /home/ftpUsername/mydomain.com/ is a live directory (is online attached to a domain) and home/ftpUsername/assets/ is not (local directory on the server).

I have tried loading it directly from path using img src="/home/ftpUsername/assets/myimage.png" to no avail, with and without a backslash.

1

There are 1 best solutions below

0
On BEST ANSWER

From script.php, you need to read, then output the PNG image (passing the right mimetype, so it will be recognized as an image).

You may use readfile or even file_get_contents to read filestream, like this: (I'm assuming you'll pass the image name by $_GET 'image'. /script.php?image=imagename.png and using a no_image.png as a fallback.

header("Content-Type:image/png"); //passing the mimetype

$image = '/home/ftpUsername/assets/' . $_GET['image']; 

if(is_file($image) ||  is_file($image = "/home/ftpUsername/assets/no_image.png"))
    readfile($image);

This way, you may link your script.png directly in your img src, just like this:

<img src="script.php?image=imagename.png" alt="" />

Your script.php will act just like an image.