I have been looking for a solution to a problem I'm having with my code. The nearest solution to my problem was found here however that solution didn't fit my problem.
I'm listing uploaded files in PHP on my page, with each file being an to the file's location. That works fine, however I am new to PHP and am having difficulty in implementing others code.
Here's the code I'm using, if it helps:
<?php
// Directory Location
$directory = './';
// Timezone (UK BST)
date_default_timezone_set(WET);
// Define Byte Sizes
function file_size($size)
{
$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 1) . $filesizename[$i] : '0 Bytes';
}
// fetches all executable files in that directory and loop over each
foreach(glob($file.'*wav') as $file) {
// List Link to Files & Date/Time
echo '<a class="files" href="'.$file.'">
<span class="time">' . date("m/d/Y H:i", filemtime($file));
// List File Name & Size
echo '</span> '.$file.'
Size: '.file_size(filesize($file)).'</a>';
}
?>
If possible I would prefer the download links to be generated in PHP for each individual file. The files are listed like this: http://i.stack.imgur.com/N8Lxa.png
You should use the code of the mentioned SO answer in the following way:
change the link you display to the following which direct the user to download.php and hands over the information which file to download:
echo '<a class="files" href="download.php?file='.$file.'"> ...
Then add an download.php with the content of the SO answer but using
$filename = $_GET['file'];
to get the given filename out of the url.
Additionally you have to change header('Content-Type: application/pdf'); to whatever filetype you want to be downloaded.
for list of files list.php e.g.
<?php
// salt for md5 check
$saltmd5 = '76t7gjbertdfv56w45sdve54etyv';
// Directory Location
$directory = './';
// Timezone (UK BST)
date_default_timezone_set(WET);
// Define Byte Sizes
function file_size($size)
{
$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 1) . $filesizename[$i] : '0 Bytes';
}
// fetches all executable files in that directory and loop over each
foreach(glob($file.'*wav') as $file) {
// List Link to Files & Date/Time
$file_md5 = md5("$file$saltmd5"); // md5 file check
$file_link = "dwn.php?f=$file&c=$file_md5"; // file link
echo '<a class="files" href="'.$file_link.'">
<span class="time">' . date("m/d/Y H:i", filemtime($file));
// List File Name & Size
echo '</span> '.$file.'
Size: '.file_size(filesize($file)).'</a>';
}
?>
for download of files dwn.php e.g.
<?php
// salt for md5 check
$saltmd5 = '76t7gjbertdfv56w45sdve54etyv';
$file_md5 = $_GET['c']; // md5 file check
$filename = $_GET['f']; // the name of the file that is downloaded
if($file_md5==md5("$filename$saltmd5")){
// Directory Location
$directory = './';
$size = filesize($directory . $filename) ;
header("Content-Type: application/force-download; name=\"". $filename ."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". $size ."");
header("Content-Disposition: attachment; filename=\"". $filename ."\"");
header("Expires: 0");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
echo (readfile($directory . $filename));
}
else
{
die('no existo'); //bad file
}
?>
Related
Let's say I want to create a unique one-time link to encrypt via md5.Script at the bottom
$file1 = "/img/img1.jpeg";
$hash1 = md5($file1 . time());
$notepad = "notepad.txt";
file_put_contents($notepad, $hash1 . "\n", FILE_APPEND);
echo "Link for : <a href='download.php?file=".$file1.".&hash=" . $hash1 . "'>Download</a><br>";
and I have download.php
$file = $_GET['file'];
$hash = $_GET['hash'];
$notepad = "notepad.txt";
$hashes = file($notepad);
if (in_array($hash . "\n", $hashes)) {
header("Content-Type: application/octet_stream");
header("Content-Disposition: attachment; filename=" . basename($file));
header("Content-Length: " . filesize($file));
readfile($file);
$hashes = array_diff($hashes, array($hash . "\n"));
file_put_contents($notepad, implode($hashes));
} else {
echo "The link you are trying to use is invalid or has already been used.";
}
Yes, everything works fine, but the problem is that when I follow the link, the path where $file1 is located is visible, for example, one-time link:
http://localhost:8080/project/download.php?file=img/img1.jpeg.&hash=e4b105d20845e7ee82f782c01f833786
And I want a one-time link for each file to look like this:
http://localhost:8080/project/download.php?hash=e4b105d20845e7ee82f782c01f833786
So that the path of the file is not visible.
How can this be implemented?
the following code is saving the converted jpg file to the home directory like where the code is placed i want to store it in a folder namely images.
the file dcm-to-jpg is the file that i am executing on the web browser and then all the functions are being called. basically this is a dicom to jpg converter the solution i want is to save the converted file to a new folder that i have already created and also do let me know how to change the name of the file is that possible too??
Thanks in advance!! :)
Filename = dcm-to-jpg.php
<?PHP
#
# Creates a jpeg and jpeg thumbnail of a DICOM file
#
require_once('../class_dicom.php');
$file = (isset($argv[1]) ? $argv[1] : 'image1.dcm');
if(!$file) {
print "USAGE: ./dcm_to_jpg.php <FILE>\n";
exit;
}
if(!file_exists($file)) {
print "$file: does not exist\n";
exit;
}
$job_start = time();
$d = new dicom_convert;
$d->file = $file;
$d->dcm_to_jpg();
system("ls -lsh $file*");
$job_end = time();
$job_time = $job_end - $job_start;
print "Created JPEG and thumbnail in $job_time seconds.\n";
?>
filename = class_dicom.php
### Convert a DICOM image to JPEG. $this->file is the filename of the image.
### $this->jpg_quality is an optional value (0-100) that'll set the quality of the JPEG produced
function dcm_to_jpg() {
$filesize = 0;
$this->jpg_file = $this->file . '.jpg';
$convert_cmd = BIN_DCMJ2PNM . " +oj +Jq " . $this->jpg_quality . " --use-window 1 \"" . $this->file . "\" \"" . $this->jpg_file . "\"";
$out = Execute($convert_cmd);
if(file_exists($this->jpg_file)) {
$filesize = filesize($this->jpg_file);
}
if($filesize < 1) {
$convert_cmd = BIN_DCMJ2PNM . " +Wm +oj +Jq " . $this->jpg_quality . " \"" . $this->file . "\" \"" . $this->jpg_file . "\"";
$out = Execute($convert_cmd);
}
return($this->jpg_file);
}
?>
I want to create a zip file which contains some PDFs which are saved at my server.
Here is the code I tried,
$filenamez = 'datasheets1.zip';
$zip = new ZipArchive;
if ($zip->open('datasheets1.zip', ZipArchive::CREATE) === true) {
// Add files to the zip file
for ($m = 0; $m <= $total - 1; $m++) {
$zip->addFile('datasheet' . $m, $model1[$m] . ".pdf");
}
$zip->close();
echo 'Archive created!';
header('Content-type: application/zip');
header('Content-disposition: attachment; filename="' . $filenamez . '"');
header("Content-length: " . filesize($filenamez));
readfile($filenamez);
}
When I execute this code the zip file is created and downloaded but when I open it shows following error: " this archive is either in unknown format or damaged ".
In addition to Andrei's comment, you're echoing the string 'Archived Created!', and then also setting an application/zip header, and then streaming the contents of the ZIP file to the browser. So the content of the ZIP will be polluted by having that string inserted at the top, making it corrupt.
Part of what's being displayed:
PKd�wL��� ���/images/image_0.jpg��ex\K��1昙�3�133���;ffff����Ԇ�����w�̼߳�cw��딎�$��Z�������&QRTB�|>��E��M5���|�~b��)�o�3�� �>s���o�'���^B�O��V ����#���Q?S#(�� 6���v4���8����vvV�sy}#�_ �O��s�o���L�7Fv.F&�ol��WV.V��?�����g�W!�/w!�������K�oLL�1`���G�p�X���T�>C�#��L��)q���s��3�g�8�p�O�?
I'm trying to download images into zip file, this is what i've got so far:
if (count($headers->images) > 0) {
$counter = 0;
$zip = new ZipArchive();
$tmpFile = "tmpFolder/tmp" . strtotime("now") . ".zip";
$zip->open($tmpFile, ZipArchive::CREATE);
foreach($headers->images as $key => $images) $zip->addFromString("/images/image_" . $counter++ . ".jpg", file_get_contents($images));
$zip->close();
if (file_exists($tmpFile)) {
$fname = basename($_POST["titleZipFile"] . ".zip");
$size = filesize($tmpFile);
header("Content-Type: archive/zip");
header("Content-Disposition: attachment; filename=$fname");
header("Content-Length: " . $size);
ob_end_clean();
readfile($tmpFile);
//unlink($tmpFile);
echo "<div id='reportMessage'><p>You have successfully save images. Please go to your folder " . $_POST["titleZipFile"] . ".zip<p></div>";
}
}
if I remove the unlink($tmpFile); line then the tmp zip is actually generated and has the images inside the zip. However it's not actually showing the zip downloading in browser.
Does any one have any ideas why this could be happening?
Try to change the header for the content type to the following. I think the header is causing the browser problems with interpreting what it is supposed to do. Try the following type.
header('Content-type: application/zip');
So I'm fairly new to PHP and have been working on a web app that allows users to submit designs which are then saved as images (using html2canvas.js) to the server. I have the app working at the moment but it saves over any previous image with the same file name.
What I would like it to do is save with a consecutive number at the end of the file name so that previous designs are not overwritten. Working code below - the idea with the if else statement is that it checks for an existing file, if there isnt one, creates it (this code works) but if there is an existing file ... I dont know..
<?php
session_start();
$customerName = $_SESSION["design_name"];
//Get the base-64 string from data
$filteredData=substr($_POST['img_val_server'], strpos($_POST['img_val_server'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Check for previous user images
$fileName = '/customer-submits/design-' . $customerName . '.png';
if (file_exists($filename)) {
//THIS IS WHERE IS WANT THE FILE TO SAVE CONSECUTIVELY
} else {
//Save the image
file_put_contents('customer-submits/design-' . $customerName . '.png', $unencodedData);
$file = 'customer-submits/design-' . $customerName . '.png' ;
$fileName = basename($file);
$fileSize = filesize($file);
set_time_limit(0);
header("Pragma: public");
header("Expires: 0"); // Cache Options
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // Cache Options
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\" " . $fileName ."\"");
header("Content-length: " . $fileSize);
readfile($file);
include 'sendMail.php';
echo send_mail();
}
?>
Would obviously very much appreciate any help with this, as Im struggling to get my head around php!
This should add a new number to the end of the customers name if a similar customers name appears.
$num = 0;
while (file_exists($filename)==TRUE) {
$num++;
$file = 'customer-submits/design-' . $customerName $num . '.png' ;
}
I added ==TRUE into my previous code which makes it a Boolean and should take away the parsing error you got earlier.
Try this after "//Check for previous user images", replacing the if...else:
$indx = 1;
$filename = '/customer-submits/design-' . $customerName . $indx . '.png';
while (file_exists ($filename) {
$indx++;
$filename = '/customer-submits/design-' . $customerName . $indx . '.png';
}