Just rename your files.
<?php
# define file array
$files = array(
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Physics.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Physics.PDF',
);
# create new zip object
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
// Variable to Keep Filenames
$filename="";
// Variable to add "-1, -2" to duplicate files
$i = 1;
# loop through each file
foreach ($files as $file) {
# download file
$download_file = file_get_contents($file);
if ( $filename == basename($file) )
{
// If this file already exists add "-1, -2"
$filename = $i . '-' . basename($file);
$i++;
} else
{
$filename = basename($file);
$i = 1;
}
#add it to the zip
$zip->addFromString($filename, $download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
?>
Edit after @RiggsFolly Comment to support out of order duplicate files
<?php
# define file array
$files = array(
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Physics.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Physics.PDF',
);
# create new zip object
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
// Array to keep filenames
$filenames = array();
# loop through each file
foreach ($files as $file) {
# download file
$download_file = file_get_contents($file);
if( array_key_exists( basename($file), $filenames ) )
{
$filename = $filenames[basename($file)] . '-' . basename($file);
$filenames[basename($file)] = $filenames[basename($file)] + 1;
} else
{
$filename = basename($file);
$filenames[basename($file)] = 1;
}
#add it to the zip
$zip->addFromString($filename, $download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
?>
5
solved Do not remove duplicate values from array