Issue getting ZipArchive to create a zip folder

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 1647 Views - Last Post: 30 October 2019 - 04:02 PM Rate Topic: -----

#1 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Issue getting ZipArchive to create a zip folder

Posted 24 October 2019 - 01:12 PM

I'm attempting to create a zip attachment from files that were just uploaded. To confirm, the files I am attempting to upload are uploading. The issue is isolated to the zip part and the code below.

This is the error I am receiving:

Quote

Warning: ZipArchive::close(): Can't remove file: No such file or directory in


For this line of code:

$f->close();


Does anyone see what I am doing wrong?

var_dump($zip) ---- outputs ---- bool(true)

var_dump($f) ----- outputs ----- : object(ZipArchive)#5 (5) { ["status"]=> int(0) ["statusSys"]=> int(0) ["numFiles"]=> int(0) ["filename"]=> string(53) "/php/uploads/analytics.PNG.zip" ["comment"]=> string(0) "" }

Here is the full code:

$date = new DateTime();
$fu = new fileUpload();
$filename = $fu->upload();
$uploadedFileTypes = $fu->getImageFileTypes();
$extensions = ['pdf','jpg', 'jpeg', 'png', 'gif'];

$differentExtensions = array_diff($uploadedFileTypes, $extensions);
if (count($differentExtensions) > 0) { 
    $f = new ZipArchive();
    $zip = $f->open('uploads/' . $_FILES['uploadedFile']['name'][0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
    if ($zip) {
        for ($index = 0; $index < count($_FILES['uploadedFile']['name']); $index++) {
            $f->addFile($_FILES['uploadedFile']['tmp_name'][$index], $_FILES['uploadedFile']['name'][$index]);
        }
        $f->close();

        $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name'][0]}.zip",
            pathinfo("uploads/{$file['uploadedFile']['name'][0]}.zip", PATHINFO_EXTENSION),
            $file['uploadedFile']['name'][0] . ".zip");
    }


Is This A Good Question/Topic? 0
  • +

Replies To: Issue getting ZipArchive to create a zip folder

#2 ArtificialSoldier   User is online

  • D.I.C Lover
  • member icon

Reputation: 2493
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: Issue getting ZipArchive to create a zip folder

Posted 24 October 2019 - 02:26 PM

It sounds like you're not adding any files to the archive.
Was This Post Helpful? 0
  • +
  • -

#3 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 08:23 AM

I don't get how it is empty though:

Quote

<b>Notice</b>: ZipArchive::addFile(): Empty string as filename in


I have the following right above the $date variable:

if (!empty($_FILES["uploadedFile"]["name"])) {


It is recognizing this has a filename in it or else it would completely bypass the zip code. What could I do to check why the file isn't being recognized in the zip code?
Was This Post Helpful? 0
  • +
  • -

#4 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 08:39 AM

When var_dumping:

$_FILES["uploadedFile"]["name"]


as

if (!empty($_FILES["uploadedFile"]["name"])) {
		$fileCheck = $_FILES["uploadedFile"]["name"];
		var_dump($fileCheck);


the files output the file data. So I don't get why this error is occurring:

Quote

<b>Notice</b>: ZipArchive::addFile(): Empty string as filename in


Filename Data:

Quote

:array(2) { [0]=> string(11) "airport.jpg" [1]=> string(21) "fath_09304701_6_0.par" }

Was This Post Helpful? 0
  • +
  • -

#5 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 09:21 AM

I just looked at
var_dump($f)
again. Could the issue be that my original extension is still included?

["filename"]=> string(53) "/public_html/php/uploads/afterglow.png.zip"

Was This Post Helpful? 0
  • +
  • -

#6 ArtificialSoldier   User is online

  • D.I.C Lover
  • member icon

Reputation: 2493
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 10:21 AM

Maybe one issue is that you're trying to add the temp uploaded files, I don't know if that's an issue or not. Maybe there's an issue with you using the fileUpload class to call its upload method, and then not using it any more and instead just using the $_FILES array.
Was This Post Helpful? 0
  • +
  • -

#7 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 10:29 AM

Not sure if including the fileUpload class here will help. File below:

class fileUpload
{

    public function __construct()
    {}

	public $imageFileTypes = [];

	public function getImageFileTypes()
    {
         return $this->imageFileTypes;
    }
	
    public function upload() {

		if (!empty($_FILES["uploadedFile"]["name"])) {

			$file_count = count($_FILES['uploadedFile']['name']);
			$results = [];
			for ($i = 0; $i<$file_count; $i++) {
	//          echo $file['uploadedFile']['name'][$index] . "\n";

				$target_dir = "uploads/";
				$target_file = $target_dir . basename($_FILES["uploadedFile"]["name"][$i]);
				$uploadOk = 1;
				//$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
				 // here's the important bit
				$this->imageFileTypes[] = $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

				// Check if $uploadOk is set to 0 by an error
				if ($uploadOk == 0) {
					return 0;
		// if everything is ok, try to upload file
				} else {
					if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"][$i], $target_file)) {
						$results[] = basename($_FILES["uploadedFile"]["name"][$i]);
					} else {
						return 0;
					}
				}
			}
			return $results;

Was This Post Helpful? 0
  • +
  • -

#8 ArtificialSoldier   User is online

  • D.I.C Lover
  • member icon

Reputation: 2493
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 10:40 AM

The upload method that you're calling uses move_uploaded_file, so that would imply (since it's not copy_uploaded_file) that the temp uploaded files are no longer there after you call that method, so that's why nothing is in the zip file.
Was This Post Helpful? 0
  • +
  • -

#9 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 10:48 AM

Ahh ok. Would something like this work then?

	if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"][$i], $target_file)) {
						copy($target_file)[$i];
						$results[] = basename($_FILES["uploadedFile"]["name"][$i]);
					} else {
						return 0;
					}
				}
			}
			return $results;


I just don't know how I would retrieve the copied files. Since I am returning $results.
Was This Post Helpful? 0
  • +
  • -

#10 ArtificialSoldier   User is online

  • D.I.C Lover
  • member icon

Reputation: 2493
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 11:18 AM

Your options are to either get the return filenames from the upload method and add those files to the zip file if you want to use the fileUpload class for whatever reason, or get rid of it and just use the $_FILES array if you don't.
Was This Post Helpful? 0
  • +
  • -

#11 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 11:30 AM

I get the same error when I use $filename.

Quote

<b>Warning</b>: ZipArchive::close(): Can't remove file: No such file or directory in


Updated code:

$fu = new fileUpload();
$filename = $fu->upload();
$f = new ZipArchive();
$zip = $f->open($target_dir . basename($filename[0]) . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
var_dump($f);
//var_dump($zip);
if ($zip) {
	for ($index = 0; $index < count($filename); $index++) {
		$f->addFile($_FILES['uploadedFile']['tmp_name'][$index], $filename[$index]);
	}
	//$check = $f->addFile($_FILES['uploadedFile']['tmp_name'][$index], $_FILES['uploadedFile']['name'][$index]);
        //var_dump($check);
	$f->close();

	$message["attachment[0]"] = curl_file_create("uploads/{$filename[0]}.zip",
	pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
	$filename[0] . ".zip");

Was This Post Helpful? 0
  • +
  • -

#12 ArtificialSoldier   User is online

  • D.I.C Lover
  • member icon

Reputation: 2493
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: Issue getting ZipArchive to create a zip folder

Posted 25 October 2019 - 02:26 PM

You're still trying to add the temp file. If you want to use the fileUpload class then do not use the $_FILES array.
Was This Post Helpful? 0
  • +
  • -

#13 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 29 October 2019 - 08:09 AM

Okay, the zip file is now being created. However, now I can't figure out why it isn't attaching. This post contains more of the overall code, so you can see how this all is supposed to work together.

I am completely fine creating/attaching the zip in the send file (see file labeling above each part of code). Unless it makes more sense in the communication class.

Does anyone see why when the zip is created that it isn't attaching to the email? Specifically, this part of the code is where I am trying to do it:

$message["attachment[0]"] = curl_file_create($target_dir . $filename[0] . ".zip",
	pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
	$filename[0] . ".zip");



Here is the updated file where the zip is created (the main one I have been working on).
SEND FILE

ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'classes/Communication.php';
require 'fileUpload.php';

$first_name = trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
$last_name = trim(htmlspecialchars($_POST['last_name'], ENT_QUOTES));
$email = trim(htmlspecialchars($_POST['email']));
$phone = trim(htmlspecialchars($_POST['phone']));
$zip = trim(htmlspecialchars($_POST['zip']));
$company = trim(htmlspecialchars($_POST['company'], ENT_QUOTES));
$details = trim(htmlspecialchars($_POST['description'], ENT_QUOTES));
$file = null;

require_once '../config.php';

    /************************ Start to Company ******************************/
    $placeholders = ['{first_name}',
        '{last_name}',
        '{phone}',
        '{zip}',
        '{company}',
        '{description}',
        '{interest}',
        '{email}',
        '{lead_owner}',
        '{lead_assign}'
    ];

    $values = [
        htmlentities($_POST['first_name']),
        htmlentities($_POST['last_name']),
        htmlentities($_POST['phone']),
        htmlentities($_POST['zip']),
        htmlentities($_POST['company']),
        nl2br(htmlentities($_POST['description'])),
        htmlentities($_POST['interest']),
        htmlentities($_POST['email']),
        $lead_owner = htmlentities($_POST['leadOwner']),
        $lead_assign = htmlentities($_POST['leadAssign']),
    ];

    $template = str_replace($placeholders, $values, file_get_contents("templates/quote_to_domain.html"));

	$files = null;
	if (!empty($_FILES["uploadedFile"]["name"])) {

        if ($_FILES['uploadedFile']['error'] == 1) {
            $error = "The file {$_POST['first_name']} attempted to upload is too large. Contact them for an alternate way to send this file.";
            $template = str_replace("{filename}", "$error", $template);
        }

		$date = new DateTime();
		$fu = new fileUpload();
		$filename = $fu->upload();
		$uploadedFileTypes = $fu->getImageFileTypes();
		$extensions = ['pdf','jpg', 'jpeg', 'png', 'gif'];
		//file_put_contents('file_type_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r($uploadedFileTypes, true), FILE_APPEND);
		$target_dir = "uploads/";

		$differentExtensions = array_diff($uploadedFileTypes, $extensions);
		if (count($differentExtensions) > 0) {
			//file_put_contents('file_norm_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r('There were other types of files uploaded', true), FILE_APPEND);  
			$f = new ZipArchive();
			$zip = $f->open($target_dir . $filename[0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
			if ($zip) {
				for ($index = 0; $index < count($filename); $index++) {
					$f->addFile($target_dir . basename($_FILES["uploadedFile"]["name"][$index]), basename($_FILES["uploadedFile"]["name"][$index]));
				}
				$f->close();

				$message["attachment[0]"] = curl_file_create($target_dir . $filename[0] . ".zip",
					pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
					$filename[0] . ".zip");
				//$template = str_replace("{filename}", $message, $template);
			} else {
				throw new Exception("Could not zip the files.");
				$msg = "Could not zip the files.";
				echo json_encode(['status_code' => 500,
				'message' => $msg]);
			}
		} else {
			$out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). '  uploaded. You can download ' . (count($filename) > 1 ? 'them' : 'the file'). ' from:</ul>';
			foreach ($filename as $indFile) {
				//print_r($template);
				$out .= "<li><a href='/php/uploads/{$indFile}'>{$indFile}</a></li>";
			}
			$out .= '</ul>';
			$template = str_replace("{filename}", $out, $template);
		}

		foreach ($_FILES as $file) {
			foreach($file['name'] as $key => $value) {
				if (empty($value)) {
					//echo "name is empty!";
					$template = str_replace("{filename}", '', $template);
				}	
				if ($file['error'][$key] != 4) {
					//echo "error code is 4";
				}
			}
		}
		clearstatcache();
	}
    $to_company = Communication::mail_api($_POST, $filename, $template, 0);



Then here is the communication class. Originally, the zip code was in here (and still is). I can't figure out how to get the two files to work together as they should have.

COMMUNICATION CLASS

class Communication
{

    public static function mail_api(Array $msg, Array $filename = null, $template = null, $recipient = false, $attachment = null)
    {
        $date = new DateTime();
        $config = array();
        $message = array();
        $message['to'] = !$recipient ? $email_to_send_to : $msg['email'];
        $message['h:Reply-To'] = !$recipient ? $msg['email'] : '';
        $message['subject'] = isset($msg['subject']) ? $msg['subject'] : '';

        if ($attachment) {
            try {
                if (!file_exists($attachment)) {
                    throw new Exception("File $attachment not found!");
                }
                $parts = explode('/', $attachment);
                $filenames = end($parts);
                $message['attachment[0]'] = curl_file_create($attachment,
                    pathinfo($attachment, PATHINFO_EXTENSION),
                    $filenames);
                file_put_contents('log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Attachment added: \n", FILE_APPEND); //here

            } catch (Exception $e) {
                file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
            }
        }

        $message['html'] = $template;

        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $config['api_url']);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'o:tracking-clicks: false'
            ));

            curl_setopt($ch, CURLOPT_USERPWD, "api:{$config['api_key']}");
            $self = new Communication();

            if (!empty($file) && !$recipient && count($filename) > 1) {

                $f = new ZipArchive();
                $zip = $f->open('uploads/' . $filename[0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
                if ($zip) {
                    for ($index = 0; $index < count($_FILES['uploadedFile']['name']); $index++) {
//                        echo $file['uploadedFile']['name'][$index] . "\n";
                        //$f->addFile($_FILES['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]);
						$f->addFile($target_dir . basename($_FILES["uploadedFile"]["name"][$index]), basename($_FILES["uploadedFile"]["name"][$index]));
                    }
                    $f->close();
						
		$message["attachment[0]"] = curl_file_create("uploads/{$filename[0]}.zip",
                        pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
                        $filename[0] . ".zip");
                } else {
                    throw new Exception("Could not zip the files.");
                }
//                $message['html'] = str_replace("{filename}", "A file was uploaded. You can download the file from: <a href='/php/uploads/{$file['uploadedFile']['name']}.zip'>{$file['uploadedFile']['name']}</a>", $message['html']);

            } elseif (count($filename) == 1) {
                $message["attachment[0]"] = curl_file_create("uploads/{$filename}",
                    pathinfo("uploads/{$filename}", PATHINFO_EXTENSION),
                    $filename);
            }


            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
            $result = curl_exec($ch);
            curl_close($ch);

            $resp = json_decode($result);
            file_put_contents('communication_log', "\n[{$date->format('Y-m-d H:i:s')}] " . "Log for {$message['to']}: \n" . print_r(json_encode($resp) . "\n\n" . print_r($message,1), 1), FILE_APPEND);
			// print_r($resp);
            if (isset($resp->id))
                return true;
            return false;

        } catch (Exception $e) {
            file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error for {$message['to']}: \n" . print_r($e, 1), FILE_APPEND);
        }
    }


Then the template, which is an email that sends the file link or attachment (though attachment not sending):

TEMPLATE
<tr>
        <td> {filename} </td>
       </tr>
       <tr>
	<td><i>{message}</i></td>
       </tr>

Was This Post Helpful? 0
  • +
  • -

#14 ArtificialSoldier   User is online

  • D.I.C Lover
  • member icon

Reputation: 2493
  • View blog
  • Posts: 7,551
  • Joined: 15-January 14

Re: Issue getting ZipArchive to create a zip folder

Posted 29 October 2019 - 09:56 AM

It looks like all you need to do is pass the attachment filename to the mail_api method.
Was This Post Helpful? 0
  • +
  • -

#15 pfar54   User is offline

  • D.I.C Addict

Reputation: 1
  • View blog
  • Posts: 615
  • Joined: 30-April 15

Re: Issue getting ZipArchive to create a zip folder

Posted 30 October 2019 - 08:11 AM

Aren't I doing that here?

$to_company = Communication::mail_api($_POST, $filename, $template, 0);


By doing this, I was at least able to get a link to the zip folder on the server. I'm assuming this isn't safe though? So, it's just a bandaid for now.

$message["attachment[0]"] = curl_file_create($target_dir . $filename[0] . ".zip",
	pathinfo("uploads/{$filename[0]}.zip", PATHINFO_EXTENSION),
	$filename[0] . ".zip");
	$attachment0 = $message["attachment[0]"];
	$attachment0name = $attachment0->name;

	$out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). '  uploaded. A zip folder was created. Click to download ' . (count($filename) > 1 ? 'the files' : 'the file'). ' here:</ul>';
	$out .= "<a href='/php/" . $attachment0name ."'>Click to download</a>";
	$template = str_replace("{filename}", $out, $template);

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2