i am creating a facebook application which lets user to upload photo through html form. I was wondering it is possible to implement a filter to check the file ext before the form is being submit.
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
Choose a file to upload: <br/>
<input name="uploadedfile" type="file" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'" accept="image/gif,image/png,image/jpeg"/> (limit: 2MB)<br />
<input type="submit" value="Upload File" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'"
onclick='checkExt()'/>
</form>
I have tried varies ways, javascript or php.
function checkExt() {
var filePath = document.getElementByName("uploadedfile");
if(filePath.indexOf('.') == -1)
return false;
var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
validExtensions[0] = 'jpg';
validExtensions[1] = 'jpeg';
validExtensions[2] = 'bmp';
validExtensions[3] = 'png';
validExtensions[4] = 'gif';
for(var i = 0; i < validExtensions.length; i++) {
if(ext == validExtensions[i])
return true;
}
top.location.href = 'http://www.google.com';
return false;
}
for the php, is there a way to get the file info before form submit?
$file = document.getElementByName("uploadedFile"); //wondering if this works.
$result_array = getimagesize($file);
if ($result_array !== false) {
$mime_type = $result_array['mime'];
switch($mime_type) {
case "image/jpeg":
echo "file is jpeg type";
break;
case "image/gif":
echo "file is gif type";
break;
default:
echo "file is an image, but not of gif or jpeg type";
}
} else {
echo "file is not a valid image file";
}
Please advice me. I am still new to facebook application.
Why do you redirect if they try to upload a wrong ext?
I would remove top.location.href = 'http://www.google.com';
You have several mistakes in the script.
var filePath = document.getElementByName("uploadedfile");
needs to be
var filePath = document.getElementsByName("uploadedfile")[0].value;
or add an id and do
var filePath = document.getElementById("uploadedfile").value;
or use my favourite method and pass the form object to the function:
<form onsubmit="return checkExt(this)" ...>
function checkExt(theForm) {
var filePath = theForm.uploadedfile.value;
Lastly remove the onclick from the submit and put it in the onsubmit of the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST"
onSubmit="return checkExt(this)">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
Choose a file to upload: <br/>
<input name="uploadedfile" id="uploadedfile" type="file" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'" accept="image/gif,image/png,image/jpeg"/> (limit: 2MB)<br />
<input type="submit" value="Upload File" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'"/>
</form>
Just some thoughts:
It's possible to have JS check the extension. Its just the part after the '.', so basic string-operations.
It's not safe and not reliable, though. It can be fooled and sidestepped.
You can send an AJAX-request to have the extension(s) transmitted before you submit the form.
For pretty acurate FileType-Info check out PHP's FileInfo-Extension.
Related
I am trying to check if a file is png before upload and am getting the error
Warning: exif_imagetype(): Filename cannot be empty
It seems to work with one file for some reason but not with any others that I have tried.
The main is
$image = $_FILES['userImg']['tmp_name'];
if (checkImageValid($image))
{
uploadImage($image);
}
The checkImageValid Function is
function checkImageValid($image)
{
$valid = true;
$imgType = exif_imagetype($image); //error here
if($imgType != IMAGETYPE_PNG)
{
$valid = false;
$_SESSION["imageMessege"] = 'The image You are trying to upload is not of type png';
}
return $valid;
}
getting it from html form here
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="10000" />
<input type="file" name="userImg" accept="image/x-png"/>
<input type="submit" value="Upload File" name="uploadImage" />
</form>
<input type="hidden" name="MAX_FILE_SIZE" value="10000" />
Is the error. Change the value to more, it's in bytes. 10000 bytes = ~10kb. Change to 10000000 for ~10MB.
Replace the line with this:
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
I tested it and it works fine for me with any images.
Hello I'm doing form upload 4 files field. Each field can upload 1 file.
but I just know that hacker can hack with firebug to add html5 "multiple" attribute.(see the screenshot)
and then hacker can upload exceed 4 files now that I don't want to happen.
Question : How can I do to limit the upload file to 4 files?
here is my current code
for($i=0;$i<count($_FILES["file"]["name"]);$i++) {
if($_FILES["file"]["name"][$i] != "") {
$split = explode('.', $_FILES["file"]["name"][$i]);
$ext = end($split);
$tempFile = $_FILES['file']['tmp_name'][$i]; //3
$targetFile = "upload/". date('Y-m-d')."_".($i+1).".".$ext; //5
move_uploaded_file($tempFile,$targetFile); //6
}
}
..
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br><br>
<input type="submit" value="Upload"/>
</form>
Things like this must be validated server-side.
if(count($_FILES["file"]["name"]) > 4) {
// show the user an error and refuse to continue
}
I designed a form in form.php with a file input. When I press +input button, a new file input object should be generated and save them to my mysql server.
My code here,
form.php
<div id="enterReplyReferenceList">
<div class="enterReplyRefInputContainer">
<div class="enterReplyRefInput">
<form action="submit.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $userID; ?>" name="userID">
<input type="submit" value="SEND"/>
<input type="file" name="enterRefFile[]" multiple class="enterRefFile" accept="application/pdf,image/jpeg, image/png, image/jpg"/>
</form>
</div>
</div>
</div>
<button onclick="appendRef()">+input</button>
form.js
function appendRef(){
var inputclass = document.getElementsByClassName('enterReplyRefInputContainer')[0];
var inputclassChild = document.createElement('div');
inputclassChild.innerHTML = inputclass.innerHTML;
var newClass = document.getElementById("enterReplyReferenceList").appendChild(inputclassChild);
newClass.className = "enterReplyRefInputContainer";
submit.php
for($i=0; $i<count($_FILES['enterRefFile']['name']); $i++) {
$tmpFilePath = $_FILES['enterRefFile']['tmp_name'][$i];
if ($tmpFilePath != ""){
$fileData = addslashes(file_get_contents($_FILES['enterRefFile']['tmp_name'][$i]));
$fileName = addslashes($_FILES['enterRefFile']['name'][$i]);
$fileType = $_FILES['enterRefFile']['type'][$i];
if($fileData != null){
if($fileType == "application/pdf" || $fileType == "image/png" || $fileType == "image/jpeg" || $fileType == "image/jpg"){
mysql_query("INSERT INTO attachment (attachData, dataType, attachName, userID) VALUES('$fileData','$fileType','$fileName', '$userID')");
}
}
}
}
When I pressed the +input button, a new input file object is generated with the same look with the original and I can select the files. However, only a single file can be uploaded to my mysql db after I clicked the submit button. Can somebody tell me why the new file input cannot be uploaded? Is the new objects will not be sent?
The problem is that your input button is cloning your whole div, which has the form, so when you click "Submit" you're uploading one form with one file element. Here's an updated version (all in one file, you can separate to your liking):
<button onclick="appendRef()">+input</button><br><hr>
<form action="submit.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $userID; ?>" name="userID">
<div id="enterReplyReferenceList">
<div class="enterReplyRefInputContainer">
<div class="enterReplyRefInput">
<input type="file" name="enterRefFile[]" multiple class="enterRefFile" accept="application/pdf,image/jpeg, image/png, image/jpg"/>
</div>
</div>
</div>
<hr>
<input type="submit" value="SEND"/>
</form>
<script>
function appendRef(){
var inputclass = document.getElementsByClassName('enterReplyRefInputContainer')[0];
var inputclassChild = document.createElement('div');
inputclassChild.innerHTML = inputclass.innerHTML;
var newClass = document.getElementById("enterReplyReferenceList").appendChild(inputclassChild);
newClass.className = "enterReplyRefInputContainer";
}
</script>
Button click is outside of the form so you don't do a submit action on it (unless you want to use a blocking action like jQuery preventDefault(), and you only need one submit for the whole form.
I made a form at HTML with an option to upload an image. The problem is that when I check the $_FILES array at the php code, it is not found.
The HTML form:
<form method="POST" action="addProduct.php" onsubmit="return checkValidation()">
Image(optional): <input type="file" name="fileImg" accept="image/*" id="fileImg">
<input id="submitProduct" type="submit" name="submitBtn" value="Submit product" onclick="checkValidation()"/>
</form>
The checkValidation() function:
function checkValidation(){
var regex = /\.(jpg|JGP|jpeg|JPEG|png|PNG|gif|GIF)$/;
if (($('#fileImg').val()) && (!(regex.test($('#fileImg').val()))))
{
return false;
}
}
And the php code:
if(isset($_POST["submitBtn"])){
if(!(empty($_FILES)))
{
if (file_exists('uploads/'.$_FILES["fileImg"]["name"]))
{
echo $_FILES["fileImg"]["name"]." already exists. ";
}
else
{
move_uploaded_file($_FILES["fileImg"]["tmp_name"], 'uploads/'. $_FILES["fileImg"]["name"]);
$path = $_FILES["fileImg"]["name"];
}
}
else
$path = 'no_photo.jpg';
The problem is that at the php code, it always jumps to the else branch (which gives me some default image).
Thanks in advance.
Your form lacks the enctype='multipart/form-data' attribute. Without it, $_FILES would always be empty.
Read more about it here: What does enctype='multipart/form-data' mean?
I have a problem conserning uploading multiple files to my ftp server and I am using jQuery's multifile extension.
This is the multifile javascript code on page with the upload form (file_upload.php):
<script type="text/javascript">
$(function(){ // wait for document to load
$('.remove').MultiFile({
STRING: {
remove: '<img src="images/upload-remove.png" height="16" width="16" alt="x"/>',
denied:'You can't choose file $ext .\nTry again...',
file:'$file',
selected:'Chosen file: $file',
duplicate:'This file is already chosen:\n$file'
}
});
});
</script>
And this is the HTML form (file_upload.php):
<form name="uploader" action="file_upload2.php" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Upload file:</label>
<br />
<input type="file" class="multi, remove" name="file[]" value="Upload file" />
<input type="submit" value="submit"/>
</fieldset>
</form>
The PHP part is where I don't get it. I tried to do it with this code (file_upload2.php):
<?php
if(isset($_POST['submit']))
{
$ftp_config['server'] = 'ftpserver.org'; //ftp host
$ftp_config['username'] = 'ftp_username'; // ftp username
$ftp_config['password'] = 'ftp_password'; // ftp user password
$ftp_config['web_root'] = 'public_html'; //foldername from user home dir.
$fileElementName = 'file[]'; //file field name
$conn_id = ftp_connect($ftp_config['server']);
$ftp_login = ftp_login($conn_id,$ftp_config['username'],$ftp_config['password']);
if(!ftp_put($conn_id,$ftp_config['web_root'].'/'.$_FILES[$fileElementName]['name'],$_FILES[$fileElementName]['tmp_name'],FTP_BINARY)){
$result = " Error occurred. ";
}else{
$result = " File has been uploaded. ";
}
echo $result;
}
?>
You have to loop through $_FILES for each file that was uploaded.
Do a print_r($_FILES); to see what you have to work with.