I'm working on an internal application where user uploads some images, uses them and at the end downloads all the files as a package.
I'm a really beginner to PHP so found a code that creates a zip of uploaded images.
<?php
$dir = 'uploads/';
$zip_file = 'file.zip';
// Get real path for our folder
$rootPath = realpath($dir);
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zip_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zip_file));
readfile($zip_file);
?>
Now there is a textarea which has a code.
I want to add that textarea's content to zip as html.
You should save textarea's content as separated .HTML file in $dir = 'uploads/';. For this you can use file_put_contents method (remember about correct file path). After ZIP creation you can remove this file.
Related
Right now I have a document that's almost like a template that has bold, indention, header and I would like to be able to take the contents of that document and replace certain strings with what the user inputs in forms that I have set up. I have it working where it makes a new one and replaces the words with just a plain text document with no special formatting. Is there a way to do this with keeping all of the formatting? Anyway it needs to be done is cool, but I've been using mostly PHP and the code I have so far to do it is PHP.
Here's what the code looks like that works with no formatting.
<?php
session_start();
$file = tempnam(sys_get_temp_dir(), 'TMP_');
file_put_contents($file, file_get_contents("freewillben1.docx"));
//replaces string in document with data
$fh = fopen($file, 'a') or die("can't open file");
$placeholders = array('Fff', 'Mmm','Lll');
$namevals =
array($_SESSION["fName"],$_SESSION["mInitial"],$_SESSION["lName"]);
$path_to_file = 'freewillben1.docx';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);
file_put_contents($file,$file_contents);
fclose($fh);
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Get a date and timestamp
$today = date("F j, Y, g:i a");
$time = time();
// Send file headers
header("Content-type: application/vnd.openxmlformats-
officedocument.wordprocessingml.document");
header("Content-Disposition: attachment; filename=yourwill.docx");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
readfile($file);
?>
So this is my whole setup :
I'm on a HTML page and i'm opening a POST request using JS inside the same HTML page and i'm opening it in a new window like this :
<script>
function Download() {
form = document.createElement('form');
form.setAttribute('method', 'POST');
form.setAttribute('action', 'test.php?App=AppNameHere');
form.setAttribute('target', 'NewWindow');
myvar = document.createElement('input');
myvar.setAttribute('name', 'terms');
myvar.setAttribute('value', '');
form.appendChild(myvar);
document.body.appendChild(form);
window.open('test.html', 'NewWindow', 'scrollbars=no,menubar=no,height=100,width=500,resizable=no,toolbar=no,status=no');
form.submit();
}
</script>
Now inside test.php i'm downloading an app referring to the GET request for the App var in the URL, also the POST request works just fine, but after start downloading the file i need to close the window, so i used :
echo "<script type='text/javascript'>window.close();</script>";
Now i tested it and it worked closing the window just fine, but now here is my problem... inside the test.php file i'm also using sessions (session_start();) and when i do use that line (session_start();) the java script code for closing the window does not work any more!!, i'v tried commenting all the code but keeping session_start(); and i really found out that it's what preventing the window from closing, which is very weird, they are not related at all, or this is what i think at least, here is my test.php file :
<?php
session_start();
if($_SESSION["TEMP"] == "Yes"){
if(isset($_GET['App'])){
$fileName = $_GET['App'] . " - Setup.exe";
if(basename($_GET['App']) == $_GET['App']){
$path = 'download_directory/' . $fileName;
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $size);
header('Content-Disposition: attachment; filename=' . $fileName);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
$file = # fopen($path, 'rb');
if($file){
fpassthru($file);
$_SESSION["TEMP"] = "No";
}
}
}
}
echo "<script type='text/javascript'>window.close();</script>";
?>
Downloading the file also worked!
Can someone please explain to me what's happening and help me go around this because i really need to use sessions?!
I'm getting really confused here. So here's whats going on in my project. The user clicks download then select directory to save the file, the file will be a zip file. After that I want to extract that zip file in the same directory the users chooses. Is this even possible in one script?
Here is my php code
<?php
require_once('connect.php');
// Get real path for our folder
$rootPath = realpath($_GET['uniq']);
// Name of the zip derive from the database
$zipname = $_GET['name'] . '.zip';
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>
If its not possible another question. Is it possible to let user choose a zip file then after that it will be extracted at some client directory ie. C://xamp/extracthere/ using javascript.
Once the user has downloaded the file to their machine, it's beyond your control. You can't force them to unzip it, or do anything else with it for that matter.
Imagine if you could control the files on a user's local disk, it would be a hacker's dream. This is impossible using both PHP and JavaScript, for similar reasons in each case.
Let's say i want to generate a download link and put it into <a> tag.
my php script:
function download_link(){
$this_id = "d"; //this is the name of file from server
$original_filename = 'xample.pdf'; //This come from database
$ext = pathinfo($original_filename, PATHINFO_EXTENSION);
$file = '../uploads/'.$this_id.'.'.$ext;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/'.$ext);
header('Content-Disposition: attachment; filename='.$original_filename);//Rename the file with its original filename
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
return readfile($file);//Here where i want to return the generated url
}
return '#'; //Or return nothing if file doesn't exist
echo ''; //And put it here, the generated url
now, my directory location is ../uploads/.
i am expecting a result like: so when the user click this tag the file will be downloaded. but instead, when i reload the page it is automatically downloading without clicking the download button which is the <a> tag.
note: i am trying to rename the filename when botton download is clicked.
i know there is a problem in my logic. maybe this can be done with JQUERY? or AJAX? im searching for solution but did not find the answer.
here's what i did with JQUERY AJAX:
HTML tag
<a id="server_name_file_name">download</a>
JQUERY AJAX:
$('a').click(function(e) {
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'download.php',
data: { server_file_name: id,},
success: function(response) {
if(response == 1){
alert("Unable to download, Maybe the file is corrupted. Please try to reload the page.");
}else{
window.location.href = response;
return false;
}
}})
});
download.php
$this_id = $_POST['server_file_name'];
$original_filename = 'xample.pdf'; //This come from database
$ext = pathinfo($original_filename, PATHINFO_EXTENSION);
$file = '../uploads/'.$this_id.'.'.$ext;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/'.$ext);
header('Content-Disposition: attachment; filename='.$original_filename);//Rename the file with its original filename
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
echo readfile($file);//Here where i want to return the generated url
exit();
} die('1');
but doesnt work.
anyone can help me here? Thank you!!!!
You're returning the actual contents of the file with readfile.
Thats why browser starts to download the file you return.
What you need to do is to generate the string which will point to the file.
If your "uploads" dir is accessible by url, then your downloads.php should look like this:
$this_id = $_POST['server_file_name'];
$original_filename = 'xample.pdf'; //This come from database
$ext = pathinfo($original_filename, PATHINFO_EXTENSION);
$file = '../uploads/' . $this_id . '.' . $ext;
if (file_exists($file)) {
echo 'www.myserver.com/uploads/' . $this_id . '.' . $ext;
exit();
}
die('1');
If your uploads dir is not accessible from outside, then you need to copy the file into the public directory first.
At a first glance, i can identify a couple of problems.
Your download function does not return the link of the file but rather it outputs the file itself, so it is logical that when refreshing the page, the file is downloading.
Plus, I can see that you are calling your function useing function download_link() whereas it should be directly download_link().
The proper way this should be done is having the download link to a file executing the download_link function (ex: http://yoursite.com/download_file.php?file=filename)
Of course it is advisable to have an id instead of filename in the URL and apply all the security you need etc...
Inside download_file.php file, you can call download_link($filename) or better download_link($id) and get the file name from the database or wherever you are storing it and then output the file as you are doing now.
I have built a PHP script that sends *.MP3 files form outside the public_html directory,
it works OK and sends the file. The problem is that I have a JavaScript script which should change the current time of the audio file (audioFile.currentTime = 25;).
When I do this(Get the file from inside the public_html directory), it works:
// JavaScript:
var audioFile = new Audio("https://www.website.com/files/audioFile.mp3");
audioFile.play();
audioFile.currentTime = 15;
But, when I try to get the file from the following PHP script it sends the file OK. But, I can't change the "currentTime" using JavaScript
<?php
// This PHP file is public www.website.com/getAudioFile.php/
$fileLocation = "../audioFiles/audioFile.mp3";
if (file_exists($fileLocation))
{
header('Content-type: audio/mpeg');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
readfile($file);
}
?>
This is the JavaScript within which I tried to change the audio file currentTime:
<script>
var audioFile = new Audio("www.website.com/getAudioFile.php");
audioFile.play();
audioFile.currentTime = 15;
</script>
Each time I use object.currentTime = 15, the audio files plays from the start.
If anyone knows what headers I should send or anything else I should do, please let me know how to solve my problem.
Maybe You should bind canplay event from Audio component and in this callback set currentTime property.
http://www.w3schools.com/tags/av_event_canplay.asp
Shortly after I have posted this question, I found the solution to the problem.
In order to make the script work you will need to add the header('Accept-Ranges: bytes');
Like this:
<?php
// This PHP file is public www.website.com/getAudioFile.php/
$fileLocation = "../audioFiles/audioFile.mp3";
if (file_exists($fileLocation))
{
header('Content-type: audio/mpeg');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length: ' . filesize($file));
readfile($file);
}
?>