I want to download multiple files from amazon s3 in zip file while click on single download button.
I want to achieve this using php or JavaScript.
I went over many solutions such as: Use recursive in aws cli,
Zipstream on fly, but I didn't get any proper solution.
Do you have any idea for another, more efficient solution?
<?php
$urls = [
'http://django-dev.s3.amazonaws.com/static/img/sample-store.jpg',
'http://ds-assets.s3.amazonaws.com/baobao/feature/2020/video/movie_sample.mp4',
'http://ds-assets.s3.amazonaws.com/briefing/mailmagazine/2019/0701/sample_g.jpg',
];
$mh = curl_multi_init();
$resources = [];
foreach ($urls as $key => $url) {
$resources[$key]['fp'] = fopen(sys_get_temp_dir() . '/file' . $key, 'w+'); // file pointer
$resources[$key]['ch'] = curl_init($url); // curl handle
curl_setopt($resources[$key]['ch'], CURLOPT_FILE, $resources[$key]['fp']);
curl_setopt($resources[$key]['ch'], CURLOPT_FOLLOWLOCATION, true);
curl_multi_add_handle($mh, $resources[$key]['ch']);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
$zip = new ZipArchive();
$zip->open(sys_get_temp_dir() . '/files.zip', ZIPARCHIVE::CREATE);
foreach ($resources as $key => $resource) {
curl_multi_remove_handle($mh, $resource['ch']);
curl_close($resource['ch']);
fclose($resource['fp']);
$zip->addFile(sys_get_temp_dir() . '/file' . $key, '/file' . $key);
}
curl_multi_close($mh);
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=files.zip');
header('Pragma: no-cache');
readfile(sys_get_temp_dir() . '/files.zip');
Related
I'm getting PDF file base64 string in controller. When i save it to local storage it shows an error of corrupted PDF (not decoded). How i can solve this issue?
Can someone figure out?
base64 String:
"data:application/pdf;filename=generated.pdf;base64,JVBERi0xLjMKJbrfrOAKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAyIDAgUgovTWVkaWFCb3ggWzAgMCA1OTUuMjggODQxLjg5XQovQ29udGVudHMgNCAwIFIKPj4KZW5kb2JqCjQgMCBvYmoKPDwKL0xlbmd0aCA1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AwIG4gCjAwMDAwMDc2MjUgMDAwMDAgbiAKMDAwMDAwMDAxNSAwMDAwMCBuIAowMDAwMDAwMTI0IDAwMDAwIG4gCjAwMDAwMDU4NjUgMDAwMDAgbiAKMDAwMDAwNTk5MCAwMDAwMCBuIAowMDAwMDA2MTIwIDAwMDAwIG4gCjAwMDAwMDYyNTMgMDAwMDAgbiAKMDAwMDAwNjM5MCAwMDAwMCBuIAowMDAwMDA2NTEzIDAwMDAwIG4gCjAwMDAwMDY2NDIgMDAwMDAgbiAKMDAwMDAwNjc3NCAwMDAwMCBuIAowMDAwMDA2OTEwIDAwMDAwIG4gCjAwMDAwMDcwMzggMDAwMDAgbiAKMDAwMDAwNzE2NSAwMDAwMCBuIAowMDAwMDA3Mjk0IDAwMDAwIG4gCjAwMDAwMDc0MjcgMDAwMDAgbiAKMDAwMDAwNzUyOSAwMDAwMCBuIAowMDAwMDA3ODczIDAwMDAwIG4gCjAwMDAwMDc5NTkgMDAwMDAgbiAKdHJhaWxlcgo8PAovU2l6ZSAyMQovUm9vdCAyMCAwIFIKL0luZm8gMTkgMCBSCi9JRCBbIDwyNjA2MTAxMjdCMkIzRDhCRjYzQUI1MEIyODM3MjdFNT4gPDI2MDYxMDEyN0IyQjNEOEJGNjNBQjUwQjI4MzcyN0U1PiBdCj4+CnN0YXJ0eHJlZgo4MDYzCiUlRU9G"
$pdf = $request->get('pdf_file');
$id = $request->get('user_id');
$data = explode( ',', $pdf);
$file_name = time() . '-test.pdf';
$path = public_path() . '/images/users/' . $file_name;
file_put_contents($path, $data[1]);
Please try this updates solution this should definitely work for you.
$pdf = $request->get('pdf_file');
$id = $request->get('user_id');
$data = explode( ',', $pdf);
# Decode the Base64 string, making sure that it contains only valid characters
$bin = base64_decode($data[1], true);
$file_name = time() . '-test.pdf';
$path = public_path() . '/images/users/' . $file_name;
# Write the PDF contents to a local file
file_put_contents($path, $bin);
$pdf = $request->get('pdf_file');
$id = $request->get('user_id');
$array_1 = explode(";", $pdf);
$array_2 = explode(",", array_1[1]);
$data = base64_decode($array_2[1]);
$file_name = time() . '-test.pdf';
$path = public_path() . '/images/users/' . $file_name;
file_put_contents($path, $data);
Try this piece of code. It is hard to explain base64 format exploding by writing, so if you just dd(); it will be very clear to you.
I have some files on my PHP server inside uploads folder. My problem is the following: I want to send a JSON asynchronous request from my client as to choose one of these files and create with this an image element as to display it in the browser.
JS code
var file_name="test.jpg";
$.ajax({
method:"POST",
dataType:"json",
url:"retrieve_photo.php",
data:{name:file_name},
success: function(data) {
var new_thumb = document.createElement("img");
document.getElementById('dragarea').appendChild(new_thumb);
...
}
})
PHP code (retrieve_photo.php):
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder="uploads";
$file_name=$_POST[name];
$files = glob($storeFolder.$ds.$file_name);
if ( false!==$files ) {
....
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
?>
I do not know what to write as $result feeds data the right way. I 've tried
$result=readfile($storeFolder.$ds.$file_name);
but maybe not correctly.As to conclude I want to use data as to display an image to my browser.
Thank you
Maybe will be better do something like that?:
var image = new Image();
image.src = "blabla";
$(image).on('load', function(){
//do what you want
})
Why do you even use AJAX? Maybe i don't understand)
Since you don't use algorithm or functions in your PHP, you can do everything by Javascript / Jquery :
var img = $("<img />").attr('src', 'uploads/'+ file_name)
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined") {
alert('Image not found');
} else {
$("#dragarea").append(img);
}
});
document.getElementByI('dragarea').appendChild(new_thumb);
Мaybe you mean? document.getElementById('dragarea').appendChild(new_thumb);
document.getElementById('dragarea').appendChild(new_thumb);
try this in your retrieve_photo.php
$filename = "test.jpg";
//Make sure $filename contains the appropriate path of the photo
$size = getimagesize($filename);
$file = $filename;
if ($size) {
header("Content-type:". $size['mime']);
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=$filename");
header('Content-Transfer-Encoding: base64');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/force-download");
readfile($file);
exit;
}
I have a webapp that simulates a terminal. Every command is posted via AJAX using the following script (portion):
AJAX/jQuery
$.post("sec/cmd_process.php", { n : n } )
.done(function(data){
output.append(display(data));
});
If the user types download log into the terminal, the following script - on sec/cmd_process.php is executed:
PHP
if(isset($_POST['n'])){
echo $_POST['n'];
$t = explode(' ', $_POST['n']);
if(strtolower($t[0])=='download'){
if(!isset($t[1])) shout_error("No download specified");
//Download Log
elseif($t[1]=='log'){
$stmt = $dbh->prepare("SELECT * FROM `tap_log` ORDER BY `time`");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
$user = user_by_id($row['user']);
$data.= "{$row['time']} - User {$user['id']} ({$user['name1']} {$user['name2']}) - {$row['information']} ({$row['subject']})".PHP_EOL;
}
$handle = fopen('log.txt','w+');
fwrite($handle, $data);
$path = 'log.txt';
header('Content-Transfer-Encoding: binary');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($path)).' GMT');
header('Accept-Ranges: bytes');
header('Content-Length:'.filesize($path));
header('Content-Encoding: none');
header('Content-Disposition: attachment; filename='.$path);
readfile($path);
fclose($handle);
}
}
}
What I want to happen is for the generated file, log.txt, is downloaded via the Save As... dialog. This code works if you directly visit a PHP page with those headers, but how can I make it work through jQuery/AJAX?
The simplest solution I found was to return a <script> tag forwarding the location to a forced download page:
<script type='text/javascript'>
location.href='sec/download.php?file=log.txt&type=text';
</script>
sec/cmd_process.php
$handle = fopen('log_'.time().'.txt','w+');
fwrite($handle, $data);
echo "Please wait while the file downloads...";
echo "<script type='text/javascript'>location.href='sec/download.php?file=log.txt&type=text';</script>";
fclose($handle);
sec/download.php
<?php
$filename = $_GET['file'];
$filetype = $_GET['type'];
header("Content-Transfer-Encoding: binary");
header("Last-Modified: ".gmdate('D, d M Y H:i:s',filemtime($filename))." GMT");
header("Accept-Ranges: bytes");
header("Content-Length: ".filesize($filename));
header("Content-Encoding: none");
header("Content-Type: application/$filetype");
header("Content-Disposition: attachment; filename=$filename");
readfile($filename);
I am trying to generate a file to download. With JavaScript I call a PHP file to process my request and send back the result in a way it should be possible to download it. But instead of making it available for download it simply display the code.
PHP
function export()
{
// Get a database object.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select fields to get.
$fields = array(
$db->quoteName('params')
);
// Conditions for which records should be get.
$conditions = array(
$db->quoteName('element') . ' = ' . $db->quote('plugin_name'),
$db->quoteName('folder') . ' = ' . $db->quote('system')
);
// Set the query and load the result.
$query->select($fields)->from($db->quoteName('#__extensions'))->where($conditions);
$db->setQuery($query);
$results = $db->loadResult();
// Namming the filename that will be generated.
$name = 'file_name';
$date = date("Ymd");
$json_name = $name."-".$date;
// Clean the output buffer.
ob_clean();
echo $results;
header('Content-disposition: attachment; filename='.$json_name.'.json');
header('Content-type: application/json');
}
JavaScript
function downloadFile() {
var fd = new FormData();
fd.append('task', 'export');
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", uploadComplete, false);
xhr.open("POST", "my_php_file");
xhr.send(fd);
}
HTML file
<button class="btn btn-primary btn-success" type="button" onclick="downloadFile()"></button>
UPDATE MY CODE
You need to call any header function calls before you output data. Otherwise you will get a headers "Headers already sent" warning, and the headers will not be set.
Example:
...
// Namming the filename that will be generated.
$name = 'file_name';
$date = date("Ymd");
$json_name = $name."-".$date;
header('Content-disposition: attachment; filename='.$json_name.'.json');
header('Content-type: application/json');
// Clean the output buffer.
ob_clean();
echo $results;
An example
<?php
ob_start();
echo "some content to go in a file";
$contentToGoInFile = ob_get_contents(); //this gets the outputted content above and puts it into a varible/buffer
ob_end_clean();
header('Content-disposition: attachment; filename='.$json_name.'.json');
header('Content-type: application/json');
echo $contentToGoInFile;
exit; //stops execution of code below
example with your code
$results = $db->loadResult();
// Namming the filename that will be generated.
$name = 'file_name';
$date = date("Ymd");
$json_name = $name."-".$date;
ob_start();
echo $results;
$contentToGoInFile = ob_get_contents(); //this gets the outputted content above and puts it into a varible/buffer
ob_end_clean();
header('Content-disposition: attachment; filename='.$json_name.'.json');
header('Content-type: application/json');
echo $contentToGoInFile;
exit
In Php, I encoded a JSON array from MySQL table . i want to decode it in different Php file . and i want to access the data through JavaScript from different file. anyone please help me.
MY code is:
$serverName = "(local)";
$connectionInfo = array( "Database"=>"sample");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br/>";
}
else
{
echo "Connection could not be established.<br/>";
die( print_r( sqlsrv_errors(), true));
}
$str="Select * from sam1";
$res=sqlsrv_query($conn,$str) or die("Error !");
$response=array();
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC) )
{
$response['tdata'][]=$row;
}
print(json_encode($response));
Output is :
{"tdata":[{"id":"1","name":"aaa"},{"id":"2","name":"bbb"},{"id":"3","name":"ccc"}]}
My decode Function is:
$data = file_get_contents('db2.php');
$data1 = json_decode($data, true);
print($data1);
but its not working..
When you return JSON encoded string it is best if you send a proper headers. You should return JSON like that (you can still use print function):
<?php
header('Content-Type: application/json');
echo json_encode($data);
Now, when you retrieve this output, send it to json_decode function that will return an object.
json_decode.
file_get_contents function retrieves content of the file, it does not parse it. To retrieve the content of the file:
by calling it with an URL (DO NOT USE THIS ONE I am showing this method for the purpose of learning only, this function wont load URL if allow_url_fopen directive is off, instead you can use curl library (here))
$json = file_get_contents('www.example.com/db2.php');
echo json_decode($json, true);
by including it with a relative path
$json = (include "db2.php");
echo json_decode($json, true);
in this particular scenario, db2.php has to use return statement like so
return json_encode($response);
by using ob_* with include, this time you do not need to return in db2.php file
ob_start();
include "db2.php";
$json = ob_get_contents();
ob_end_clean();
echo json_decode($json, true);
It looks like you're populating $data with the text of db2.php instead of the output from running the file in php. Try this:
$data = `php db2.php`