I am facing an issue with the below code, I can upload multiple files but still need that the if condition not be executed till user chooses a file as it is not good to see Unique ID and the echo message run however no files chosen!
PHP
<?php
$path = "Uploads/Files/";
if( (isset($_POST['submit'])) && (!empty ($_FILES['myFile']['name'])) ){
$countfiles = count($_FILES['myFile']['name']);
for($i=0;$i<$countfiles;$i++){
$filename = uniqid(). $_FILES['myFile']['name'][$i];
// Upload file
move_uploaded_file($_FILES['myFile']['tmp_name'][$i], $path.$filename);
echo "<h3> $filename has been uploaded Successfully!</h3>";
}
}
?>
So I want the && part above to be valid as well and not below message to appear till files be chosen.
HTML
<form method='post' enctype='multipart/form-data'>
<input type="file" name="myFile[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
Error:
there are two parts:
add validation for required field <input type="file" name="myFile[]" id="file" multiple required>
render whatever you want instead of echo "<h3> $filename has been uploaded Successfully!</h3>";
Related
I need to upload a lot of images at once (e.g. 200 small images) through the browser. I have this code:
<?php
if(isset($_POST['Upload_files']) and $_SERVER['REQUEST_METHOD'] == "POST"){
echo count($_FILES['files']['name']); // Even if I upload more than 20 files, it still displays 20.
$target_directory = "upload/";
foreach ($_FILES['files']['name'] as $file_number => $file_name) {
$file = $_FILES["files"]["tmp_name"][$file_number];
if (mime_content_type($file) != 'image/png' && mime_content_type($file) != 'image/jpeg')
{ $error[] = 'File '.$file_name.' is not in JPG / PNG format!'; continue; }
else
{ if(move_uploaded_file($file, $target_directory.$file_name)) {$count_of_upload_file++;}}
}
}
// If files were uploaded
if($count_of_upload_file != 0){echo 'Your files ('.$count_of_upload_file.' ) were successfully uploaded.';}
// If there was an error
if (isset($error)) {foreach ($error as $display_error) {echo '- '.$display_error.'<br />';}}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
And it works. However my provider set the 'max_file_uploads' to 20 (and I'm not able to change it). (The Uploadify extension is working for more than 20 files, but I'd like to have my own small solution.) So I presume I need to add here something, which instead of 200 files at once uploads 200 files one by one (or twenty by twenty). But I don't know how to do it. (To use AJAX? -- I never used it, so I really don't know.) Thank you!
If you don't want to use ajax, you need a loop to receive files
for($i = 0; $i < count($_FILES['files']['tmp_name']); $i++){
$tmp = $_FILES['files']['tmp_name'][$i];
$name = md5(microtime());
if(move_uploaded_file($tmp, "dir/$name.jpg")){
echo "Uploaded successfully";
}else{
echo "failed";
}
}
In your form you must name all your input fields as files[], example:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="file" name="files[]" multiple="multiple" accept="image/*">
<input type="submit" name="Upload_files" value="Upload files">
</form>
Or if you want to use ajax here is an example:
Upload multiple image using AJAX, PHP and jQuery
How can i count the number of uploaded files?
This is my form:
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form id="sfmFiler" class="sfmform" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<input type="submit" name="submitHandler" id="submitHandler" class="buttonUpload" value="Upload">
</form>
and this is the piece of php which uploads the files:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$tmpFilePath = $_FILES['file']['tmp_name'];
$newFilePath = $dir.'/' . $_FILES['file']['name'];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "xxx files are successfully uploaded";
}
}
In this code you are getting only one file thats why you are getting count result 1. if change your input file name like "file[]"
<input type="file" name="file[]" id="file" multiple />
and then use the below line code you will get your desire result. Cause its needs an array filed to hold the input data.
<?php echo count($_FILES['file']['name']); ?>
Thanks, i tried in my system get the result.
AFriend is correct. The above answers always return 1.
Try:
echo count(array_filter($_FILES['file']['name']))
Worked for me anyway.
_t
Using the array_filter function it works
try
$countfiles = count(array_filter($_FILES['file']['name']));
It returns 0 in case of NULL, 1 in case of 1 file uploaded, etc.
Check this answer
<?php echo count($_FILES['file']['name']); ?>
php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array
You could use the count function:
$no_files = count($_FILES);
If no files are selected and your file count is 1, you can use this line before moving the file:
if (!empty($_FILES['file']['tmp_name'][0])) {
for($i=0;$i<$countfiles;$i++){
I have a form with input type file and its not compulsory to upload . But after the submit action occurs I want to check in the controller section if the file input is empty or not. I have a following view page and controller but the method is not working for me .
This is the form fillup page
<form enctype="multipart/form-data" method="post"
action="<?php echo site_url('welcome/do_upload');?>">
username:<input type="text" name="username">
<p>upload file</p>
<input type="file" name="image">
<input type="submit" name="submit" value="submit">
</form>
and this is the controller where am trying to check if the file is selected to upload or not .
if(isset($_FILES['image'])){
echo( "image selected");
} else {
echo("image not selected");
}
the output of the result is always the "image selected" though I don't select any image
The error is when you submit the FORM
$_FILES['image'] will always be created no matter what thus making your conditions true.
You are checking for the wrong conditions here, what you want to do is when a user uploads a file. You might want to do is to check if the $_FILES['image']['name'] length is > 0 or the $_FILES['image']['size'] is > 0.
example, code not for production, just for testing.
if ( strlen($_FILES['image']['name']) > 0){
//yeahhhh!
}
I am trying to upload an image to a server, then get that image name and insert it into mysql database. Before I got to the database bit, the upload isn't working. I have narrowed it down to the fact there is no data in the $_FILES array, when I echo out $imageFileName is it blank.
Here is part of my form:
<form name="addItem" method="post" action="add-new-item.php">
<input name="name" placeholder="Portfolio Item Name" type="text" id="itemName"/><br />
<input type="file" name="imageName" id="imageName" /><br />
</form>
Script, which is part of the same page the form is on:
$target = "images/";
$target = $target . basename( $_FILES['imageName']['name']);
$imageFileName=($_FILES['imageName']['name']);
if(move_uploaded_file($_FILES['imageName']['tmp_name'], $target)){
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}else {
echo "Sorry, there was a problem uploading your file.";
}
$query1="INSERT INTO portfolio_items (item_name,full_size_image) VALUES('$itemName','$itemImage')";
You need to include the following in your <form> tag :
enctype="multipart/form-data"
So it would become :
<form name="addItem" method="post" action="add-new-item.php" enctype="multipart/form-data">
Documented very well here - see the note at the bottom of the first page ...
Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" 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>
</body>
</html>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>