PHP Upload and Extract Zip - php

I'm trying to run a script that allows the upload of a .zip and extracts the contents. I grabbed a sample code online that is supposed to work and added a class at the beginning b/c my ISP doesn't have the zip functionality compiled in correctly.
I've left a big comment in the middle where I'm getting stuck. Not sure if this has anything to do with it running on IIS?
The .zip file gets uploaded where I'd expect it to, and I'm manually able to ftp it back and extract the files. I'm looking to extract the files here, loop over them, if they're image files, then add them to a database of gallery images... first things first though. Need to understand why I'm not seeing the contents of the zip...
<?php // need this bc of ISP settings
require($_SERVER['DOCUMENT_ROOT']."/_classes/ZipArchive.php");
?><?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
// I set up the _TEST dir with 777 permissions
$target_path = $_SERVER['DOCUMENT_ROOT']."/_TEST/".$filename;
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
// **********************************************************
// $x returns an error here
// code: ER_OPEN
// http://php.net/manual/en/function.ziparchive-open.php
// Not sure why?????
// **********************************************************
if ($x === true) {
$zip->extractTo($_SERVER['DOCUMENT_ROOT']."/_TEST/");
$zip->close();
unlink($target_path);
$message = "Your .zip file was uploaded and unpacked.";
}
else {
$message = 'failed';
}
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>

Not a solution but a workaround: do you have the control of the machine? If so, install 7-zip (on Windows) or unzip, use system('unzip ...') or system('7z ...') to extract the zip archive.

ISP installed the necessary components for zip to work so all is well now. Thanks #timdream for an alternative approach.

Related

is_uploaded_file function worked in linux But not in Windows

