if(isset($_POST['submit'])){
if(!empty($_FILES['files']['name'])){
$Zip = new ZipArchive();
$Zip->open('uploads.zip', ZIPARCHIVE::CREATE);
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
$Zip->close();
}
else {
echo "no files selected";
}
}
What is wrong here ? I have just watched a tutorial of creating archives and adding files in it but it is not working ...I am using php 5.4 . It is not even giving me any error. Can any one please guide me what i am doing wrong here.
Below is the form
<form action="" method="POST" enctype="multipart/form-data">
<label>Select files to upload</label>
<input type="file" name="files">
<input type="submit" name="submit" value="Add to archieve">
</form>
These lines don't make any sense
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
At that point in the code you posted, no uploaded files have been moved to a uploads/ directory, and looping though the $_FILES["files"] element - which is an associative array of various values, only one of which is the actual file name - and adding each value to the ZIP as a file, is nonsensical. - You should read the PHP docs relating to file uploading. It's clear you don't really know how PHP handles file uploads yet, which you should learn before attempting things like this.
One solution would be to move the uploaded file to the uploads/ directory using move_uploaded_file, but seeing as you are only really using the file there to add it to the archive, that step is pretty redundant; you can just add it directly from the temp location. First you need to verify it, though, which you can do with the is_uploaded_file function.
// Make sure the file is valid. (Security!)
if (is_uploaded_file($_FILES["files"]["tmp_name"])) {
// Add the file to the archive directly from it's
// temporary location. Pass the real name of the file
// as the second param, or the temporary name will be
// the one used inside the archive.
$Zip->addFile($_FILES["files"]["tmp_name"], $_FILES["files"]["name"]);
$Zip->close();
// Remove the temporary file. Always a good move when
// uploaded files are not moved to a new location.
// Make sure this happens AFTER the archive is closed.
unlink($_FILES["files"]["tmp_name"]);
}
Related
I have a form for users to upload files into the folder.
HTML and PHP codes are as below:
<form enctype="multipart/form-data" method="post" action="test.php">
<input type="text" name="name"/><br/>
<input type="file" name="photo" /><br/>
<input type="submit"/>
</form>
<?php //test.php
move_uploaded_file($_FILES["photo"]["tmp_name"], "testFolder/".$_POST["name"]);
?>
The upload form works well, and uploaded files are in the folder testFolder/ .
Now I want to use glob() function to get all file names in the folder.
<?php
foreach(glob("testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
However, it doesn't echo anything.
The glob() function works well on other folders, which contains existing files, not uploaded files.
But why doesn't it work on this folder with uploaded files ?
Possbile wildcard extension could be the issue.
It may be that glob does not allow wildcard extensions, i dont see any mention of this in the docs. Have you tried a directory iterator?
$dir = new DirectoryIterator(__DIR__.'/testFolder);
foreach ($dir as $file) {
echo $file->getFilename();
}
UPDATE: THE PATH IS NOT THE ISSUE
You are using a relative file path, therefore glob probably isn't finding the directory you are trying to search for.
Either the script calling the function needs to sit inside the parent directory of 'testFolder' or you need to use an absolute path like so.
<?php
foreach(glob("/absolute/path/to/testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
If you do want to use a relative path you could do the following:
<?php
//__DIR__ is a PHP super constant that will get the absolute directory path of the script being ran
// .. = relative, go up a folder level
foreach(glob(__DIR__."/../testFolder/*.*") as $file) {
echo $file."<br/>";
}
?>
Obviously the paths above are examples but should get you on the right track.
Hope this helps
Because I didn't give the extension for the uploaded file, that's why glob("testFolder/*.*") doesn't get anything.
Two solutions:
Give uploaded files an extension.
$ext = strrchr($_FILES["photo"]["name"], ".");
move_uploaded_file($_FILES["photo"]["tmp_name"],
"testFolder/".$_POST["name"].$ext);
Then, glob("testFolder/*.*") will be able to get these uploaded files with an extension.
Just change glob("testFolder/*.*") to be glob("testFolder/*")
I am completely a novice in all this ...
I have created a Social Networking project in which there is a module which allows user to upload photos..
I have hosted this project in my college server
I access that server using bitvise client with my server credentials.
My problem is i don't know how to setup upload mechanism for remote server ... In my localhost i simply use
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
function but i don't know how to do this for remote server ...
I tried FTP by looking at some tutorials but that didn't worked for me.
In my project structure there is a directory
users/user_id (diff for all users)/photos
here i want to place the uploaded files....
A proper description with example and proper functioning might be very helpful for me.... Thank you
EDIT:
Below is my code.
Photos.php
<form class="input-group-btn" method="post" action="editPhotos.php"enctype="multipart/form-data" id="myForm">
<input type="file" name="file" id="imgInp">
<button type="submit" class="btn btn-primary" name="form-submit">Done</button>
</form>
editPhotos.php
if( isset($_POST['form-submit']) ){
$target_file = "users/".$email."/pictures/Photos/" . basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$img =str_replace(" ", "",basename($_FILES["file"]["name"]));
rename($target_file, "users/".$email."/pictures/Photos/".$img);
header('Refresh: 1; url=Photos.php?user='.$email);
}
Small tutorial how to upload file.
For sure, you need correct encryption and file's type in your form (ommited other fields, to clear example):
form.html
< form action="upload.php" method="post" enctype="multipart/form-data">< /form>
< input name="test" type=file>
upload.php
In $_FILES you have all data of uploaded file. In given example, we have field named test.
Advice, to always first check error $_FILES['test']['error'] - the values you can find in here.
If this is correct, then prepare upload path. Some advices:
remember that if you use original filename ($_FILES['test']['name']), then is User upload second file, with same name, you will need overwrite file or ignore upload. Other way, is to save data to database and generate temporary name form him.
destination path(target_file) - regardless if upload folder is in the same catalog, you should always use global path, as good practice. You can use DIR for that.
don't use in path data, like email - is you have project, and want give opportunity to change email in configuration, what you will do with files? Better save user to Database and use his ID as key.
If you have path, then you simply need only use of move_uploaded_file, but remember to check result, as it not always will return true. You can have error, when you don't have permissions to destination folder (you'll need debug this).
I see that you, first upload file, then rename (then you should check, if rename was success). Don't extends this process, if it not necessary. Upload file for final path and name.
Example of code (I this rattle off)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$fileName = basename($_FILES["file"]["name"]);
$fileName = str_replace(" ", "", $fileName);
$target_file = sprintf(__DIR__ . "/users/%s/pictures/Photos/%s", $email, $fileName);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
// File was uploaded
header('Refresh: 1; url=Photos.php?user=' . $email);
} else {
// File was not uploaded;
throw new \Exception('File was not uploaded. Check warnings.');
}
}
Used other method to check, if this is POST
use method sprintf, for better code quality
checked effect of move_uploaded_file
use global path for destination file
Below code is risky in live environment, please use cautiously
Use a relative path to the uploads folder. For example, if your uploads folder is placed outside your current folder. Then
$PATH = '/absolute/example/path/to/uploads';//from config file
$target_file = "$PATH/file_name";
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
The above code will work both in local and remote server.
Other checks are below:
Check for errors while uploading file in server
To enable error handling use below code in your upload logic:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Another important note is to make uploads folder writable otherwise file upload wont work.
I want to upload multiple files to the server.
As far as I can see files are not writable.
What can I do so my code can actually work and upload files.
PHP:
if(isset($_FILES ['uploaded_files']))
{
foreach($_FILES['uploaded_files']['name'] as $key=>$value)
{
if(is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES['uploaded_files']['error'][$key] == 0)
{
$filename = $_FILES['uploaded_files']['name'][$key];
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
{
//code
}
else
{
die ('There was a problem uploading the pictures.');
}
}
else
{
die ('There is a problem with the uploading system.');
}
}
}
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" id="input_clone_id" name="input_clone_id" value="'.$row['id'].'"/>
<input type="hidden" id="input_clone_var" name="input_clone_var" value="V"/>
<input type="file" name="uploaded_files[]" id="input_clone" multiple="multiple" /><br />
<input type="submit" style="margin-left:0" value="Upload Files" />
</form>
I see two problems with this. The first is a security issue and the second is probably what is causing your problem
You have a security problem here:
$filename = $_FILES['uploaded_files']['name'][$key];
...
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
...
Problem a: Since $filename comes from the $_FILES array, it CANNOT be trusted. The user told your site what the name of their file was and put it there. They could feed you some bogus filename that could cause your script to fail in interesting ways. You need to sanitize that filename before using it in any way.
Problem b: By allowing the user to specify the filename, they could potentially overwrite other files in your "images/gallery" directory simply by specifying a conflicting filename. The way to avoid this is to use a database, generate a unique identifier for the uploaded file, store the file under that unique name, and in the database keep a record of the original filename and other information. That way you always know what the original filename was and you don't have the chance of someone trying to overwrite files in that directory.
Writing problem:*
Your "check for writable" statement is wrong. The filename that comes back is the one that the user used when submitting. This will not point to any point on your filesystem...it points to a spot on theirs (sometimes) which you cannot see. What you need to check is that your "../images/gallery" directory is writable rather than $filename. If that fails, you need to do either "chmod -R 777 gallery" while in the images folder if you have command line access or give it world write access through whatever FTP client you are using if you are using FTP to talk to your server.
So, what you should have instead for that check is:
if (is_writable("../images/gallery")) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
After doing that, if your script comes back and says "the file is writable", it should have been able to copy the file into your images/gallery folder (remember to not use the name of the file the user gave you). If not, perhaps you don't have permissions to move uploaded files.
As for the location of uploaded files, I think sometimes they are deleted after the script execution ends sometimes, but if not, you can echo the 'tmp_name' of the file and if you go to that directory you should find it sitting there. That would be just a verification test to make sure the file was actually getting to your server. So long as you have write permissions (that what chmod 777 does) on the directory you are moving the uploaded file to, you should be able to copy it there.
You are checking to see if a file that you recently uploaded, but not yet saved is writable, I don't think such a file will ever be writable.
Better remove that if, or just check if the folder you are uploading to is writable.
Other than that, I checked your code and it works.
I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);
So I want to:
upload a csv file which will contain a list of student numbers, one to each line (392232, per line).
populate an array with the student numbers (as i already have a process in place of looking up ids from an array of student numbers and storing etc if they were to add students manually)
I have been lookin at a tutorial found here.
however I am slightly confused with this:
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){...
where does he establish 'tmp_name' from?
anyway, if somebody could explain how I should be going about this I would appreciate the help.
many thanks,
EDIT: added progress of where it is not working.
if(isset($_POST['csv_submit'])){
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//upload directory
$upload_dir = "/ece70141/csv_files/";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
// GETTING THE ERROR BELOW.
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
print_r($_FILES['csv_file']);
//delete csv file
unlink($file_path);
}
}
$_FILES is a magic superglobal similar to $_POST. It's an array of every file that's been uploaded in the last request, and where that file is stored (tmp_name).
tmp_name is basically generated by the web server to let PHP know where they've stored the file.
You have the following items available to you in each element of the $_FILES array:
name (Original Name of the file)
type (MIME Type of the file, ie. text/plain)
tmp_name (Path to the uploaded files' temporary location)
error (Error occurred when uploading, 0 when no error)
size (Size of the uploaded file, in bytes)
From what I can see in your code, this will work perfectly fine and as discussed in comments, I think the issue lies in your HTML.
The tutorial that you linked to has an incorrect <form ..> tag definition. For file uploads, you're required to set the enctype attribute, below is what it should look like:
<form action="" method="post" enctype="multipart/form-data">