Can't create archives with php zip library - php

I'm trying to develop for homework a MVC PHP app that archives some files, app which I'm building on a Zend Server in Windows 7 (if it matters).
Here's the setup : I have this form in a view :
<div class="box">
<h3>What would you like to store?</h3>
<form action="<?php echo URL; ?>archives/archiveAction" method="POST" enctype='multipart/form-data'>
<label>Select the files you'd like to store</label>
<input type="file" name="upload[]" multiple>
<input type="hidden" name="user_id" value="<?php echo $_SESSION['id']; ?>" >
<label>Select your favorite compression algorithm</label>
<select name="type_of_archive">
<option value="zip">ZIP</option>
<option value="tar">TAR</option>
<option value="gzip">GZIP</option>
<option value="bzip2">BZIP2</option>
</select>
<input type="submit" name="add_files" value="Submit" />
</form>
</div>
And then I'm passing it to the responsible controller action:
public function archiveAction()
{
if(isset($_POST["user_id"]) && isset($_POST["type_of_archive"]) && isset($_FILES['upload']))
{
$time = new DateTime();
if ($_POST['type_of_archive'] == 'zip')
{
Helper::zipFiles($_FILES['upload'],"./".$_SESSION['username']."/",$_SESSION['username']." - ".$time->format('Y-m-d H:i:s'));
}
}
}
The zipFiles function itself is below :
static public function zipFiles($files, $dir, $name)
{
$location = $dir.$filename.".zip";
$zip = new ZipArchive();
if ($zip->open($location, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$num_of_files = count($files['name']);
for($i = 0;$i<$num_of_files;$i++ )
{
$zip->addFile($files['tmp_name'][$i]);
}
$zip->close();
return $location;
}
The problem is that I'm not getting any errors. What I'm trying to do is create a zip file in a directory. All I'm getting is that my browser is downloading an empty file called archiveAction. Anything I'm missing here? If I keep retrying the script just hangs after a while.

This happens because you use $files['tmp_name'][$i]. If you print_r your $_FILES you will see that $files['tmp_name'][0] (for example) is just a file name without a path. So when you execute archiveAction script tries to find file $files['tmp_name'][$i] in a directory where it is (script) is run. Sure there's no such file, as it is stored in your /tmp or some other directory for temporary files.
So, you should either first copy your uploaded files (move_uploaded_file function) to some specific location, path to which you know, and create zip archive using these copied files and full path to them. For example, copy them to uploads folder of you site. And use:
$zip->addFile($_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $somefile_name);
Or you can find out path to your temporary files folder (check php.ini) and use:
$zip->addFile($temporary_path . $files['tmp_name'][$i]);

Related

Upload Multiple Files HTML5 / PHP

I'm trying to build a basic upload form to add multiple files to a folder, which is processed by PHP.
The HTML code I have is:
<form id="form" action="add-files-php.php" method="POST" enctype="multipart/form-data">
<div class="addSection">Files To Add:<br><input type="file" name="files[]" multiple /></div>
<div class="addSection"><input type="submit" name="submit" value="Add Files" /></div>
</form>
And the PHP to process is:
$file_path = "../a/files/article-files/$year/$month/";
foreach ($_FILES['files']['files'] as $file) {
move_uploaded_file($_FILES["file"]["name"],"$file_path");
}
I can run the PHP without any errors, but the files don't get added to the path folder.
Where am I going wrong with this?
I have a similar code actually in one of my projects. Try it.
foreach ($_FILES['files']['name'] as $f => $name) {
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path);
}
Look at the following page:
http://php.net/manual/en/function.move-uploaded-file.php
EDIT:
Nowhere in the code you provided, does it show that you actually give your file a filename, you simply refer to a path, rather than a path+filename+extension
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path . $name);
modifying my original code sample to be like the second one, should work.
Iterate the $_FILES['files']['error'] array and check if the files are actually uploaded to the server:
$dest_dir = "../a/files/article-files/$year/$month";
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
// The temporary filename of the file stored on the server
$tmp_name = $_FILES["files"]["tmp_name"][$key];
$name = basename($_FILES["files"]["name"][$key]);
// Handle possible failure of the move_uploaded_file() function, too!
if (! move_uploaded_file($tmp_name, "$dest_dir/$name")) {
trigger_error("Failed to move $tmp_name to $dest_dir/$name",
E_USER_WARNING);
}
} else {
// Handle upload error
trigger_error("Upload failed, key: $key, error: $error",
E_USER_WARNING);
}
}
The biggest issue with your code is that you are trying to move $_FILES['files']['name'] instead of $_FILES['files']['tmp_name']. The latter is a file name of temporary file uploaded into the temporary directory used for storing files when doing file upload.
P.S.
Using relative paths is error-prone. Consider using absolute paths with the help of a constant containing path to the project root, e.g.:
config.php
<?php
define('MY_PROJECT_ROOT', __DIR__);
upload.php
<?php
require_once '../some/path/to/project/root/config.php';
$dest_dir = MY_PROJECT_ROOT . "/a/files/article-files/$year/$month";

