Temporary store image in php only while displaying on web page

点点圈 提交于 2019-12-24 07:26:35

问题


I want to fetch images from other site and display on my site. I want to store that images in my side temporary only at time of showing on page , so that user think images are coming from my site.is it possible? How? Thanks in advance.

ex:- imagine there are some graphs generated in a server (some network monitoring graphs like smokeping )and those graphs are stored in a folder as .png format.

ex:- imagine_this_url_has_a_graph (but this is just a page)

so that user want to show those graphs in another web site.


回答1:


A simple caching system would do this. Given an HTML file like:

<body>
 <img src="imagesource.php?file=1" />
</body>

You could create your image data source (imagesource.php) like:

<?php
$files = array(
   'http://somesite.com/image_to_cache.gif',
   'http://somesite.com/image_to_cache2.gif'
);

if(!isset($_REQUEST['file']) || !isset($files[$_REQUEST['file']])) {
   header('HTTP/1.0 404 Not Found');
   exit;
}

// do we already have the cached file?
$requested_file = $files[$_REQUEST['file']];
$cache_dir = '/tmp/cached_images';
$cache_file = md5($requested_file);
$cache_path = $cache_dir . '/' . $cache_file;

header('Content-Type: image/gif');

if(file_exists($cache_path)) {
   readfile($cache_path);
   exit;
}

//need to create the cache.
$data = file_get_contents($requested_file);
file_put_contents($cache_path, $data);

echo $data;

This would cache the remote images locally if they haven't already been downloaded, and output them to the browser when requested.




回答2:


When the request for an image is made against your server, simply use fopen() to open the remote image, and fpassthru() to pass it through.




回答3:


use fileread() instead of fopen() if you want to output the image as it yours, otherwise, you will get an error.



来源:https://stackoverflow.com/questions/2069959/temporary-store-image-in-php-only-while-displaying-on-web-page

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