How to serve multiple images which reside above the www root within a single page?

半城伤御伤魂 提交于 2019-12-07 07:44:41

问题


I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.

What is the best method to achieve this?


回答1:


You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.

Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.

The contents of getimage.php are small and simple:

// Check user permissions if necessary...

// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.

// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();

In your HTML:

<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />

It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.




回答2:


If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.

ln -s /webroot/pictures /outside-of-webroot/uploads

If you're using an Apache server you could also have a look at mod_alias. I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.




回答3:


Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.

This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.

<?php
include("auth.php");
// uploadimg.php               
// By Tyler Biscoe             
// 09 Mar 2008                 
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;

if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
    {
        $error = "Error: File size must be under ". $max_kb . " kb.";
    }

if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
    {
        $error .= "Error: Invalid file type. Use gif or jpg files only.";

    }

if(!$error)
    {
        echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
        $handle = fopen($_FILES["file"]["tmp_name"],'r');
        $file_content = fread($handle,$_FILES["file"]["size"]);
        fclose($handle);
        $encoded = chunk_split(base64_encode($file_content)); 
        $id = $_POST["userid"];
        echo $_FILES["file"]["tmp_name"];
        $default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
        $default_result = mysql_query($default_exist_sql);
        $results = mysql_fetch_array($default_result);
        if(!$results["default_image"])
        {
            $insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
            mysql_query($insert_sql);

        }

        $sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
        mysql_query($sql);
    }
    else
    {
        echo "<div id='alertBox'>". $error . "</div>";
    }  
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />

    <form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method =        "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>

This next one displays the file:

<?php
// image.php                    
// By Tyler Biscoe              
// 09 Mar 2008                  
// File used to display pictures
include("connect.php");

$imgid = $_GET["id"];

$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");

$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];

?>

Then:

<img src="image.php?id=your_img_id">


来源:https://stackoverflow.com/questions/6625427/how-to-serve-multiple-images-which-reside-above-the-www-root-within-a-single-pag

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