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";
}
}
?>
Related
I have two PHP files.
index.php allows users to upload an image. The uploaded data is sent to another page i.e. upload.php, where I check certain conditions for example if the uploaded image is really an image and not some other file and if the image already exists on the server etc;
I want to see that my upload.php page redirects back to the index.php page in false conditions. I have seen many of the posts on redirecting, e.g., by using header, which I did. Well, It does redirect. However, there is some part of javascript code, which does not execute. I want to see that alert box on my upload.php page, which upon user interaction redirects to index.php.
Alert box does not appear at the moment, but the page does redirect
My question might be very trivial, but I am a PHP newbie.
index.php
<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>
upload.php
$target_dir = "uploads/";
$file_name=basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $file_name;
$uploadOk = 1;
if (file_exists($target_file)) {
$uploadOk = 0;
echo "<script language='javascript'>
alert('Sorry, file already exists.Consider Renaming or upload new file');
</script>";
header("Location: http://xx.yyy.zz");
exit;
}
You can replace the 'HTTP header redirect' with a redirection done in javascript.
Remove the code
header("Location: http://xx.yyy.zz");
And replace the echo command with
echo "<script language='javascript'>
alert('Sorry, file already exists.Consider Renaming or upload new file');
window.location = "http://xx.yyy.zz";
</script>";
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Trying to allow file upload along with a form that is otherwise working. I cut out the relevant form/input/processing rules. Hopefully someone who is more than ankle-deep in PHP (as I am) can point me in the right direction?
<form name="form-quote" id="form-quote" enctype="multipart/form-data" action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>" method="POST">
<div class="form_labels">
<p><label for="fileupload">Upload File (optional):</label></p>
</div>
<div class="form_inputs">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<p><input type="file" name="fileupload" id="fileupload" accept=".pdf, .txt, .rtf, .doc, .docx, .xls, .xlsx" style="margin-bottom:2px;"/>
<span style="color:#777;">(pdf, txt, rtf, doc, docx, xls, xlsx, <5MB)</span></p>
</div>
<input type="hidden" name="formtype" id="formtype-quote" value="quote">
<div class="form_labels submit">
<p> </p>
</div>
<div class="form_inputs">
<input type="submit" value="Submit" name="action" class="btn-red" >
</div>
</form>
<?php
//$formerrors is set to false unless one of the validation rules for the OTHER fields fails - no validation on the file upload, although I would like to trim & sanitize it if possible.
if (!($formerrors) && isset($_POST['fileupload'])):
$tmp_name = $_FILES["fileupload"]["temp_name"];
$uploadfilename = $_FILES["fileupload"]["name"];
$savedate = date("mdy-Hms");
$newfilename = "/wp-content/uploads_forms/" . $savedate . "_" . $uploadfilename;
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename)):
$msg = "File uploaded.";
else:
$msg = "Sorry, your file could not be uploaded." . $_FILES['file']['error'];
$formerrors = true;
endif; //move uploaded file
endif;
?>
Thanks to Alexander's answer below, I was able to modify my validator to work and to achieve my original goals (check for null, and give files unique names before uploading). Here's my "final draft," which is working now.
//Check form errors, check file name not null, rename file with unique identifier to avoid overwriting existing files with same name
if (!($formerrors)) {
$tmp_file = $_FILES["fileupload"]["tmp_name"];
if ($tmp_file != "") {
$savedate = date("mdy-Hms");
$target_dir = "wp-content/uploads/";
$target_file = $target_dir . $savedate . '_' . $_FILES["fileupload"]["name"];
if (move_uploaded_file($tmp_file, $target_file)) {
$msg = "File uploaded.";
} else {
$msg = "Sorry, your file could not be uploaded.";
$formerrors = true;
}//move successful
}//end null check
}//end form errors check
The code you are using above is Javascript. In case you depend on that please change the tags of the post. If not here is a possibility for a PHP-Uploadscript:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileupload"]["name"]);
if (move_uploaded_file($_FILES["fileupload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileupload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
SOURCE: http://www.w3schools.com/php/php_file_upload.asp
EDIT: The script above has be placed in the file receiving the POST from the form.
The code you posted is a big mess!
Let's try to clarify some basic points...
File-upload mechanism
For file-upload to work you must have a <form> with action attribute addressing the script where you'll check and use the uploaded file.
This script may be the same as the one where the <form> is generated, assumed you take care of the pitfalls that come with this situation.
At a first general glance your current code seems to correspond to the latter case.
But your form action looks weird:
action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>"
As a first intent, if you want to address the same page where you already are, you can simply omit action attribute.
Here you seem to explicitely try the same, adding the precision of #form-quote, but:
This #form-quote has no effect here, since such a hash is made to target a <a>, while it's currently affected to your <form>.
The other part of the url you build is a non-sense mixing REQUEST_URI (which is the name of one of the $_SERVER members) with the hard-core expression of a path in your context.
Anyway all the above doesn't matter, because this end with $_SERVER[...something which is not a known $_SERVER member...], so it actually returns NULL, and somewhat ironically it has the same effect as if you didn't specify action at all!
PHP in a SO snippet
So ou put your code in a snippet, but SO snippets work only with HTML, CSS, and Javascript, so you can't expect it allows to demonstrate how your code is working or not.
Note that at this step, despite the errors mentioned above, we didn't point something which would make your code to fail.
And in your question you didn't mention how it fails!
Uploaded file processing
So looking at your PHP code part, I first note this statement:
$tmp_name = $_FILES["fileupload"]["temp_name"];
where you're looking for temp_name, while the true involved key is tmp_name. This alone is enough to make your code to fail.
Furthermore looking at these two statements:
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename))
In the 1st one you use $newfilename as the complement of the url you're building, so obviously $newfilename can't target an absolute physical path.
It means that in the 2nd one you try to move_uploaded_file() to a wrong place!
Last point, you currently don't take care of possible errors before trying to use the uploaded file.
You should complete your primary condition like this:
if (!($formerrors) && isset($_POST['fileupload'])) && !$_FILES["fileupload"]["error"])
And if you effectively get some errors and have trouble to understand why, you should also look at this interesting PHP manual page.
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.
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
}