I want to allow users to select a folder by clicking on upload button . On submit , I want to retrieve all filenames from folder (recursively) , without uploading any file or folder.
Example ,
Lets say there is folder name Test with following folder structure :
Test
- 1.txt
- 2.pdf
- 3.avi
- Test2 (Folder, contains multiple files)
- 4.mp4
On selecting Test folder on clicking upload button , output should be :
1.txt , 2.pdf , 3.avi, Test2 (filenames of file inside this folder) , 4.mp4
I don't need to get contents inside file , just the filename.
How should I do it ?
I know there is chrome webkit directory which allows folder upload
<?php
$count = 0;
$name2 = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
foreach ($_FILES['files']['name'] as $i => $name) {
if (strlen($_FILES['files']['name'][$i]) > 1) {
$count++;
array_push($name2, $_FILES['files']['name'][$i]);
}
}
}
?>
<!DOCTYPE HTML>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" id="files" multiple="" directory="" webkitdirectory="" mozdirectory="">
<input class="button" type="submit" value="Upload" />
</form>
</body>
</html>
$name2 array return list of filenames
Above code does not work for video files and is not compatible with other browsers.
Is there any other way of doing it ?
PHP provides you with an object called the filesystemiterator that's designed to help you loop through a designated folder. In your case, I'd do a recursive function that would look like this:
function readFolder($folder)
{
$retArray = array();
$folder = new FilesystemIterator("path/to/folder", FilesystemIterator::SKIP_DOTS);
foreach($folder as $file)
{
if(is_dir($file->getPathname())
$retArray[] = readFolder($file->getPathname());
else
$retArray[] = $file->getFilename();
}
return $retArray;
}
What's nice about all this is that the getPathname() method returns the entire path of the file while if you just want the name of the file, you can just use the getFilename() method. Here's a link to the documentation on PHP's website:
http://php.net/manual/en/class.filesystemiterator.php
Also, for security purposes, modern web browsers do not include the full path to a file when you use the "file" input type.
Related
i'm going to create a gallery website and it will contain a lot of
alboums and photos, videos. now what the right thing: 1-insert the photos and videos in database (if it right tell me how) 2-make an html page for each alboum. thanks in advance.
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above:
Make sure that the form uses method="post". The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
Other things to notice:
The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
more info :
https://www.w3schools.com/php/php_file_upload.asp
https://sites.google.com/site/prgimr/how-to-upload-image-or-files-into-database-using-php-and-mysql
https://www.youtube.com/watch?v=3OUTgnaezNY
Third option probably is the best. Store them in a cloud storage like AWS S3, Azure Blob Storage or Google Cloud Storage and many other options. They are much cheaper than a database and more versatile then storing as html.
I am trying to add edit option for image filename and also delete option for the images. All the images are in a folder and I haven't used database at all. I am able to display the image filenames along with button for edit and delete adjacent to every image name.
But I am not sure how to go forward. I know PHP has a unlink() and rename() functions. but I am not sure how to include this functions dynamically.
<?php
echo "<div class='container'>";
if(isset($_POST["submit"])) {
$files = glob("images/Kwebsite/". $_POST['path']."/*.*");
}
echo "<div class='col l5'>";
echo "<h3>Image Filename Actions</h3>";
echo "</div>";
for ($i=0; $i<count($files); $i++){
$num = $files[$i];
$filenamewithextension = basename($num);
$fileextenstion = pathinfo($filenamewithextension, PATHINFO_EXTENSION);
$filename = basename($num,$fileextenstion);
echo '<div class="imagename">';
echo $filename;
echo '<button type="submit" class="btn-flat" value="Delete" onClick="Delete()">Delete</button>';
if(isset($_POST["submit"])) {
$imgfile = glob("images/Kanishk website/". $_POST['path']."/*.*");
foreach $imgfile as $img {
unlink($img)
}
}
}
?>
You have to pass the file path to unlink().
If you want to remove multiple files, you will have to call unlink multiple times. If you push the file paths to an array you can loop over the paths.
$paths['/files/file1.jpg','/files/file2.jpg']
foreach $paths as $file {
unlink($file)
}
If you want to rename the file, you also have to provide the full path,
otherwise you will create a new file somewhere else:
rename ("/files/file1.jpg", "/files/file_1.jpg");
This info has to be provided by a user, at least in most cases.
I would recommend storing the paths and filenames in a database.
First of all, this a dangerous thing you are doing there and you should avoid it. Imagine what could happen if someone gives some level up dots combination like this ../../; the script would have listed all the files 2 levels up. In order to prevent such behavior, we need to check the path input string for slashes and backslashes and do not execute the glob function if some slashes found. Here is the regular expression to validate the path query:
// Check for backslash, level up dir .. and wildcards
$isValidPath = !preg_match('#([\\\.\?\*])#', $path);
I made a very simple example based on your code. All the commands are passed to PHP by posting form data to the server (not AJAX). When the user clicks on delete button, a message confirmation appears and if the user clicks OK, then the form posts the delete button data, which are its name="delete" and the value="path/filename.ext". We'll have a $_POST['delete'] == "path/filename.ext" value in PHP. If we detect the delete in our POST data, then we call the unlink and we delete the file. For the renaming functionality, we use the same method but with the javascript prompt this time, which prompts and asks the user to type a new filename. If the new filename is different from the original, then it updates a hidden field with the new filename and posts the form fields to our PHP server script; the POST data will have these values for the rename function $_POST['rename'] == "path/oldfilename.ext" and $_POST['renameto'] == "newfilename.ext". Then we just call the rename function at the beginning of our script.
Tip: Use PHP print_r function to print the $_POST array inside an HTML <pre></pre> to debug post data on each page refresh:
<pre><?php print_r($_POST) ?></pre>
The final working script
<pre><?php print_r($_POST) ?></pre>
<?php
$hasPath = isset($_POST['path']);
$basePath = __DIR__."/images/Kwebsite/";
$path = '';
$files = array();
if(isset($_POST['rename']) && isset($_POST['renameto'])) {
$fileToRename = $basePath.$_POST['rename'];
$renameTo = dirname($fileToRename).'/'. $_POST['renameto'];
rename($fileToRename, $renameTo);
}
if(isset($_POST['delete'])) {
$fileToDelete = $basePath.$_POST['delete'];
unlink($fileToDelete);
}
if($hasPath) {
// Check for backslash, level up dir .. and wildcards
$path = $_POST['path'];
$isValidPath = !preg_match('#([\\\.\?\*])#', $path);
if($isValidPath) {
$searchPath = $basePath.$path.'/*.*';
$files = glob($searchPath);
}
}
?>
<form method="post">
<label>Search directory: </label>
<input type="text" name="path" value="<?php echo $path ?>"/>
<button type="submit">Search</button>
<hr>
<table border="1">
<thead>
<tr>
<th>Image Filename</th><th>Actions</th>
</tr>
</thead>
<tbody>
<?php if($hasPath && $isValidPath && count($files) > 0): ?>
<?php foreach($files as $file):
$filenameWithExtension = basename($file);
$fileExtenstion = pathinfo($filenameWithExtension, PATHINFO_EXTENSION);
$filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
?>
<tr>
<td><?php echo $filename ?></td>
<td>
<button type="submit" name="delete" value="<?php echo "{$path}/{$filenameWithExtension}" ?>" onClick="Delete(event)">Delete</button>
<button type="submit" name="rename" value="<?php echo "{$path}/{$filenameWithExtension}" ?>" onClick="Rename(event)">Rename</button>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<input type="hidden" id="renameto" name="renameto"/>
</form>
<script type="text/javascript">
function Delete(e) {
var event = e || window.event,
filename = event.target.value.substr(event.target.value.lastIndexOf('/') + 1);
if(!confirm("Are you sure you want to delete this file '"+filename+"'?"))
event.preventDefault();
}
function Rename(e) {
var event = e || window.event,
oldFilename = event.target.value.substr(event.target.value.lastIndexOf('/') + 1),
newFilename = prompt("Enter a new filename", oldFilename);
if(newFilename != null) {
if(newFilename == oldFilename) {
alert("You must give a different filename");
event.preventDefault();
} else {
document.getElementById('renameto').value = newFilename;
}
} else {
event.preventDefault();
}
}
</script>
I am not sure how to include this functions dynamically
Based on your question and your code, it looks like you are capable of deleting or renaming the files but are looking for work flow advice.
I give the following suggestions. If you want code, I am happy to supply my solutions, but the scope of an interface is rather large and needs some clarification first. For example,
Do you have directories that the user navigates?
Do you want the user to have checkboxes to check individual files (recommended) OR do you want them to be able to enter a file pattern as you example shows (dangerous!)?
My recommendations:
Use a table to display the files. Above the table include buttons to "Delete Selected", "Cancel"
Include the following columns in the table:
Checkbox (for selecting multiple files if this is desired)
Filename (just text and can be the label portion of the checkbox)
Editable input with filename allowing user to rename
Input Button = "Rename" (to rename individual file)
Input Button = "Delete" (to delete individual file)
Thumbnail image which they can click on to see a full sized image.
The table is within a form so that each <input> with a name property will end up in $_POST For example, the inputs for renaming a file and submitting it looks like this:
<td><input type=text name=filer-<?php echo encodestr($filefull) ?> value='<?php echo $name ?>'></td>
<td><input type="submit" name="fprename-<?php echo encodestr($filefull) ?>" value="Rename" onClick='return confirm("Do you want to rename this file?");'></td>
where $filefull is the full existing path to the file and $name is without the path. When clicking on the Rename button, $_POST will contain elements with each filename prefixed with filer- so I can easily recognize them. I know which one to rename or delete based on which submit button was pressed which I can tell from the var which is prefixed with fprename-.
So if I get back from $_POST a var named $_POST['fprename-/path/myfile.jpg'], I look for the input var $_POST['filer-/path/myfile.jpg'] and rename the file to the value contained in it (of course checking first that a file with that name doesn't already exist).
Work Flow:
For deleting multiple files
User selects items using checkboxes for deleting and submits form by clicking on the Delete Selected submit button.
The form onSubmit gives a javascript alert() to allow cancelling the delete request.
After user confirms, you want to do a Post/Redirect/Get (to prevent multiple form submission). This involves submitting the form to another php (e.g. processFiles.php) which processes the unlink() code you have then redirects back to the userInterface.php.
For deleting or renaming individual files
User clicks on a submit button in the table next to the individual files.
The button onclick gives a javascript alert() to allow cancelling the delete or rename request.
After user confirms, the form will submit. Again, you want to do a Post/Redirect/Get where another php (e.g. processFiles.php) processes the unlink() or rename code then redirects back to the userInterface.php.
In the following example, I don't allow deleting multiple files, only Selecting multiple files - hence the "Select" button at the top instead of a "Delete Selected".
I investigate the problem of file upload using html5, and I have theoretical question: has html5 any limits for file size for uploading?
For example, can I upload files with size ~500Gb?
P.S.: I use FileReader api for reading file.
Ok. This problem is resolved.
But as it explains in FileReader API:
This interface provides methods to read File objects or Blob objects into memory...
As I understood correctly, I can't read file with size which is more than available RAM?
Nope, there is no size upload limit.
here is the spec and here is a related question on how to check the file size, so that you can add limits if you like.
It's worth pointing out that if you are looking to store the file on the server, you might hit file upload limits/restrictions there. But you should be able to configure them. i.e. php/wordpress default upload limit
Hope this useful..
Form,script for validating:
<form action="check.php" method="post" enctype="multipart/form-data">
<label>Upload An Image</label>
<input type="file" id="file_upload" name="file_upload" />
<input type="submit" onClick="return validate()" name="upload"/>
</form>
<script>
function validate(){
var size=2097152;
var file_size=document.getElementById('file_upload').files[0].size;
if(file_size>=size){
alert('File too large');
return false;
}
var type='image/jpeg';
var file_type=document.getElementById('file_upload').files[0].type;
if(file_type!=type){
alert('Format not supported,Only .jpeg images are accepted');
return false;
}
}
php for uploading:
<?php
if(isset($_POST['upload'])){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
if(move_uploaded_file($_FILES["file_upload"]["tmp_name"], $target_file)){
echo "The file ". basename( $_FILES["file_upload"]["name"]). " has been uploaded.";
}
else{
echo "sorry";
}
}
?>
Getting an issue with the upload image part from the client.
We have a php form called entry where the client will enter some information that we needs to upload an image. After submitting, the information will be saved into an xml file called data.xml and it will be shown on an html file called display.html
The image have to be saved into a folder called upload. We have this code but I think somewhere we are doing it wrong because it's not working.
This is the part for the image:
PHP Code:
$_FILES['file'];
$_FILES["file"]["name"];
$_FILES["file"]["type"];
$_FILES["file"]["size"];
$_FILES["file"]["tmp_name"];
$_FILES["file"]["error"];
if(isset($_POST["file"]['submit'])) {
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "<br>Stored in: " . "upload/" . $_FILES["file"]["name"];
}
} echo $doc->save($file); } ?>
And in the body html we have this:
<label for="file">Image:</label>
<input type="file" name="file" id="file" action:"entry.php" method:"post" entype:"multipart/form-data"><br>
And also it doesn't save anything in the data.xml file. If I remove this code and leave it as it is, the information are saved in the xml form and the display is working.
Can anyone help please?
Thank you
firstly you need to use form and input type submit.
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
also You have a spelling mistake in enctype:"multipart/form-data" you missed c..
Important parts of the code are missing.
Assuming that you've done everything else correctly, and your problem is that it doesn't save anything in the xml file,you should add the below code just after your second echo:
//foreach takes keys and values from all file input types
foreach($_FILES as $item => $val){
$val=$_FILES["$item"]["name"]; //save each file's name to $val
$fileNode=$doc->createElement($item, $val); //create a new file element(file is an image in your case)
$entry->appendChild($fileNode); //add the file element as a child of another element - $entry must be initialized from before
}
Is any other way to get the slected folder path other than using fileupload control ?
using file upload control i am getting filename but i need to get only selected folder path , is it possible to get folder path ?
Code:
<input id="fileToUpload" type="file" size="45" style="width:300px;" name="fileToUpload" onChange="addFiles(this, this.value,this.value);" class="input">
<select name="mcffiles" id="mcffiles" size=5 style="width:200px; height:100px">
function addFiles(selectObject, seltext, selvalue)
{
alert(seltext);
alert(selvalue);
var optionObject = new Option(seltext,selvalue);
var optionRank = document.getElementById("mcffiles").options.length;
alert(optionRank);
if(optionRank <= 4)
{
document.getElementById("mcffiles").options[optionRank]= optionObject;
}
else
alert('Only 5 files can select')
}
If you mean the folder path on the client then no, javascript can not access the local file system even to read.
If you want to allow upload of the entire folder content (which I guess is why you are asking), then you have to embed flash or something similar.