Displaying an image with path stored in Database in a html template file with php

放肆的年华 提交于 2019-12-12 01:48:32

问题


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 template and whilst i get the image display, the template is gone. Can anyone advise on the best way to bypass this?


回答1:


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.




回答2:


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?>"/>



回答3:


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" />



回答4:


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



来源:https://stackoverflow.com/questions/7363102/displaying-an-image-with-path-stored-in-database-in-a-html-template-file-with-ph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!