Displaying an image with path stored in Database in a html template file with php
so my problem is that i have images storesd to a location on my server (not the web root, for security purposes) and i have the path to these images stored in the database. i ues php along with pear's html_template_it to display my pages. The only successful method of displaying the images has ben to modify the headers using
header("Content-type:image/type")
header("Content-Disposition:inline")
echo "<img src=readfile($image) />";
my problem is that this disrupts the templ开发者_StackOverflow社区ate and whilst i get the image display, the template is gone. Can anyone advise on the best way to bypass this?
The proper way to do it would be to have something like:
<img src="image.php?imageID=XYZ" />
in your template, where XYZ is the image's primary key in the database. Then you'd have the image.php script:
<?php
$id = $_GET['imageID'];
$sql = "SELECT path FROM images WHERE id='" . mysql_real_escape_string($id) . "'";
... run query, fetch path, etc...
header('Content-type: image/whatever');
readfile($path);
If you output an image/whatever
content-type as you are in your code snippet, then you can't wrap the image in some HTML, as the browser will interpret EVERYTHING your script sends as an image, and see a corrupted image - no image format on the planet has <img ....
as its first few bytes.
if You have image path stored in db, get information from there and assign it to variable
//some php code (getting image)
$image = 'ImagePath/ImageName.jpg';
to output image in html just print variable in src attribute without any headers html code
<img src=" <?=$image?>"/>
You need to have a separate img.php
file with this code in it:
header( "Content-type:image/type" );
echo file_get_contents( $imageFilePath );
then put this <img>
tag wherever you want to show the image:
<img src="img.php" />
The best way to display the images is as follows:
$query = "SELECT imagecolumnname FROM tablename";
$result = msql_query($result); if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result))
{
$image_path = $row["image_path"];
}
}
$abs_path = $_SERVER["DOCUMENT_ROOT"]."/path_to_your_app/".$image_path;
<img src="<?php echo $abs_path; ?>" alt="" title="" />
I hope this helps.
Regards J
精彩评论