I am trying to upload multiple images into the folder using php . The code can print out the file names which means I get the files but now it does not upload them and I get no error : below is my code
<?php
$target = "image_uploads/";
if(isset($_FILES['FILE_NAME'])){
foreach($_FILES['FILE_NAME']['tmp_name']as $key => $error ){
print_r($key);
$file_upload = $key.$_FILES['FILE_NAME']['name'][$key];
#print image names
echo $file_upload.'</br>';
move_uploaded_file($file_upload,$target);
}
}
?>
In target you have to give the file name too. Please use the code below,
$target = "image_uploads/";
if(isset($_FILES['FILE_NAME'])){
foreach($_FILES['FILE_NAME']['tmp_name'] as $key => $error ){
print_r($key);
$file_upload = $key.$_FILES['FILE_NAME']['name'][$key];
print image names
echo $file_upload.'</br>';
move_uploaded_file($file_upload,$target.$_FILES['FILE_NAME']['name']);
}
}
I think the problem is in the foreach loop.
foreach ($_FILES['FILE_NAME']['tmp_name'] as $key => $val) {
// this loops through the tmp_name of $_FILES['FILE_NAME']
// which is a string
}
I think you meant something like:
foreach ($_FILES as $index => $fileArray) {
$tmpName = $fileArray['tmp_name'];
echo "File at key $index is temporarily uploaded at $tmpName";
}
The code above will loop through all uploaded files and print it's current filename.
It might happen that your target folder is not writable.
I also think, that the cause of which you're not getting errors is, that you have the following:
print_r($key);
Yous should have:
print_r($error);
There can be multiple reasons for this :
The target folder must exist before trying to move the file from temp location to the target and must also be writable
the move_uploaded_file takes the second argument as the file name followed by the directory name, so it can be something like : target folder/user.file.name.ext
If you are uploading multiple files, then the $_FILES must be accessed as shown in the link : http://php.net/manual/en/features.file-upload.multiple.php
for the php error messages that you may encounter, here is a list : http://php.net/manual/en/features.file-upload.errors.php
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 have 100 files and I am scanning them and picking the correct file out of them.
I am using the following code:
$dir = 'myDir';
$files1 = scandir($dir);
$scanned_directory = array_diff($files1, array('..', '.'));
foreach ($scanned_directory as $key => $value) {
$onlyname=explode(".", $value);
if($onlyname[0]== $name){
// echo "file found";
break;
}else{
//echo "<h2>Not Found. Please Try Later</h2>";
}
}
The problem with this is that if the file is the 10th file I get 9x not found, before I get the file found message.
What is the proper way to display error message if no file is found?
I simplified your code a bit.
First of all I get all files from your directory into an array with glob(). Then I simply grab all files which have the name $name with preg_grep() and check with count() if there is at least 1 file with that specific name.
<?php
$dir = "myDir";
$files = glob($dir . "/*.*");
if(count(preg_grep("/^$name\..*$/", array_map("basename", $files))) > 0)
echo "file found";
else
echo "<h2>Not Found. Please Try Later</h2>";
?>
In a file called docs.php I have made the following code to display all the files inside uploads folder
The foreach() loops all the files there stored in a view of the website and has an hyperlink that let it be open in the browser (in my model file it has restriction's to only pds, png or jpg files)
What i'm not able to do is inside the foreach() loop for every iteration is display some sort of hyperlink (example: Delete me!) that permits the user to click and delete only that particular file physical from the server, the others not clicked must remain visible.
My php code inside a view to the forloop() is:
<?php
$files=\yii\helpers\FileHelper::findFiles('uploads/', ['except'=>['*.DS_Store']]);
if (isset($files[0])) {
foreach ($files as $index => $file) {
$nameFile = substr($file, strrpos($file, '/') + 1);
echo Html::a($nameFile, Url::base().'/uploads/'.$nameFile) . "<br/>" . "<br/>" ; // render do ficheiro no browser
}
} else {
echo "There are no files available for download.";
}
?>
As i assume you have concept of FileHelper, but to delete file you have to use php native function unlink(filePath). unlink()
i have an application that is used to edit .txt files. the application is made up of 3 parts
Displays contents of a folder with the files to be edited(each file is a link when clicked it opens on edit mode).
writing in to a file.
saving to file.
part 2 and 3 I have completed using fopen and fwrite functions that wasn't too hard. the part that i need help is part one currently I open the file by inputing its location and file name like so in the php file where i have the display function and save function:
$relPath = 'file_to_edit.txt';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath ! ");
but what i want is for the file to open in edit mode when clicked instead of typing in the files name every time.
$directory = 'folder_name';
if ($handle = opendir($directory. '/')){
echo 'Lookong inside \''.$directory.'\'<br><br>';
while ($file = readdir($handle)) {
if($file !='.' && $file!='..'){
echo '<a href="'.$directory.'/'.$file.'">'.$file.'<a><br>';
}
}
}
this is the code that ti use to display the list of files that are in a specified folder.
Can anyone give me some pointers how I can achieve this ? any help will be greatly appreciated.
To get content of file use file_get_contents();
To put content of file use file_put_contents(); with FILE_APPEND flag for editing.
To recieve list of files in directory you can use DirectoryIterator
Example:
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
If you don't want to put filenames you can put read files once put in db assign ids to them and use links with id param. The other solution is to store files in session array and assign keys for them. When you want to get a file you just need to provide key instead of whole filename and path.
Example with $_SESSION
$file_arr = array();
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
$file_arr[] = array("path" => $fileInfo->getPathname(), 'name' => $fileInfo->getFilename());
}
$_SESSION['files'] = $file_arr;
then in view you can use
foreach($_SESSION['files'] as $k=>$file)
{
echo "<a href='edit.php?f=".$k."'>'.$file['name'].'</a>";
}
and edit.php
$file = (int)$_GET['f'];
if(array_key_exits($file, $_SESSION['files'])
{
$fileInfo = $_SESSION[$file'];
//in file info you have now $fileInfo['path'] $fileInfo['name']
}
I post a file by HTML and I want to move it but it always return value false.
here's my code :
$fileName = $_FILES['atc']['name'];
$fileTmp = $_FILES['atc']['tmp_name'];
$newDir = "/home/goes/attachments/" . $fileName;
$a = move_uploaded_file($fileTmp, $newDir);
if ($a==true){
echo "true";
}
else{
echo "false";
}
The destination folder may not be have write permission
Check the content of all of your variables, see if they contain anything (good)
Check if the directory where you want to place the files exists, and is writeable by the webserver (or whoever runs the PHP process).
Is this the script you are calling from your form? Apache only holds the uploaded files for the duration of the called script, after that, the files are deleted if they are not handled by the script.
foreach ($_FILES['atc']['tmp_name'] as $key => $tmp_name){ $path = "home/goes/attachments/" . $fileName";move_uploaded_file($tmp_name, $path);
}