i know that
$localfile = $_FILES['media']['tmp_name'];
will get the image given that the POST method was used. I am trying to read an image which is in the same directory as my code. How do i read it and assign it to a variable like the one above?
The code you posted will not read the image data, but rather its filename. If you need to retrieve an image in the same directory, you can retrieve its contents with file_get_contents()
, which can be used to directly output it to the browser:
$im = file_get_contents("./image.jpeg");
header("Content-type: image/jpeg");
echo $im;
Otherwise, you can use the GD library to read in the image data for further image processing:
$im = imagecreatefromjpeg("./image.jpeg");
if ($im) {
// do other stuff...
// Output the result
header("Content-type: image/jpeg");
imagejpeg($im);
}
Finally, if you don't know the filename of the image you need (though if it's in the same location as your code, you should), you can use a glob()
to find all the jpegs, for example:
$jpegs = glob("./*.jpg");
foreach ($jpegs as $jpg) {
// print the filename
echo $jpg;
}
name
points to the files original name as uploaded by the user. tmp_name
is a filename assigned by PHP in temporary space, which points to the actual file data. It only exists until the script terminates, then tmp_name
is no longer valid - Michael Berkowski 2012-04-05 18:56
$filename = "./image.jpg";
if you don' tknow the filename, retrieve it with glob()
Michael Berkowski 2012-04-05 19:08
file_get_contents()
echoing it out will output the actual binary file data - Michael Berkowski 2012-04-05 19:22
If you want to read an image and then render it as an image
$image="path-to-your-image"; //this can also be a url
$filename = basename($image);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpeg"; break;
default:
}
header('Content-type: ' . $ctype);
$image = file_get_contents($image);
echo $image;
If your path is a url, and it is using https:// protocol then you might want to change the protocol to http