I have a wordpress site and I’m creating an HR plugin for the company I work for. One function allows administrators to download a zip file containing several documents. I have tested the following code which works fine but I would like the ZIP archive to be created in a directory of my choice.
function direct_download()
{
if ($_REQUEST['action'] == 'download')
{
$App = new DHR_Application();
$file_name=str_replace(" ","_",$App->Fname)."_".str_replace(" ","_",$App->Lname)."_".$App->ID;
$txt_name=$file_name.".txt";
$txt_path="../user-upload/temp/".$file_name.".txt";
$arc_name=$file_name.".zip";
$txt=$App->Fname." ".$App->Lname."rn".$App->ID;
$file=fopen($txt_path,"w+");
fwrite($file,$txt);
$zip = new ZipArchive();
if ($zip->open($arc_name, ZIPARCHIVE::CREATE )!==TRUE)
{
exit("cannot open <$arc_name>n");
}
$nameAtt1 = pathinfo($App->Att1,PATHINFO_BASENAME);
$zip->addFile($App->Att1,$nameAtt1);
if (($App->Att2 != '') && ($App->Att2 != null))
{
$nameAtt2 = pathinfo($App->Att2,PATHINFO_BASENAME);
$zip->addFile($App->Att2,$nameAtt2);
}
$zip->addFile($txt_name,$txt_path);
$zip->close();
fclose($file);
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$arc_name");
header("Pragma: no-cache");
header("Expire: 0");
readfile("$arc_name");
exit();
}
}
Normally the ZIP archive is created in /wp-admin/ directory. I don’t want temporary files created and deleted in this directory because it runs the back end of wordpress.
When I include the path of the file in $arc_name
the code breaks. I looked at the $zip->filename value and it will change the value from “C:/wamp/www/company/user-upload/temp/Tony_Beroni_000001.zip” to “C:wampwwwcompanyuser-upload\tempTony_Beroni_000001.zip”. I assume this could be an issue because of the difference between WAMP and a native Apache server(no pun intended).
Does anyone know how to create a ZIP archive with PHP in a specific directory?
Edit: I noticed that I had the parameters for $zip->addFile($txt_name,$txt_path);
in reverse it should be $zip->addFile($txt_path, $txt_name);
If you are doing cross-platform development (i.e. Windows and Linux). You should alwasy specify paths using the PHP DIRECTORY_SEPARATOR constant like:
You can define the path however you like, so long as the running webserver has permissions to write to that path.
$arc_name is where you define the zip path
its first parameter for zip open.