Kaye
Kaye

Reputation: 21

file_exist displaying image path instead of .jpg

I got a code here using file_exist. it checks if a .txt and a .jpg file exist in the directory. and then displays those in an alert box. it works well for the .txt but not in the .jpg. it displays the image source instead of the image itself. what am i doing wrong here? can you give me some help regarding this? thanks a lot in advance! here's my code.

search.php

<?php
    class Model
    {
        public function readexisting()
        {
            if(
                file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.txt") 
                && 
                file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.jpg")
            )
            {  
                $myPic     =   "/Alchemy/ajax/events/folder-01/event-01.jpg";
                echo $myPic;

                $myFile    =   ($_SERVER['DOCUMENT_ROOT'] . "/Alchemy/events/folder-01/event-01.txt");
                $fh        =   fopen($myFile, 'r');
                $theData   =   fread($fh, filesize($myFile));
                fclose($fh);

                echo $theData ;
            }
            else
            {
                echo "The file $myFile does not exist";
            }
        }
    }
?>

Upvotes: 0

Views: 120

Answers (3)

KodeFor.Me
KodeFor.Me

Reputation: 13511

Remove the echo $myPic; and then add this before the echo $theData;

header("Content-type: image/jpeg");

In general you have to inform the browser for the data type you are sending. Also note, that the header() command should be located before you start sending any data to the browser.

Also, if you will manipulate multiple file types (ie: png, jpg, gif) you should change the MIME type in the deader command to map the appropriate file type.

header("Content-type: image/gif");   // For gif images
header("Content-type: image/png");   // For png images
header("Content-type: image/jpeg");   // For jpg images

Upvotes: 1

user771071
user771071

Reputation:

For an image (or anything else for that matter) you'll need to send a content-type header, otherwise it will not be shown. You can do this by getting the mime-type first here and then adding the header by doing this before the echo.

header("Content-Type: ". $mimetype);
echo $theData;

Where $mimetype is the mime type retrieved.

Upvotes: 0

Pupil
Pupil

Reputation: 23948

You need to apply header() and tell PHP that you are rendering an image.

header("Content-type: image/jpeg");

OR depending upon which file you are rendering, apply proper headers.

Upvotes: 4

Related Questions