-3

Imagine there is a picture at http://example.com/icon.jpg and I want to add it to a zip file on my own sever named "Stack.zip" using php. This is my code, but it doesn't work.

$url="http://example.com/icon.jpg"
$zip = new ZipArchive;
echo $zip->open("Stack.zip");
$zip->addFile($url);
$zip->close();

P.S. I was able to do it with local files, but I had no success on doing it with internet addresses. So that's why I asked this question.

Work
  • 23
  • 6
  • What's your afford so far? Have you looked it up on the internet? For example [the php manuals](http://php.net/manual/de/book.zip.php) – Andreas Jul 13 '17 at 12:42
  • @AndreasLackner Yes, and I was successful on doing it with local files, but not with addresses from the internet. – Work Jul 13 '17 at 12:48
  • Then just store the file in a local temp-folder – Andreas Jul 13 '17 at 12:51

1 Answers1

0

From the PHP manual: http://php.net/manual/en/ziparchive.addfile.php (PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

This assumes you want to add to an existing zip file on your server.

$url = 'https://www.stackoverflowbusiness.com/hubfs/logo-so-color.png?t=1499443352566';
$local_path = '/your/local/folder/';
$img = 'icon.jpg';
file_put_contents($local_path.$img, file_get_contents($url));

$zip = new ZipArchive;
if ($zip->open($local_path.'Stack.zip') === TRUE) {
    $zip->addFile($local_path.$img, $img);
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

If you want to keep the same folder structure as the original source file, change this line ..

$zip->addFile($local_path.$img, $img);

...to this...

$zip->addFile($local_path.$img);

If you want the same script to create the zip, you can find a PHP function here: Add files to the zip

Dazza
  • 126
  • 7