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";
Related
I have a file input selection as follows in a form which I send data from using the POST Method.
<input type="file" name="inputFile">
I would like to validate that the user has chosen a file and would like to check whether the file is an image file (png,jpg)
I am also getting stuck because a line in my code is generating an error. Why?
'Array key 'inputFile' is undefined'
if (isset($_POST['submit'])) {
$file = $_FILES['inputFile']; //THIS LINE IS GENERATING AN ERROR
}
see : https://www.php.net/manual/en/features.file-upload.post-method.php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
see also:
Undefined Array Key error when uploading image on php
it would appear you are looking for $_FILES["inputFile"]["name"] - goodluck
You can use something like:
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
And specify the formats you want without PHP
I have a problem loading the file to the server in PHP and HTML using move_uploaded_file () when I put PHP files in this way http://mydomin.com/uploadfile.php succeed the process and if this way http://mydomin.com/uploadfiles/uploadfile.php The the process fails
code php
<?php
if (isset($_FILES['image'])) {
$idApp = uniqid();
$uploadDir = '../images/';
$uploadedFile = $uploadDir . $idApp . ".jpg";
if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadedFile)) {
echo"Success: ".$_FILES['image']['tmp_name']. $uploadedFile;
} else {
echo"error 2";
}
} else {
echo"error 3";
}
?>
code html
<form action="add.php" method="POST" enctype="multipart/form-data">
<input type='file' name='image' id='image'>
<div align='center''><input type='submit' id='myButton' value='add'></div>";
</form>
check your upload path
$uploadDir = '../images/';
Try to use this path './images/' or best use absolute path.
check your script location by using
var_dump(__DIR__)
this will show you where is your .php file is ( also called as absolute path ). Thus simply you can see where you made a mistake to assign a folder for file uploading(image in your case ).
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?
I have a form where I allow the user to upload files. I just changed the post processing to a post-redirect-get since the user enters other information as well. I noticed that the global $_FILE is visible to the redirect.php but is lost after redirecting back to the input form. I attempted to save the $_FILE array, but it appears that the temp files are removed with the post-redirect-get. Is there any way to tell the server to preserve the temp files when leaving the redirect.php so I can process them when I see fit? Thanks in advance.
User Form:
<input type="file" name="file[]" id="userfiles" size='1px' multiple onChange="makeFileList();" />
Redirect File:
if (isset($_FILES)){
$_SESSION['post-files'] = $_FILES;
}
header("Location: /back/to/input/form.php");
In the end, the simplist solution was to process the temp files in the redirect.php and store the files in my own temp location. I then can deal with them once back in my processing form. For anyone who follows, this is what I did...
if (isset($_FILES)){
$_SESSION['post-files'] = $_FILES;
$i=0;
foreach ($_SESSION['post-files']['file']['name'] as $filename){
// get the file to upload
$fromfile=$_SESSION['post-files']['file']['tmp_name'][$i];
// get just the filename
$filename = pathinfo($fromfile, PATHINFO_FILENAME) . '.' . pathinfo ($fromfile, PATHINFO_EXTENSION);
// give it a new path
$tofile = "/some/temp/path/". $filename;
// store the new temp location
$_SESSION['post-files']['file']['tmp_name'][$i] = $tofile;
// move the files to a temp location
if (!is_dir(pathinfo($tofile,PATHINFO_DIRNAME))) {
mkdir(pathinfo($tofile,PATHINFO_DIRNAME), 0777, true);
}
move_uploaded_file($fromfile,$tofile);
}
}
You might be able to pass an encoded copy of the file(s) into the session.
Something like...
$tempImages = array();
foreach($_FILES as $file)
{
$tempImages[] = base64_encode(file_get_contents($file['tmp_name']));
}
$_SESSION['post-files'] = serialize($tempImages);
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);