I have an issue with displaying an image stored on my debian server outside the path accessible to the webserver in order to keep it safe. Here's a link to the expected results, as well as the relevant PHP code below:
header("content-type: image/png");
if (isset($_POST['mot_de_passe']) AND $_POST['mot_de_passe'] == "superPassword") {
// If password is valid
$filename = "/home/image/test.png";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
echo $contents;
} else {
// If password is invalid
echo '<p>Mot de passe incorrect</p>';
}
This below statement should be first line of your script. Means before any html output. That solves the issue
header("content-type: image/png");
Try to use r+
fopen($filename, "r+");
Because you say Debian I have the question: PHP and httpd have access to read that directory(somewhere in my debian) and file (image)?
chmod
Related
I'm currently having the problem that my download always stops at almost exactly one gigabyte. I have created a PHP download script which checks the user permissions before downloading and then prevents copying the URL. For this I use fread() to pass the data through PHP. However, I have no idea why the download always stops exactly after one gigabyte. The file is about twice as large.
Could someone take a look at this?
// ... Permission check, get download url, etc. ...
try
{
define('CHUNK_SIZE', 8 * 1024);
function readfile_chunked($filename, $retbytes = true)
{
$buffer = '';
$cnt = 0;
$handle = fopen($filename, 'rb');
if ($handle === false)
{
return false;
}
while (!feof($handle))
{
$buffer = fread($handle, CHUNK_SIZE);
echo $buffer;
if(ob_get_level() > 0)
{
ob_flush();
flush();
}
if ($retbytes)
{
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status)
{
return $cnt;
}
return $status;
}
$mimetype = 'mime/type';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $download->url);
readfile_chunked($download->url);
}
catch(Exception $e)
{
echo "Error while reading the file";
exit;
}
Update:
I have now tested the script on another server. Here the download sometimes terminated after 300 MB and sometimes after 1.3 GB. I then defined the following settings:
ini_set('display_errors', 0);
ini_set('error_reporting', E_ALL);
ini_set("log_errors", 1);
ini_set("error_log", "error.log");
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 7200);
On the other server, the script has now run through several times without any problems. The download was complete and the file was error-free. However, I copied these settings to the original system and the download still stops. I downloaded the file three times in a row. The file size varies slightly:
1.057.983 KB
1.056.192 KB
1.056.776 KB
I'm running out of ideas. What else could that be? They are both Apache web servers.
There are also no noticeable entries in the log.
I'm having some trouble with this one. I have found some helpful scripts on the web and have been modifying them for my needs. However, I can't seem to download a file. It will respond back with the contents of the file but doesn't download it. I am using Polymer 1.0+ for my client side and PHP for my server side. The client side code to download a file is as follows:
<!--THIS IS THE HTML SIDE-->
<iron-ajax
id="ajaxDownloadItem"
url="../../../dropFilesBackend/index.php/main/DownloadItem"
method="GET"
handle-as="document"
last-response="{{downloadResponse}}"
on-response="ajaxDownloadItemResponse">
</iron-ajax>
//THIS IS THE JAVASCRIPT THAT WILL CALL THE "iron-ajax" ELEMENT
downloadItem:function(e){
this.$.ajaxDownloadItem.params = {"FILENAME":this.selectedItem.FILENAME,
"PATH":this.folder};
this.$.ajaxDownloadItem.generateRequest();
},
The server side code is as follows (the url is different because I do some url modification to get to the correct script):
function actionDownloadItem(){
valRequestMethodGet();
$username = $_SESSION['USERNAME'];
if(validateLoggedIn($username)){
$itemName = arrayGet($_GET,"FILENAME");
$path = arrayGet($_GET,"PATH");
$username = $_SESSION['USERNAME'];
$downloadItem = CoreFilePath();
$downloadItem .= "/".$_SESSION['USERNAME']."".$path."".$itemName;
DownloadFile($downloadItem);
}
else {
echo "Not Logged In.";
}
}
function DownloadFile($filePath) {
//ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
//touch($filePath);
//chmod($filePath, 0775);
if ($fd = fopen($filePath, "r")) {
$fsize = filesize($filePath);//this returns 12
$path_parts = pathinfo($filePath);//basename = textfile.txt
$ext = strtolower($path_parts["extension"]);//this returns txt
$header = headerMimeType($ext); //this returns text/plain
header('Content-disposition: attachment; filename="'.$path_parts["basename"].'"'); // use 'attachment' to force a file download
header("Content-type: $header");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
}
Any help on this one would be greatly appreciated.
First you will need the file handle
$pathToSave = '/home/something/something.txt';
$writeHandle = fopen($pathToSave, 'wb');
Then, while you are reading the download, write to the file instead of echoing
fwrite($writeHandle, fread($fd, 2048));
Finally, after writing to the file finished close the handle
fclose($writeHandle);
I neglect the error check, you should implement your own.
I need to save a pdf file into BLOB (database is MsSql 2012, but I would need it work on 2008 too).
Here is compilation of what I have tried so far:
(File where I save pdf into database)
function preparePDF2String($filepath)
{
$handle = #fopen($filepath, 'rb');
if ($handle)
{
$content = #fread($handle, filesize($filepath));
$content = bin2hex($content);
#fclose($handle);
return "0x".$content;
}
}
$out = preparePDF2String('pdf/pdf.pdf');
$q_blob = "INSERT INTO HISTORIA_ARCHIWUM_test(PDFName, PDFData) VALUES('First test pdf', $out) ";
$r_blob = mssql_query($q_blob,$polacz);
Results (ok, I think)
(Now the php file where I try to output the pdf)
// header('Content-type: application/pdf');
// readfile('pdf/pdf.pdf'); - this works just fine, so pdf is ok
$q_blob = "select top 1 * from HISTORIA_ARCHIWUM_test";
$r_blob = mssql_query($q_blob,$polacz);
$w_blob = mssql_fetch_array($r_blob);
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"');
echo $w_blob['PDFData'];
//echo hex2bin ($w_blob['PDFData']); - I also tried this - same problem
Problem: when I try to output the pdf in the browser I get error (this pdf is of not supported format). It won't open in Adobe reader also. My guess is that I output it wrong, but maybe it is the way I save it?
EDIT from comments
It seems php+mssql truncates string when you get it from db, but its manageable in php.ini. I set mssql.textlimit = 160000 and mssql.textsize = 160000 and it works fine with Hex conversion and varchar(max).
You are transforming the pdf data before you save it to the database, you have to undo the transformation before you output it.
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"');
echo hex2bin(substr($w_blob['PDFData'], 2));
Also why are you transforming the data in the first place, just save it as binary.
I got a code here using file_exist. it checks if a .txt and a .jpg file exist in the directory. and then displays those in an alert box. it works well for the .txt but not in the .jpg. it displays the image source instead of the image itself. what am i doing wrong here? can you give me some help regarding this? thanks a lot in advance! here's my code.
search.php
<?php
class Model
{
public function readexisting()
{
if(
file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.txt")
&&
file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.jpg")
)
{
$myPic = "/Alchemy/ajax/events/folder-01/event-01.jpg";
echo $myPic;
$myFile = ($_SERVER['DOCUMENT_ROOT'] . "/Alchemy/events/folder-01/event-01.txt");
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData ;
}
else
{
echo "The file $myFile does not exist";
}
}
}
?>
You need to apply header() and tell PHP that you are rendering an image.
header("Content-type: image/jpeg");
OR depending upon which file you are rendering, apply proper headers.
Remove the echo $myPic; and then add this before the echo $theData;
header("Content-type: image/jpeg");
In general you have to inform the browser for the data type you are sending. Also note, that the header() command should be located before you start sending any data to the browser.
Also, if you will manipulate multiple file types (ie: png, jpg, gif) you should change the MIME type in the deader command to map the appropriate file type.
header("Content-type: image/gif"); // For gif images
header("Content-type: image/png"); // For png images
header("Content-type: image/jpeg"); // For jpg images
For an image (or anything else for that matter) you'll need to send a content-type header, otherwise it will not be shown. You can do this by getting the mime-type first here and then adding the header by doing this before the echo.
header("Content-Type: ". $mimetype);
echo $theData;
Where $mimetype is the mime type retrieved.
Im trying to extract the values between eng_tid
and eng_data for http://fdguirhgeruih.x10.mx/html.txt and I keep getting T string errors.
why do I keep getting errors
<? php
//First, open the file. Change your filename
$file = "http://fdguirhgeruih.x10.mx/html.txt";
$word1='tid';
$word2='data';
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);
$between=substr($contents, strpos($contents, $word1), strpos($contents, $word2) - strpos($contents, $word1));
echo $between;
?>
UPDATE after seeing error messages...
Instead of fread() and attempting to use the size in bytes of your target file, you may simply use file_get_contents() to retrieve the remote file. Your error is because PHP wants to read the filesize of the file as though it is local, but it is a remote file over HTTP. filesize() reports 0 and an error. Instead do
// Don't do this...
//$handle = fopen($file, "r");
//$contents = fread($handle, filesize($file));
//fclose($handle);
// Instead do this...
$contents = file_get_contents($file);