Trying to upload image to a folder and save its location in DB error

I keep getting this error and I do not know why.
Upload form
<?php
require_once 'processor/dbconfig.php';
if(isset($_POST['submit']))
{
if($_FILES['image']['name'])
{
$save_path="newimages"; // Folder where you wanna move the file.
$myname = strtolower($_FILES['image']['tmp_name']); //You are renaming the file here
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.$myname); // Move the uploaded file to the desired folder
}
$hl = $_POST['headline'];
$fd = $_POST['feed'];
$st = $_POST['story'];
$tp = $_POST['type'];
if($user->send($h1,$fd,$st,$tp,$save_path,$myname))
{
echo 'Success';
$user->redirect("input.php");
}
}
?>
<form enctype="multipart/form-data" method="post">
<input type="text" name="headline">
<input type="text" name="feed">
<textarea cols="15" id="comment" name="story" placeholder="Message" rows="10"></textarea>
<input type="text" name="type">
<input type="file" name="image">
<input type="submit" name="submit">
</form>
Here is my SEND function
public function send($hl,$fd,$st,$tp,$save_path,$myname)
{
try
{
$stmt = $this->db->prepare("
INSERT INTO news(headline,feed,story,type,folder,file)
VALUES(:headline, :feed, :story, :type, :foler, :file);
");
$stmt->bindparam(":headline", $hl);
$stmt->bindparam(":feed", $fd);
$stmt->bindparam(":story", $st);
$stmt->bindparam(":type", $tp);
$stmt->bindparam(":folder", $save_path);
$stmt->bindparam(":file", $myname);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
And finally, Here is my Error.
Warning: move_uploaded_file(newimages//var/tmp/phpyctf0k) [function.move-uploaded-file]: failed to open stream: No such file or directory in /nfs/c11/h05/mnt//domains/concept/html/input.php on line 12
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/var/tmp/phpyctf0K' to 'newimages//var/tmp/phpyctf0k' in /nfs/c11/h05/mnt//domains/concept/html/input.php on line 12
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Yes I did create a new folder named newimages as well.
so you're saying you've made a folder in the same relative directory of the current running php script called newimages, in which you want to upload this file. just to be absolutely clear, this is not an absolute path, and that's OK.
$save_path="newimages";
I think it needs a trailing slash, as it appears in your output, but not in your example code.
$save_path="newimages/";
on this line, you are making the whole path and filename to lowercase of the temporary file in your absolute path /var/tmp/phpyctf0k
$myname = strtolower($_FILES['image']['tmp_name']); //You are renaming the file here
so on this line, you are appending the local relative path newimages with the whole absolute path of the temp file /var/tmp/phpyctf0k, so this now indicates to the PHP interpreter that you intend to move a file to a directory that doesn't exist newimages/var/tmp/phpyctf0k
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.$myname); // Move the uploaded file to the desired folder
in order to fix it, you could use something like basename
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.basename($myname)); // Move the uploaded file to the desired folder
or perhaps $_FILES['image']['name'] as #Sean commented.
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.strtolower($_FILES['image']['name'])); // Move the uploaded file to the desired folder

Check if directory exists, make directory

I'm having a little trouble with this. Thought it'd be easier, but turning out to frustrate. All I'm trying to do is have a text field where I can type the name of a new directory, check if that directory exists, and if not create it. I have found about 50 other people with almost the exact same code, so thought I had it correct but I keep getting Directory exists as per the "if" statement.
Eventually I want to tie this into my file upload script.
Here is the insert.php
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="directory">Directory:</label>
<input value="<?php if ($_POST && $errors) {
echo htmlentities($_POST['directory'], ENT_COMPAT, 'UTF-8');
}?>" type="text" name="directory" id="directory" />
</p>
<p>
<input type="submit" name="insert" id="insert" value="insert" />
</p>
</form>
And here is the post.php
try {
if (isset($_POST['insert'])) {
$directory = $_POST['directory'];
$photo_destination = 'image_upload/';
$path = $photo_destination;
$new_path = $path . $directory;
$mode = 0755;
if(!is_dir($new_path)) {
echo "The Directory {$new_path} exists";
} else {
mkdir($new_path , 0777);
echo "The Directory {$new_path} was created";
}
}
}
Change this :
if(!is_dir($new_path)) {
echo "The Directory {$new_path} exists";
}
to this :
if(is_dir($new_path)) {
echo "The Directory {$new_path} exists";
}
Try and tell me the result :)
Instead of using is_dir in the if block you can use file_exists. Because file_exists is the function to check whether file exists or not. For the same you can also refer to http://php.net/manual/en/function.file-exists.php
Try
if( is_dir( $new_path ) ) {
echo "The Directory {$new_path} exists";
}
Let someone wants to create a sub-folder,
with a year name under /uploads folderthen he/she want to create
another sub-folder under an /uploads/<year_name_folder>/,
named project_number.
$yearfolder = date('y');
if (!file_exists('uploads/'.$yearfolder)) {
mkdir("uploads/".$yearfolder);
}
*// Folder named by year has been created.*
$project_number = Any Unique field ,Come from database or anywhere !
$target_directory = mkdir("uploads/".$yearfolder."/".$project_number);
*// project number wise folder also created.
// If project number is not unique do check like year folder. I think every project number is unique.*
$target_dir = "uploads/$yearfolder/$project_number/";
*//my target dir has created where my document or pic whatever will be uploaded.*
Now Upload ! Woo
$target_file = $target_dir.($_FILES["file"]["name"]);

