I'm using php to create a ziparchive which contains some images. This works fine exept when i try to rename the files. This is the code that works:
$zip_archive->open(tempnam("tmp", "zip"), ZipArchive::OVERWRITE);
foreach ($images as $image) {
$path = $image['path'];
$title = $image['title'];
if(file_exists($path)){
$zip_file->addFile($path, pathinfo($path, PATHINFO_BASENAME));
}
}
$zip_archive->close();
$images is an array and could look like this:
$images = array(
'path' => array(
'folder/title1.jpg',
'folder/title2.jpg'
),
'title' => array(
'new_name1.jpg',
'new_name2.jpg'
)
)
I would like to name the image as its title.
$zip_file->addFile($path, $title);
But whats happening is that the files in the zip with the title as name are empty. What am I doing wrong?
If I run this
$images = array(
'path' => array(
'folder/title1.jpg',
'folder/title2.jpg'
),
'title' => array(
'new_name1.jpg',
'new_name2.jpg'
)
);
$i = 0;
foreach($images as $image)
var_dump($image, $i++);
I get
array(2) {
[0]=>
string(17) "folder/title1.jpg"
[1]=>
string(17) "folder/title2.jpg"
}
int(0)
array(2) {
[0]=>
string(13) "new_name1.jpg"
[1]=>
string(13) "new_name2.jpg"
}
int(1)
This means that these
$path = $image['path'];
$title = $image['title'];
are both NULL
You have two ways to fix this:
Change the array to look like
$images = array(
[0] => array(
'path' => 'folder/title1.jpg',
'title' => 'new_name1.jpg'
),
[1] => array(
'path' => 'folder/title2.jpg'
'title' => 'new_name2.jpg',
)
);
in this case your initial code should work
Change the way to access the array, doing something like
for($i = 0;$i < count($images['path']);$i++)
{
$path = $image['path'][$i];
$title = $image['title'][$i];
}
This way you are sure that path and title of the image will have the same index, but it's not recommanded to do so because the array must be ordered.
I suggest you to change the array, your code should be ok that way