0

this is my first time writing code in PHP. I am trying to write a simple function that opens a given file. It works fine with .txt files, but when I try to open a .jpg image, it opens it as a long series of characters. This is the PHP code:

<?php
$new = fopen("note.txt", "r");
echo fread($new, filesize("note.txt"));
fclose($new);
?>

This is the code that works and displays the .txt file. However, when I try to open an image -

<?php
$new = fopen("Salamander.jpg", "r");
echo fread($new, filesize("Salamander.jpg"));
header("Content-Type: image/jpeg");
fclose($new);
?>

-I get a long series of question marks, numbers, letters and other characters (near the beginning is the photograph's EXIF data). I guess I have to specify the file's contents in some other way than the way I've done it, but I don't know how. Any help?

P.S. My server in on the computer I am working on.

peter_s
  • 55
  • 2
  • 10
  • 1
    What you expect to get when you read file of image? Yes, it's some data, that can be opened with any plain text editor. And headers must be set before any output from script – Justinas Aug 28 '14 at 11:52
  • what do you want to achieve by opening the file ? – Dwza Aug 28 '14 at 11:56
  • I want to view it in a browser, the image itself, not its data in text format. – peter_s Aug 28 '14 at 11:58

1 Answers1

1

Try to define the header() before the echo. How ever when u open a file from server side always open it in text format.

  • I did it, now it shows an icon of a broken image, the one that's displayed when an image can't load. – peter_s Aug 28 '14 at 12:02