i am trying to learn how to cache an image that is created in PHP, this current piece of PHP wil cache text to a file, but i want to get it to cache an image called 'my_barcode.png' to the cache folder, any help would be greatly appreciated.
<?php
$h = opendir('data/');
$chace = 'cache/test.cache.php';
if(file_exists($chace))
{
include($chace);
}
else
{
$result = NULL;
while (($file = readdir($h)) !=false)
{
$result .= $file. '<br />';
}
closedir($h);
echo $result;
$fs = fopen($chace, 'w+');
fwrite($fs, $result);
fclose($fs);
}
?>
If the purpose is to serve cached files, PHP should create them when not existing but the http server (such as Apache) should be serving the static files if they exist. Implementing cache the way you did takes too many resources as PHP is still called.
Related
I want to open a server stored html report file on a client machine.
I want to bring back a list of all the saved reports in that folder (scandir).
This way the user can click on any of the crated reports to open them.
So id you click on a report to open it, you will need the location where the report can be opend from
This is my dilemma. Im not sure how to get a decent ip, port and folder location that the client can understand
Here bellow is what Ive been experimenting with.
Using this wont work obviously:
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
So I though I might try this instead.
$host= gethostname();
$ip = gethostbyname($host);
$ip = $ip.':'.$_SERVER['SERVER_PORT'];
$path = $ip."/reports/saved_reports/";
$files = scandir($path);
after the above code I loop through each file and generate a array with the name, date created and path. This is sent back to generate a list of reports in a table that the user can interact with. ( open, delete, edit)
But this fails aswell.
So im officially clueless on how to approach this.
PS. Im adding react.js as a tag, because that is my front-end and might be useful to know.
Your question may be partially answered here: https://stackoverflow.com/a/11970479/2781096
Get the file names from the specified path and hit curl or get_text() function again to save the files.
function get_text($filename) {
$fp_load = fopen("$filename", "rb");
if ( $fp_load ) {
while ( !feof($fp_load) ) {
$content .= fgets($fp_load, 8192);
}
fclose($fp_load);
return $content;
}
}
$matches = array();
// This will give you names of all the files available on the specified path.
preg_match_all("/(a href\=\")([^\?\"]*)(\")/i", get_text($ip."/reports/saved_reports/"), $matches);
foreach($matches[2] as $match) {
echo $match . '<br>';
// Again hit a cURL to download each of the reports.
}
Get list of reports:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
$files = scandir($path);
foreach($files as $file){
if($file !== '.' && $file != '..'){
echo "<a href='show-report.php?name=".$file. "'>$file</a><br/>";
}
}
?>
and write second php file for showing html reports, which receives file name as GET param and echoes content of given html report.
show-report.php
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
if(isset($_GET['name'])){
$name = $_GET['name'];
echo file_get_contents($path.$name);
}
I'm using the getID3 library to get the details of a remote video file. I'm trying to read a portion of the file to get the details of the file, however some videos don't have the full details at the start.
For these videos, I'm trying to download the full video, and then extract the relevant information. However, even after the video has downloaded completely, getID3->analyze($filename), returns the same erroneous file info.
But when I copy the video, and then run the function analyze($filename.'copied.mp4') on copied video, it returns the correct info even though the file contents are same. Perhaps getID3 isn't loading the video again, however, how can I fix this issue without copying the video.
Please find the code below.
if ($fp_remote = fopen($remotefilename, 'r')) {
echo 'conn opened';
$localtempfilename = tempnam('/home/xerox/abc', 'whateva').'.mp4';
if ($fp_local = fopen($localtempfilename, 'wb')) {
$count = 0;
$countExpiry = 8;
while ($buffer = fread($fp_remote, 8192)) {
$count++;
fwrite($fp_local, $buffer);
if ($count >= $countExpiry) {
fflush($fp_local);
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($localtempfilename);
if ($ThisFileInfo["error"]){
print "problem encouterd";
$countExpiry += 1000;
} else {
break;}
}
}
fclose($fp_local);
$getID31 = new getID3;
copy ( $localtempfilename, $localtempfilename.'_copied.mp4' );
$ThisFileInfoz = $getID31->analyze($localtempfilename.'_copied.mp4');
// Delete temporary file
unlink($localtempfilename);
fclose($fp_remote);
var_dump($ThisFileInfoz);
}
}
A call to clearstatcache solved the problem for me,
since repeated calls to things like filesize will be cached by the
filesystem and getID3 won't read beyond end-of-file.
source: James Heinrich, developer of getID3.
I'm trying to make a upload class with PHP. so this is my first PHP class:
//Create Class
class Upload{
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
if(copy($Content, '/test/sdfsdfd.jpg')){
return "UPLOADED";
}else{
return "ERROR";
}
}
}
and usage:
$Upload = new Upload();
echo $Upload->Remote('https://www.gstatic.com/webp/gallery/4.sm.jpg');
problem is, this class is not working. where is the problem? I'm new with PHP classes and trying to learn it.
thank you.
copy expects filesystem paths, e.g.
copy('/path/to/source', '/path/to/destination');
You're passing in the literal image you fetched, so it's going to be
copy('massive pile of binary garbage that will be treated as a filename', '/path/to/destination');
You want
file_put_contents('/test/sdfsdfg.jpg', $Content);
instead.
PHP's copy() function is used for copying files that you have permission to copy.
Since you're getting the contents of the file first, you could use fwrite().
<?php
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
// Create the file
if (!$fp = fopen('img.png', 'w')) {
echo "Failed to create image file.";
}
// Add the contents
if (fwrite($fp, $Content) === false) {
echo "Failed to write image file contents.";
}
fclose($fp);
}
Since you want to download a image, you could also use the imagejpeg-method of php to ensure you do not end up with any corrupted file format afterwards (http://de2.php.net/manual/en/function.imagejpeg.php):
download the target as "String"
create a image resource out of it.
save it as jpeg, using the proper method:
inside your method:
$content = file_get_contents($Image);
$img = imagecreatefromstring($content);
return imagejpeg($img, "Path/to/targetFile");
In order to have file_get_contents working correctly you need to ensure that allow_url_fopen is set to 1 in your php ini: http://php.net/manual/en/filesystem.configuration.php
Most managed hosters disable this by default. Either contact the support therefore or if they will not enable allow_url_fopen, you need to use another attempt, for example using cURL for file download. http://php.net/manual/en/book.curl.php
U can use the following snippet to check whether its enabled or not:
if ( ini_get('allow_url_fopen') ) {
echo "Enabled";
} else{
echo "Disabled";
}
What you describe is more download (to the server) then upload. stream_copy_to_stream.
class Remote
{
public static function download($in, $out)
{
$src = fopen($in, "r");
if (!$src) {
return 0;
}
$dest = fopen($out, "w");
if (!$dest) {
return 0;
}
$bytes = stream_copy_to_stream($src, $dest);
fclose($src); fclose($dest);
return $bytes;
}
}
$remote = 'https://www.gstatic.com/webp/gallery/4.sm.jpg';
$local = __DIR__ . '/test/sdfsdfd.jpg';
echo (Remote::download($remote, $local) > 0 ? "OK" : "ERROR");
In my project I have a code for downloading images from a server. In php code I have:
if (is_dir($dir)){ //check if is directory
$files = scandir($dir); //list files
$i=-1;
$result = array();
foreach($files as $file){
$file = $dir.$file; //complete dir of file
if(is_file($file)){ //if it's a file
$i++;
$fileo = #fopen($file,"rb"); //open and write it on $result[$i]
if ($fileo) {
$result[$i] = "";
while(!feof($fileo)) {
$result[$i] .= fread($fileo, 1024*8);
flush();
if (connection_status()!=0) {
#fclose($fileo);
die();
}
}
$result[$i] = utf8_encode($result[$i]); //This prevents null returning on jsonencode
#fclose($fileo);
}
}
}
}else{
echo json_encode(array('Error'));
}
echo json_encode($result); //returns images as an array of strings, each one with all code of an image.
And in java I have an httpost method with asynctask. The problem of this is that I need to wait until all images are downloaded. I have thought that maybe I can download an image with a number and if the number is 0 for example recall to the server to download the next image but I think that maybe is a waste of time calling again the server and listing files again. Is there a better way so I can download image per image instead of all at the same time without calling N times to the sever?
I've had the same problem that you are having, and my solution was the next:
1º Download all data you need
2º Download to the computer the image web direction
3º Execute an asynctask per Image to download it and update your Activity while is needed
Maybe i'm not so exact and i would need some more details to give a better solution.
I want to load image via c:/user_name/image/image_name.jpg using http://intranet/user/index.php.
<img src="file:///c:/user_name/image/image_name.jpg">
How do I display them?
Thanks
Jean
You realize this would only work if that image is in the exact same location on every machine which will be viewing this page? Is there any reason you can't serve up the image normally, via the web server itself?
Since you're using an absolute Windows path, this would only work on Windows machines, which actually have a C drive, the same directories, etc... It won't work at all on a Mac or Linux or whatever else box, since they don't bother with drive letters.
followup:
after pondering your question a bit, it looks like you want to serve up a specific image that's not stored in your document root and serve it from a specific page. If you put something like this at the start of your index.php:
<?php
if (isset($_GET['username']) && isset($_GET['image'])) {
$user = $_GET['username'];
$image = $_GET['image'];
$path = "C:\\{$user}\\image\\{$image}";
if (is_readable($path)) {
$info = getimagesize($path);
if ($info !== FALSE) {
header("Content-type: {$info['mime']}");
readfile($path);
exit();
}
}
}
?>
and within the HTML:
<img src="index.php?user=user_name&image=image_name" />
Of course, this is very basic, and serving up files this way is highly insecure, but most likely this is the basics of what you wanted.
<?php
$path = "C:\\xampp\\htdocs\\Create.jpg";
if (is_readable($path))
{
$info = getimagesize($path);
if ($info !== FALSE)
{
header("Content-type: {$info['mime']}");
readfile($path);
echo '<img src="data:image/jpeg;base64,'. base64_encode($path) .'" height="100" width="100"/>';
}
}
?>