convert upload file script to upload url

i have upload script which does the job for uploading in usual way like browse the file from computer and upload but i want to convert the existing script to upload from url.for example if i paste the url which is direct link of video file it should be uploaded to my server. i can use php copy method and feof to do the job but i want to do with my existing script as several other data are related to my uploading script i tried with above both method but its not working.
converting this code to accept remote url upload
<form enctype="multipart/form-data" id="form1" method="post" action="">
<p><label>Upload videos</label>
<input type="file" name="video">
<span>Only mp4 is accepted</span>
<input type="submit" value="Submit" class="button"></p>
if (!eregi(".mp4$",$_FILES['video']['name'])) {
die("Unavailable mp4 format");
}
$uri = save_file($_FILES['video'],array('mp4'));
function save_file($file) {
$allowed_ext = array('mp4');
$ext = $file['name'];
if (in_array($ext, $allowed_ext)) {
die('Sorry, the file type is incorrect:'.$file['name']);
}
$fname = date("H_i",time()).'_'.get_rand(3);
$dir = date("Ym",time());
$folder = 'uploads/userfiles/'.$dir;
$uri = $folder.'/'.$fname.'.'.$ext;
if (!is_dir($folder))
mkdir($folder, 0777);
if (copy($file['tmp_name'],$uri))
return $uri;
else {
return false;}}
?>
If you're getting a URL, you aren't getting a file upload so you can't just use a file upload script and wish it would work. Just use the copy() function to get the file from the URL and save it to your server.
You should use "http_get" to download files from another server.
$response = http_get($url);

move_uploaded_file() showing successful but not working

I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';

Categories