I am working on a simple thing that uploads files using PHP.
My form:
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type="file" name="file_upload">
<input type="submit" name="submit" value="Upload">
</form>
And PHP:
$id = '3';
if (isset($_POST['submit'])) {
$tmp_file = $_FILES['file_upload']['tmp_name'];
$file = basename($_FILES['file_upload']['name']);
$upload_dir = "uploads";
if (file_exists($upload_dir."/".$file)) {
die("File {$file} already exists in {$upload_dir} folder.");
}
if(move_uploaded_file($tmp_file, $upload_dir."/".$file)) {
$message = "File " . $file . " uploaded to " . $upload_dir;
echo $message;
} else {
# Code with message about error.
}
}
Files successfully uploads only in uploads folder. In that uploads folder, I have few other folders: 1, 2, 3 and so on.
My question: How to move files in a specific subfolder after upload? (Subfolder name — from variable id.) Thanks!
Efficient way to do this:
This method move file when it get uploaded.
if (!empty($post_array['IconURI'])) {
$IconURI_current_path = "./" . $post_array['IconURI'];
if (file_exists($IconURI_current_path)) {
// Desired folder structure
$structure = './uploads/' . $primary_key . "/";
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (is_dir($structure) || mkdir($structure, 0777, true)) {
$dir = './uploads/' . $primary_key . "/" . $post_array['IconURI'];
chmod("$IconURI_current_path", 0777);
if (copy("$IconURI_current_path", "$dir")) {
#unlink("$IconURI_current_path");
//rename IconURI from [ 9723d-632ac-e325b-db1b8-icon.jpg ]
$IconURI = "uploads/" . $primary_key . "/" . $post_array['IconURI'];
}
} else {
die('Failed to create folders...');
}
} else {
echo "Banner file does not exist";
}
}
the script also handle file permissions. some time due to directory or files permission file couldn't moved.
Can be used as callback function like in Grocery CRUD or other third party Plugins. i.e these plugins uploads files to their default directory and you some time need to move file to other specific directory.
Related
I'm attempting to create a plugin on wordpress and I need to upload multiple images to a specific folder on the server...
I currently have
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple="multiple">
<input type="submit" value="Upload">
</form>
And this is the code that reads and should upload the files...
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$name = $myFile["name"][$i];
$error_msg = $myFile["error"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $photo_dir."/".$name);
if ($success) {
echo $name ." uploaded<br>";
} else {
echo $error_msg;
}
}
}
Is there a way to get it to report an error - at the moment if the file name already exists then it jsut overwrites the old version...
When you do a upload of files PHP store the files in a temporary folder.
You have to move the file from temporary folder to the folder that you want to store the files.
Here is an example using your code:
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
// The folder that you want to store the file
$folderName = 'tmp/';
for ($i = 0; $i < $fileCount; $i++) {
$fileName = $myFile["name"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $folderName . $fileName);
if ($success) {
echo 'File ' . $fileName . ' uploaded!<br>';
}
}
}
Using move_uploaded_file("temp_location","new_location"), is there a way to upload files to the same directory as the file uploading script when specifying the "new_location" or does it always have to be uploaded in another specified folder within the script's directory?
It's possible, as long as you have the permission to write in that specific directory:
/* new_file can be any path ... */
$new_file = __DIR__ . '/' . $_FILES['file']['name'];
if ( is_writable(dirname($new_file)) ) {
move_upload_file( $_FILES['file']['tmp_name'], $new_file );
} else {
throw new Exception( 'File upload failed: Directory is not writable.' );
}
You can upload file in script directory as following code .
HTML code :-
<input type="file" name="file" id="file">
PHP code:-
move_uploaded_file($_FILES["file"]["tmp_name"], "". $_FILES["file"]["name"]);
But a problem in the case of permission.
You could use dirname and __FILE__ for that:
move_uploaded_file($tmpName, dirname(__FILE__) . '/' . $newName);
I'm trying to upload a file and rename it if it already exists.
The way I want i to do is that when det same file uploads the name just adds 1, then 2, then 3, and so on.
Example: If file "file" exists, the new file should be "file1", then the next one "file2".
I've seen some examples on the net, but nothing that I could see fit to my code (noob)
This is my code now:
$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {die("You can only upload PDF files");}
// Checking filesize
if ($_FILES['dok']['size']>1048576) {die("The file is too big. Max size is 1MB");}
// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}
//If user don't have his own catalogue
else {
// Creates new catalogue then move the file in place
mkdir("filer/".$id);
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname); } }
Can somebody help me where I can put in code that solves this problem?
Big thank you!
$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf") {
die("You can only upload PDF files");
}
// Checking filesize
if ($_FILES['dok']['size']>1048576) {
die("The file is too big. Max size is 1MB");
}
if(!is_dir("filer/".$id."/")) {
mkdir("filer/".$id);
}
$rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
$extension = pathinfo($fname, PATHINFO_EXTENSION );
$counter = 0;
while(file_exists("filer/".$id."/".$fname)) {
$fname = $rawBaseName . $counter . '.' . $extension;
$counter++;
};
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);
}
But don't forget to secure your script (eg see comment of Marc B above) and maybe you could optimize some more ;-)
so if folder exists:
file_exists("filer/".$id."/")
check if file exists
file_exists("filer/".$id."/".$fname)
and then if it does,
$fname = $fname . "(1)" // or some appending string
So in the end you change your code to:
// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
while (file_exists("filer/".$id."/".$fname)) // Now a while loop
$fname = "copy-" . $fname; // Prepending "copy-" to avoid breaking extensions
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}
//If user don't have his own catalogue
else {
<form action="test.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
<?php
$id = $_SESSION['id'];
$fname = $_FILES['fileToUpload']['name'];
// Checking filesize
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/".$id."/".$fname)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}else {
echo "Sorry, there was an error uploading your file.";
}
// Check file size$
if ($_FILES['fileToUpload']['size']>1048576) {
die("The file is too big. Max size is 1MB");
}
if(!is_dir("uploads/".$id."/")) {
mkdir("uploads/".$id);
}
$rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
$extension = pathinfo($fname, PATHINFO_EXTENSION );
$counter = 0;
while(file_exists("uploads/".$id."/".$fname)) {
$fname = $rawBaseName . $counter . '.' . $extension;
$counter++;
};
move_uploaded_file($_FILES['fileToUpload'] ['tmp_name'],"uploads/".$id."/".$fname);
?>
I've been searching for the solution but I can't find the answer.
I created a image upload form. It runs with ajaxform plugin. But still it doesn't upload to the directory.
The error_log says
move_uploaded_file() Unable to move file from [tmp] to [dir].
Then on the front end it says Upload Complete. But when the file is called, it doesn't exist.
HTML CODE:
<div class="imgupload hidden">
<form id="profpicform" action="" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="profpic">
<input type="submit" value="Submit File">
</form>
<div class="imguploadStatus">
<div class="imguploadProgress">
<div class="imguploadProgressBar"></div>
<div class="imguploadProgressPercent">0%</div>
</div>
<div class="imguploadMsg"></div>
</div>
<div class="imgpreview"></div>
</div>
JS:
var options = {
beforeSend: function()
{
$(".imguploadProgress").show();
$(".imguploadProgressBar").width('0%');
$(".imguploadMsg").html("");
$(".imguploadProgressPercent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$(".imguploadProgressBar").width(percentComplete+'%');
$(".imguploadProgressPercent").html(percentComplete+'%');
},
success: function()
{
$(".imguploadProgressBar").width('100%');
$(".imguploadProgressPercent").html('100%');
},
complete: function(response)
{
alert('Complecion');
},
error: function()
{
$(".imguploadMsg").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#profpicform").ajaxForm(options);
SEVER SIDE:
$output_dir = home_url()."/path/to/dir/";
if(isset($_FILES["profpic"])){
if ($_FILES["profpic"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}else{
move_uploaded_file($_FILES["profpic"]["tmp_name"],$output_dir. $_FILES["profpic"]["name"]);
if(get_user_meta($_SESSION['userid'], 'user_profile_picture')==""){
add_user_meta($_SESSION['userid'], 'user_profile_picture', $_FILES['profpic']);
}else{
update_user_meta($_SESSION['userid'], 'user_profile_picture', $_FILES['profpic']);
}
echo "Uploaded File :".$_FILES["profpic"]["name"];
}
}
They are only found in one PHP file. Folder permission for the directory is 777.
Try this:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . basename( $_FILES["profpic"]["name"]);
#move_uploaded_file($_FILES['profpic']['tmp_name'], $target_path)
Look into the below case:
$file_tmp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_destination = 'upload/' . $file_name;
move_uploaded_file($file_tmp, $file_destination);
In the above code snippet, I have used $_FILES array with the name of the input field that is “file” to get the name and temporary name of the uploaded file.
Check the scenario that cause the error:
Make sure you have created folder where you want to move your file.
Check for the folder permission, is it writable or not. Use chmod() to modify permission.
See if your target path URL is properly created or not. You can use dirname(__FILE__) to get the absolute path. To get current working directory, use getcwd().
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path = $destination_path . 'images/'. basename( $_FILES["profpic"]["name"]);
move_uploaded_file($_FILES['profpic']['tmp_name'], $target_path);
getcwd() : getting current working directory path from the root.
'images/' : is the directory where you want to save your file.
I have a problem to find out the relative path to
upload the images to other directories
target directory
htdocs/dt3/tadi/adm/dim/dim_images/tadi_user_images/
source directory
htdocs/dt3/tadi/adm/cbt/uploadfile.php
uploadfile.php
<html>
<form method="post"enctype="multipart/form-data">
<input type="file" name="fileimg1" ><input type="submit" name="upload">
</form>
</html>
<?php
$dirname = "/dt3/tadi/adm/dim/dim_images/tadi_user_images/";
$of = $_FILES['fileimg1']['name'];
$ext = pathinfo($of, PATHINFO_EXTENSION);
$changename3 = time() * 24 * 60;
$image_name3 = "timage_" . $changename3 . "." . $ext;
$final_pathdir = $dirname . $image_name3;
$suc = move_uploaded_file($_FILES['fileimg1']['tmp_name'], $final_pathdir);
if ($suc > 0)
{
echo "Image uploaded successfully";
}
else
{
echo "Error : " . $_FILES['filimg1']['error'];
}
?>
I tried out some of the paths, I didnt got any solution for that.
How can I upload images to that path?
htdocs/dt3/tadi/adm/dim/dim_images/tadi_user_images/
With relative path only.
I believe you could do
$dirname = dirname(__FILE__)."/../dim/dim_images/tadi_user_images/"