Reputation: 31
Hello fellow coders!
I have a php script that saves the url's passed from a form to a zipped archive, which works just fine.
The only trouble is when a user submits the form after selecting a lot of urls, the user has to wait a while whilst the php script does it's stuff.
I would like to use ajax to have a sort of verbose feedback after each url is added to the zip in it's foreach loop, and also flag up if it encountered a php error (it currently does this if one of the url's was a 404 page.)
I've tried a couple of tests with AJAX but gotten nowhere.
Would this even be possible?
My line of thought is that the foreach loop would run as an external php script via AJAX, and pass it's data back to this script on success... or there may be a better way of doing it.
Any help would be greatly appreciated!
<?php
$dir = "archive/";
$site = 'http://domain.com/';
$urls = array($site);
$zipfile = 'archive-'.date('Ymd_His').'.zip';
$zip = new ZipArchive;
$newzip = $zip->open($zipfile, ZipArchive::CREATE);
if (isset($_POST['urls'])){$urls = $_POST['urls'];}
if ($newzip === TRUE) {
foreach ($urls as $url) {
$file = file_get_contents($url);
$filename = "index.html";
$namer = str_replace($site, '', $url);
if ($namer != "") {$filename = $namer;}
$zip->addFromString($dir.$filename, $file);
}
$source = "assets/";
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
if (is_dir($file) === true){
$zip->addEmptyDir($dir.str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true){
$zip->addFromString($dir.str_replace($source . '/', '', $file), file_get_contents($file));
}
}
$zip->close();
echo "Generated <a href='$zipfile'>$zipfile</a>";
} else {
echo 'failed';
}
?>
Upvotes: 3
Views: 172
Reputation: 26549
For you to use ajax to receive feedback on the progress of your PHP script you can do the following:
In the case you use a database, your secondary script must query the database, and provide all new information to the client about how the zip file operations are going.
So summary:
setInterval
to query URL that provides status information.Upvotes: 1