Show progessbar on page load - php

I have created the script of downloading an facebook album in php. When I will click on download button, script is fetching all photos in that album behind the scene and zip them inside a folder. I want to start a “progress bar” as soon as user-click download button as download process may take time.
Following is index.php
if ($album['count'] != "0 photos")
{
echo "";
}
Here I am passing album id to the download.php
and following is the code for download.php where I am downloading images into the downloads folder, creating the zip file of all that images and downloading that zip file.
<?php
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
//GETTING THE ID HERE FROM INDEX.PHP FILE
$albumid = $_GET['id'];
$photos = $facebook->api("/{$albumid}/photos?limit=50");
$file_name = rand(1, 99999) . "_image.zip";
$albumArr = array();
foreach ($photos['data'] as $photo) {
$albumArr[] = $photo['source'];
}
create_zip($albumArr, $file_name);
function create_zip($files, $file_name, $overwrite = false) {
$i = 0;
$imgFiles = array();
foreach ($files as $imglink) {
$img = #file_get_contents($imglink);
$destination_path = 'downloads/' . time() . "Image_" . $i . '.jpg';
#file_put_contents($destination_path, $img);
$imgFiles[] = $destination_path;
$i++;
}
if (file_exists($file_name) && !$overwrite) {
return false;
}
$valid_files = array();
if (is_array($imgFiles)) {
foreach ($imgFiles as $file) {
$valid_files[] = $file;
}
}
if (count($valid_files)) {
$zip = new ZipArchive();
if ($zip->open($file_name, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
echo "Sorry ZIP creation failed at this time";
}
$size1 = 0;
foreach ($valid_files as $file) {
$size1+= filesize($file);
$zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
}
$zip->close();
$allimages = glob('downloads/*.jpg');
foreach ($allimages as $img) { // iterate images
if (is_file($img)) {
unlink($img); // delete images
}
}
$count = $zip->numFiles;
$resultArr = array();
$resultArr['count'] = $count;
$resultArr['destination'] = $file_name;
$filename = $file_name;
$filepath = $_SERVER['HTTP_HOST'] . '/';
$path = $filepath . $filename;
if (file_exists($filename)) {
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
unlink($filename);
}
} else {
return false;
}
}
?>
I want to start a “progress bar” as soon as user-click download button as download process may take time.
How can I do this? Thanks

Something like this? PLease tell me if I didn't understand your question
HTML:
<img id="loadingImage" src="pathToImage" alt="" style="display:none" />
//pathToImage is the path to where your image is located
jQuery:
$('#YourButtonID').click(function(){
$('#loadingImage').css('display','block');
//call your download page
return false;
});
After your download and redirect are finished, call this method to hide the progressbar
$('#loadingImage').css('display','none');

You can do this by using ajax.
$(document).ready(function()
{
$("#download_button").click(function() {
document.getElementById('progressbar').style.display='';
//call your download page.
});
});

Related

Zip file is not downloading in Yii2

I am trying to download the zip file with many images.This code is working when i call the path in browser but not downloading when i call from Jquery ajax.Need to change or add anything in header?please help.
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('imgsrc');
//it displays the URLs.
$zip = new \ZipArchive();
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach ($files as $file) {
$download_file = file_get_contents($file);
$zip->addFromString(basename($file), $download_file);
}
$zip->close();
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
}
Jquery:
$.ajax({
url:url+'site/zipdownload',
data:{'imgsrc':imgsrc},
type:'POST',
success:function(data){
//alert(data);
}
});
In console response:
I just ignore the Jquery Ajax and done it by Html::a with two actions..When i am calling the url in a tag then the file got downloaded.And also done some changes in controller.
Views:
<?=Html::a('Create Zip',['site/zipdownload'],['class'=>'btn btn-danger pull-left'])?>
<?=Html::a('Download',['site/download'],['class'=>'btn btn-danger pull-left'])?>
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('img_src');
$zip = new \ZipArchive();
$tmp_file = 'uploads/images.zip';
if(file_exists($tmp_file)){
$zip->open($tmp_file, ZipArchive::OVERWRITE);
}
else{
$zip->open($tmp_file, ZipArchive::CREATE);
}
$i=1;
foreach ($files as $file) {
$download_file = file_get_contents($file);
$fileParts = pathinfo($file);
$filename = $i.explode("?",$fileParts['filename'])[0];
$zip->addFromString($filename, $download_file);
$i++;
}
$zip->close();
}
public function actionDownload(){
$path = 'uploads/images.zip';
if(file_exists($path)){
\Yii::$app->response->sendFile($path)->send();
unlink($path);
}
else{
return $this->redirect(['site/dashboard']);
}
}

How to rename an uploaded file so that it is unique?

