Generate dynamic zip files containing variable addresses and files and get downloadable links
P粉513318114
2023-08-08 19:02:30
<p>I want to put 2 files into a zip file, one is thanks.txt and the other is file.dat, using the following code, and link to this zip file, but my code does not run correctly, I Need help correcting and optimizing this code. <br /><br />In the thanks.txt file, place the following text along with the customer's user email: <br /><br />Hi, Dear '.$email_address .' Thanks for using it!<br /><br />My code:</p><p><strong></strong></p>
<pre class="brush:php;toolbar:false;">funtion create_zip_file() {
// Get Current User Email Address!
$current_user = wp_get_current_user();
$email_address = $current_user->user_email;
$md5_address = md5($email_address);
$directory_path = 'myfiles/cloud/' . $md5_address . '/';
if (!file_exists($directory_path)) {
mkdir($directory_path, 0777, true);
}
$Myfile = file_put_contents($directory_path . 'file.dat' , $email_address);
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$website_url = 'https://' . $_SERVER['HTTP_HOST'] .'/';
} else {
$website_url = 'http://' . $_SERVER['HTTP_HOST'] .'/';
}
$result = $website_url . $directory_path . 'file.dat';
$zip = new ZipArchive;
if ($zip->open($zip_file , ZipArchive::CREATE) === TRUE)
{
//Add files to the zip file
$zip->addFile($result);
// Add a file new.txt file to zip using the text specified
$zip->addFromString('thanks.txt', 'Hi, Dear '.$email_address.' Thanks for use it!');
// All files are added, so close the zip file
$zip->close();
// Delete file after zip it
unlink($result);
}
$zip_file = $website_url . $directory_path . 'file.zip';
if (file_exists($zip_file)) {
return $zip_file;
} else {
return false;
}
}</pre>
<p><strong>And I call the zip file with the following code: </strong></p>
<p><code><a href="<?php echo create_zip_file();"> Download zip file </a></code></p>
<p>If I use a static address ($zip_file) in the following code: </p>
<p><code>if ($zip->open($zip_file , ZipArchive::CREATE) === TRUE)</code></p>
<p>The zip file is created, but when I use dynamic address, the zip file is not created. </p>
$zip->addFile($result);
Expected a valid path on the server, but you passed in the URL of the file.Same applies to $zip_file = $website_url . $directory_path . 'file.zip';
Please use the same path used when creating the .dat file: $zip->addFile($ directory_path . 'file.dat')