This is my html form
<form action="index.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
This is my index.php file
<?php
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
echo"$error_codes[$error]";
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$_FILES["userfile"]["name"][$key]
) or die("Problems with upload");
}
}
?>
**The code is working properly. But, What I really need is to change the name of the 1st uploaded file to birthcertificate and the name of the 2nd uploaded file into NIC. **
**Example : If I upload a file named 123 or abc (whatever the name) the 1st file's name should be birthcertificate and the 2nd file's name should be NIC. **
There are probably lots of ways to do this.
I thought that making a list of the new file names
might be the way to go.
<?php
// Make a list of the new file names
$newFileNames = ['birthcertificate', 'NIC'];
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
echo"$error_codes[$error]";
// Grab new file name
$newFileName = array_shift($newFileNames);
// Make sure we actually got one
if ( $newFileName ) {
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$newFileName)
or die("Problems with upload");
}
}
}
move_uploaded_file(file, location);
You can use file and new name in location parameter like this:
$newname = "yourimg.png";
enter code here
move_uploaded_file($_FILES["userfile"]["tmp_name"][$key], "your location" . $newname);
This is the basic way of renaming, make changes to the loop for renaming both files. If you only upload 2 files at a time, you can use the array index for your logic.
You can rename a file:
Instead of below code inside foreach you have shared
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$_FILES["userfile"]["name"][$key]
) or die("Problems with upload");
You can use:
$temp = explode(".", $_FILES["userfile"]["name"]);
$newfilename = 'birthcertificate' . '.' . end($temp);
move_uploaded_file($_FILES["userfile"]["tmp_name"], $newfilename) or die("Problems with upload");
Try giving the file seperate names, in PHP you can receive them and make in one array if you need
You can also refer to this link:
How to rename uploaded file before saving it into a directory?
Related
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";
I'm using a form and a loop to upload multiple image files directly to the file server, but I'm getting a false result with the move_uploaded_file function.
Upload Form:
<body>
<p>
<form action='uploadform.php' method='post' enctype='multipart/form-data'>
Select the files you would like to upload.
<input type='file' name='fileToUpload[]' id='fileToUpload' mozdirectory webkitdirectory directory multiple />
<input type='submit' value='Upload Image' name='submit'>
</form><br>
The files will be uploaded to a folder named '".$_SESSION['filename']."'.<br>
</p>
</body>
Multiple file uploading loop (uploadform.php:
if (isset($_POST["submit"])) {
foreach ($_FILES['fileToUpload']['name'] as $i => $name) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"][$i]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (strlen($_FILES['fileToUpload']['name'][$i]) > 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["name"][$i], $target_file)) {
echo basename($_FILES["fileToUpload"]["name"][$i]);
}
else {
echo "Error! File basename: ".basename($_FILES["fileToUpload"]["name"][$i])."<br>";
}
$count++;
}
}
}
When uploading one or multiple files with the form, it goes to the else statement echoing the "ERROR" string.
The Apache Error Log comes up blank, so I have no clue what's wrong with the code.
I tried echoing the variables used in the loop ($_FILES["fileToUpload"]["name"][$i], $target_file and $imageFileType) but these seem to be fine.
I would put entire foreach loop in try-catch block and see what, if any Exception occurs:
try{
// your foreach loop here:
}
catch(\Exception $e)
{
echo $e->getMessage();
}
The $_FILES["fileToUpload"]["name"][$i] variable was not the one that the loop was supposed to use.
By changing all instances of $_FILES["fileToUpload"]["name"][$i] to $name (which is $_FILES["fileToUpload"]["tmp_name"][$i]) the error was gone.
Here is my html code for uploading multiple files in php. I want to store the image name in the database and upload the file in folder:
<input name="userfile[]" type="file" multiple="multiple"/><br />
<input name="userfile[]" type="file" multiple="multiple"/><br />
if(isset($_FILES['file']['tmp_name'])){
$num_files = count($_FILES['file']['tmp_name']);
for($i=0; $i < $num_files;$i++){
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i])){
$messages[] = 'No file uploaded';
}
else{
if (file_exists("images/Locations" . $_FILES["file"]["name"]))
{
}
else
{
if ($_FILES["file"]["error"] > 0){
$file = fopen("test.txt","w");
echo fwrite($file,"Not uploaded");
fclose($file);
}
else{
move_uploaded_file($_FILES['file']['tmp_name'][$i],"images/Locations");
}
}
}
}
}
So can anyone tell me where I am making a mistake. I want to store name of image into database so how can i do that when i am writing the error it displays error code 0, so what is error code 0 in it.
The mistakes that I found at the first sight was:
<input name="userfile[]" type="file" multiple/><br />
This should there only once because of the multiple attribute it forms multi-dimensional array according to the number of images selected.
Change your if-conditional to
if(count($_FILES['userfile']['name']> 0)){
That should give you a start. Let me know if you find any problems.
Your input file type name is "userfile"
And you are using in the PHP script as
$_FILES['file']['tmp_name']
And here is the problem.
Change them accordingly to use proper input names on your script processing the upload.
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"]);
I need customers to upload files to my website and I want to gather their name or company name and attach it to the file name or create a folder on the server with that as the name so we can keep the files organized. Using PHP to upload file
PHP:>>
if(isset($_POST['submit'])){
$target = "upload/";
$file_name = $_FILES['file']['name'];
$tmp_dir = $_FILES ['file']['tmp_name'];
try{
if(!preg_match('/(jpe?g|psd|ai|eps|zip|rar|tif?f|pdf)$/i', $file_name))
{
throw new Exception("Wrong File Type");
exit;
}
move_uploaded_file($tmp_dir, $target . $file_name);
$status = true;
}
catch (Exception $e)
{
$fail = true;
}
}
Other PHPw/form:>>
<form enctype="multipart/form-data" action="" method="post">
input type="hidden" name="MAX_FILE_SIZE" value="1073741824" />
label for="file">Choose File to Upload </label> <br />input name="file" type="file" id="file" size="50" maxlength="50" /><br />
input type="submit" name="submit" value="Upload" />
php
if(isset($status)) {
$yay = "alert-success";
echo "<div class=\"$yay\">
<br/>
<h2>Thank You!</h2>
<p>File Upload Successful!</p></div>";
}
if(isset($fail)) {
$boo = "alert-error";
echo "<div class=\"$boo\">
<br/>
<h2>Sorry...</h2>
<p>There was a problem uploading the file.</p><br/><p>Please make sure that you are trying to upload a file that is less than 50mb and an acceptable file type.</p></div>";
}
Look at mkdir(), assuming the user PHP is running as has appropriate permissions, you can simply make a directory inside of uploads/.
After that, you can modify $file_name to contain some of the other posted variables that you mentioned you will add. Just take care to ensure those variables contain only expected characters.
Do your customers need to Log into your site before they upload? If that's the case perhaps you can store/grab $_SESSION information regarding their company and name. You could then append that info to the $file_name or the $target directory.
the mkdir() idea below this looks like it will probably work, but have you considered what would happen if a user entered someone else's name, had someone else's name, or entered someone else's company?
use this code on the top of the page
$path = dirname( __FILE__ );
$slash = '/';
(stristr( $path, $slash )) ? '' : $slash = '\\';
define( 'BASE_DIR', $path . $slash );
& use below code after inside if below exit;}
$folder = $file_name; // folder name
$dirPath = BASE_DIR . $folder; // folder path
$target = #mkdir( $dirPath, 0777 );
move_uploaded_file($tmp_dir, $target . $file_name);
here is your code as it is
I figured it out, I just made a input for the name ant attached it to the file name.