I have an upload form on a site that uploads multiple files to a server, and also sends me an email.
It is written in php, with the main file part being the following:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
// Define allowed extensions
// blahblahblah checking
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
Nowadays, people upload pictures from a cell phone and often they are all named the same file name: image.jpg (or something similar) - so they get overwritten.
I would like to append a counter on to each multiple file (like 1,2,3...) name so they are uploaded and sent with unique names, even though the client sends them as same name.
Something like:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
// Define allowed extensions
// counter= counter++;
// newFilename=oldFileName+String(counter);
// doRestStuffNewFileName();
// blahblahblah checking
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];`
`move_uploaded_file($temp_name, $server_file);`
array_push($files, $server_file);`
How can I modify it as such in php?
ok new comments:
I would like:
for int i=0;i<files[attached];i++;
fileName=files[i]
newFileName=filename+String(Integer(i));
uploadWithNewFileName();
writeToServerWithNewFileName();
This is php current code:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
foreach ($_FILES as $name => $file) {
if (!$file['name'] == "") {
$file_name = $file['name'];
$size += $file['size'];
$temp_name = $file['tmp_name'];
$path_part = pathinfo($file_name);
$ext = $path_part['extension'];
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
}
}
Why doesnt this work:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
counter =0; //My code
foreach ($_FILES as $name => $file) {
counter++; //My code
if (!$file['name'] == "") {
$file_name = $file['name'];
$size += $file['size'];
$temp_name = $file['tmp_name'];
$path_part = pathinfo($file_name) + counter; //My code
$ext = $path_part['extension'];
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
}
}

Symfony cannot open the downloaded zip file

I'm trying to make a zip file download. So I try to make the code like this :
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$zipFilePath = $root . '/' . $zipName;
// prepare BinaryFileResponse
$response = new BinaryFileResponse($zipFilePath);
$response->trustXSendfileTypeHeader();
$response->headers->set('Cache-Control', 'public');
$response->headers->set('Content-type', 'application/zip');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$zipName,
iconv('UTF-8', 'ASCII//TRANSLIT', $zipName)
);
return $response;
}
I think it was successful. But, when I tried to open the zip file, There is an error like this An error occurred while loading the archive.
then I tried to make the code like this
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
header('Content-Type', 'application/zip');
header('Content-disposition: attachment; filename="' . $zipName . '"');
header('Content-Length: ' . filesize($zipName));
readfile($zipName);
}
but I got nothing. The same thing also happen when i change it to this :
$zip = new ZipArchive();
$create = $zip->open($zipName, ZipArchive::CREATE);
if ($create === TRUE) { // check if the zip file is created
$basePath = $this->container->getParameter('kernel.root_dir').'/../marks/';
foreach ($listToken as $token) {
$file = $repoMarks->findByToken($token);
if($file) {
$fileName = $file[0]->getNameOnServer();
$filePath = $basePath . $fileName;
$root = realpath($this->container->getParameter('kernel.root_dir') . '/../marks');
$filePath = $root . '/' . $fileName;
if (file_exists($filePath)) {
$zip->addFile($filePath, $fileName);
}
}
}
$zip->close();
header("HTTP/1.1 303"); // 303 is technically correct for this type of redirect
header("Location: http://{$_SERVER['HTTP_HOST']}/" . $fileName);
}
is there anyone who can help me to solve this download zip file problem?
An error occurred while loading the archive. occured in your clients side is because :
Your client doesn't have any application to open zip file.
zip file corrupt or missing extension.
There is possibility you never updated / fresh install. Try to
update it sudo apt-get update
Make sure your downloader app (like IDM or flareget) is working good. (I have problem with this, and when I disable the downloader app, it works) -By Asker
It is problem with client side, (connection or program error) or with the file it self. Try open the file using another PC.

create and download zip file using php