Code
if(is_array($_FILES) && isset($_FILES['photography_attachment'])) {
if(is_uploaded_file($_FILES['photography_attachment']['tmp_name'])) {
$fileName = $_FILES["photography_attachment"]["name"]; // The file name
$fileTmpLoc = $_FILES["photography_attachment"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["photography_attachment"]["type"]; // The type of file it is
$fileSize = $_FILES["photography_attachment"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["photography_attachment"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
$error = $error."<p>Please browse for a file before clicking the upload button.</p>";
} else if($fileSize > 10485760) { // if file size is larger than 2 Megabytes
$error = $error."<p><span>Your file was larger than</span> 10 <span>Megabytes in size</span>.</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if (!preg_match("/.(gif|jpg|png|jpeg)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
$error = $error."<p>Your file was not .gif, .jpg, .png</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
$error = $error."<p>An error occured while processing the file. Try again.</p>";
}
}else{ $error = "Please try again !!!"; }
}else{ $error = "Attachment field cannot be blank!"; }
Always goto "Please try again !!!" else while uploading image in windows, but it worked well in linux system.
Can you please any one help me for this issue?
On windows platforms you musst replace inside the file path the "\" with an "/"
Like this:
$file = str_replace ("\\", "/", $_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
Or use the php build in method, for all systems:
$file = realpath($_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}

how can I extract zip files, which was uploaded by user?

So, I want to create a system where user uploads in a zip file the files of a 3d model and the model can be shown, stored, etc
So, I got the file, I place it into a folder, permanently, And unzip it into another temp folder, just to see if it is a 3d model.
I tried like this:
$target_dir = "upload/";
$targetfilename = rand().$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $target_dir.$targetfilename);
//unzip the file into temp folder
$tmp_dir = $target_dir.rand();
mkdir($tmp_dir);
chmod($tmp_dir, 0777);
//chmod($targetfilename, 0777); //this not working, maybe isn't the right way
$zip = new ZipArchive;
$res = $zip->open($targetfilename);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($tmp_dir);
$zip->close();
echo 'SUCCESS';
} else {
echo 'ERROR';
}
I do not get any errors, but the zip can't be unzipped. Any idea? How can I resolve this?
Isn't $targetfilename is in $target_dir folder?
If so, changing
$res = $zip->open($targetfilename); to
$res = $zip->open($target_dir.$targetfilename); might solve your problem.

php upload to two different directories

I am currently using the below script to upload to the main directory, however I need this to upload to a second directory which is one level below (../../gfx/).
Any ideas how I can make this work for both uploads?
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = '../gfx/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
You're already moving it to one location:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
Just copy to another afterward. How you want to report to the user in the event that only one succeeds is up to you. But, for example, if it's only "successful" if both files are created, then you can move/copy like this:
$success = move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
$success = copy($upload_dir.$pic['name'], $another_dir.$pic['name']);
if ($success === true) {
exit_status('File was uploaded successfuly!');
}
(Where, of course, $another_dir is the directory to which you want to duplicate the file.)
You can check for errors in between the two operations, you can report success only after the first and simply internally log if the second fails, etc. That's up to you.

move_uploaded_file is making a file called 'array'?

the following piece of code recognizes the image through getimagesize() but then when i try to move the file to an uploaded folder it moves the file there but says it's an array? im confused because im not setting any variables as an array?
<?php
//simple image check using getimagesize() instead of extensions
if($_FILES){
$empty_check = getimagesize($_FILES['file']['tmp_name']);
if(empty($empty_check)){
echo 'this is not an image';
}
else{
echo 'you have uploaded ' . explode('.',$_FILES['file']['name'])[0].'
and it is a ' . explode('.',$_FILES['file']['name'])[1].'.';
//an example of how i would extract the extension
$target = "C:\\xampp\\htdocs";
move_uploaded_file($_FILES['file']['tmp_name'], $target.'\\'.$_FILES['file']);
}
}
?>
$_FILES['file']
is an array, you're trying to use it as the target filename;
comment of deceze.
Echo the file you want to move/save, then you should see what he mentioned..
When using move_uploaded_file you get to pick the filename, so you can pick anything you want.
When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.
Use this coding for multiple file uploading....
//For Multiple file uploading
if (isset($_FILES['photo']) != "") {
$errors = array();
foreach($_FILES['photo']['tmp_name'] as $key = > $tmp_name) {
$file_name = $_FILES['photo']['name'][$key];
$file_size = $_FILES['photo']['size'][$key];
$file_tmp = $_FILES['photo']['tmp_name'][$key];
$file_type = $_FILES['photo']['type'][$key];
//change the image extension as png
$fileExt = "png";
$photorename[$key] = strtolower($property_code.
'_'.$key.
'.'.$fileExt);
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
//Path of Uploading file
$target = "images_property";
if (empty($errors) == true) {
if (is_dir($target) == false) {
mkdir("$target", 0700); // Create directory if it does not exist
}
if (file_exists("$target/".$photorename[$key])) {
unlink("$target/".$photorename[$key]);
}
move_uploaded_file($file_tmp, "$target/".$photorename[$key]);
} else {
print_r($errors);
}
}
if (empty($errors)) {
echo "Success";
}
}

Uploading an image with rackspace

So i have the following codes that uploads an image to the dir /uploads.
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode('', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
I tried to change the code a bit. So instead of uploading to the directory, i wanted it to upload to my rackspace. I am using the following codes (which works with my other file uploads)
// cloud info
$username = ""; // username
$key = ""; // api key
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
// Get the container we want to use
$container = $conn->get_container('ContainerName');
// store file information
$localfile = $_FILES['pic']['tmp_name'];
$filename = $_FILES['pic']['name'];
// upload file to Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
?>
I replaced the part where the image uploads to the dir /upload to the above one. It's not working.
I am using this HTML5 drag & drop uploader.
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
Help please.
I had a problem similar to this. The issue I had was that the object doesn't have the file type associated with it. Someone probably can explain it better as I am a PHP newb, but this is what I used for it to work for me:
$object = $container->create_object($filename);
$object->content_type = "image/jpeg"; //This is where the issue is
$object->load_from_filename($localfile);

Categories