i am trying to create a zip file(using php) for this i have written the following code:
$fileName = "1.docx,2.docx";
$fileNames = explode(',', $fileName);
$zipName = 'download_resume.zip';
$resumePath = asset_url() . "uploads/resume/";
//http://localhost/mywebsite/public/uploads/resume/
$zip = new ZipArchive();
if ($zip->open($zipName, ZIPARCHIVE::CREATE) !== TRUE) {
echo json_encode("Cannot Open");
}
foreach ($fileNames as $files) {
$zip->addFile($resumePath . $files, $files);
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=".$zipName."");
header("Content-length: " . filesize($zipName));
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipName);
exit;
however on a button click i am not getting anything..not even any error or message..
any help or suggestion would be a great help for me.. thanks in advance
Why not use the Zip Encoding Class in Codeigniter - it will do this for you
$name = 'mydata1.txt';
$data = 'A Data String!';
$this->zip->add_data($name, $data);
// Write the zip file to a folder on your server. Name it "my_backup.zip"
$this->zip->archive('/path/to/directory/my_backup.zip');
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
https://www.codeigniter.com/user_guide/libraries/zip.html
... it work for me
public function downloadall(){
$createdzipname = 'myzipfilename';
$this->load->library('zip');
$this->load->helper('download');
$cours_id = $this->input->post('todownloadall');
$files = $this->model_travaux->getByID($cours_id);
// create new folder
$this->zip->add_dir('zipfolder');
foreach ($files as $file) {
$paths = 'http://localhost/uploads/'.$file->file_name.'.docx';
// add data own data into the folder created
$this->zip->add_data('zipfolder/'.$paths,file_get_contents($paths));
}
$this->zip->download($createdzipname.'.zip');
}
What is asset_url() function? Try to use APPPATH constant istead this function:
$resumePath = APPPATH."../uploads/resume/";
Add "exists" validation for file names:
foreach ($fileNames as $files) {
if (is_file($resumePath . $files)) {
$zip->addFile($resumePath . $files, $files);
}
}
Add exit() after:
echo json_encode("Cannot Open");
Also I think it's the better desision to use CI zip library User Guide. Simple example:
public function generate_zip($files = array(), $path)
{
if (empty($files)) {
throw new Exception('Archive should\'t be empty');
}
$this->load->library('zip');
foreach ($files as $file) {
$this->zip->read_file($file);
}
$this->zip->archive($path);
}
public function download_zip($path)
{
if (!file_exists($path)) {
throw new Exception('Archive doesn\'t exists');
}
$this->load->library('zip');
$this->zip->download($path);
}
Below scripting working ok in my local system. 1st remove asset_url() from $resumePath and set zip file store location relative path.
- Pass zip file name with its location path to $zip->open()
$fileName = "1.docx,2.docx";
$fileNames = explode(',', $fileName);
$zipName = 'download_resume.zip';
$resumePath = "resume/";
$zip = new ZipArchive();
if ($zip->open($resumePath.$zipName, ZIPARCHIVE::CREATE) !== TRUE) {
echo json_encode("Cannot Open");
}
foreach ($fileNames as $files) {
$zip->addFile($files, $files);
}
$zip->close();
/* create zip folder */
public function zip(){
$getImage = $this->cart_model->getImage();
$zip = new ZipArchive;
$auto = rand();
$file = date("dmYhis",strtotime("Y:m:d H:i:s")).$auto.'.zip';
if ($zip->open('./download/'.$file, ZipArchive::CREATE)) {
foreach($getImage as $getImages){
$zip->addFile('./assets/upload/photos/'.$getImages->image, $getImages->image);
}
$zip->close();
$downloadFile = $file;
$download = Header("Location:http://localhost/projectname/download/".$downloadFile);
}
}
model------
/* get add to cart image */
public function getImage(){
$user_id = $this->session->userdata('user_id');
$this->db->select('tbl_cart.photo_id, tbl_album_image.image as image');
$this->db->from('tbl_cart');
$this->db->join('tbl_album_image', 'tbl_album_image.id = tbl_cart.photo_id', 'LEFT');
$this->db->where('user_id', $user_id);
return $this->db->get()->result();
}

PHP change variable into jpeg file

I have the following code to get the album cover of an mp3 using getid3, the problem is though, how do I copy this image and put it into a specified directory?
<?php
require_once('getid3/getid3.php');
$file = "path/to/mp3/file.mp3";
$getID3 = new getID3;
$getID3->option_tag_id3v2 = true;
$getID3->option_tags_images = true;
$getID3->analyze($file);
if (isset($getID3->info['id3v2']['APIC'][0]['data'])) {
$cover = $getID3->info['id3v2']['APIC'][0]['data'];
} elseif (isset($getID3->info['id3v2']['PIC'][0]['data'])) {
$cover = $getID3->info['id3v2']['PIC'][0]['data'];
} else {
$cover = "no_cover";
}
if (isset($getID3->info['id3v2']['APIC'][0]['image_mime'])) {
$mimetype = $getID3->info['id3v2']['APIC'][0]['image_mime'];
} else {
$mimetype = 'image/jpeg';
}
if (!is_null($cover)) {
// Send file
header("Content-Type: " . $mimetype);
if (isset($getID3->info['id3v2']['APIC'][0]['image_bytes'])) {
header("Content-Length: " . $getID3->info['id3v2']['APIC'][0]['image_bytes']);
}
echo ($cover);
?>
Is this possible, if yes how? Thanks for any help :)
have you tried:
file_put_contents('<filename>', $getID3->info['id3v2']['APIC'][0]['image_bytes']);

Categories