This question already has answers here:
how to check if a $_FILE is set in php?
(5 answers)
Closed 8 years ago.
I have an input type ="file" in a form that upload images (multiple images) and other inputs (from textareas) .
I need that, if the user didn't choose any images, I don't want to excecute the upload image.
This because if I use the site from Ipad, the script give me error because he didn't find anything in the file-input[], also if I don't want to upload images.
So I wanna check if the file-input[] is empty or not, so the problem from Ipad will be solved (I hope).
This is the html
<div id="file-ins-immagini">
<div class="et-form-ins">Immagini allegate</div>
<input type="file" name="file-input[]" id="file-input" value="" class="file" multiple>
</div>
And this is the code of the insert in php ('invia' is the name of the submit button of my form)
if (isset($_POST['invia']) && $_POST['invia'] == "Inserisci")
{
$messaggiocaso = "";
$infoimages = array_combine($_FILES["file-input"]['name'], $_FILES["file-input"]['tmp_name']); // recuperiamo e uniamo le informazionei sulle immagini
foreach ($infoimages as $k => $v)
{
$nomefile = strtolower($k);
if(!empty($nomefile))
{
if (filesize($v) < $peso_file)
{
$estensionefile = pathinfo($nomefile, PATHINFO_EXTENSION);
if (in_array(strtolower($estensionefile), $estensioni))
{
if (is_uploaded_file($v))
{
if(!file_exists("$uploadDIR/$next_id"))
{
mkdir("$uploadDIR/$next_id",0777,true);
}
if (!move_uploaded_file($v, "$uploadDIR/$next_id/$nomefile"))
{
$messaggiocaso = urlencode("Impossibile l'inserimento del caso. Impossibile spostare il file $k");
header("location:tabella.php".'?msgcasoerrato='.$messaggiocaso);
exit;
}
else
//the rest of the code
I tryied with
if (isset($_POST['invia']) && $_POST['invia'] == "Inserisci" && !empty($_POST['file-input[]']))
and !empty($_POST['file-input']
but in these cases, the upload don't work anymore on pc.
So how can I check if file-input is empty?
if ($_FILES['file_input']){
foreach($_FILES['file_input']['name'] as $k=>$v){
if(!empty($_FILES['file_input']['name'][$k])){
if($_FILES['file_input']['size'][$k]>0){
// all ok, can be moved ..
}
}
}
}
Related
Edit 2 : I notices user can upload unlimited files and can take all disk space, how to prevent that?
Edit: since no one answered this question, is there a source I could read to get my answer???
I have a contact form. There are three inputs. I used a jQuery plugin for uploading files. This plugin adds another form element and uploads files by ajax.
I'm kind of beginner but this code is for a customer and a real job so I want to make sure it's safe!
in my view:
<form action="" method="post" enctype="multipart/form-data" >
<input type="text" name="name" />
<input type="number" name="phone" />
<textarea name="enquiry" rows="10" ></textarea>
<div id="upload-div">
<div id="extraupload">Upload</div>
<input type="hidden" name="count" value="0" id="count"/>
<input type="submit" />
$(document).ready(function()
{
var uploadObj = $("#extraupload").uploadFile({
url:"/uplod_url",
fileName:"file",
onSuccess:function(files,data,xhr,pd)
{
data = jQuery.parseJSON(data);
if(data.status == 'success') {
var count = $('#count').val() * 1 + 1;
for(var i=0; i<data.files.length; i++) {
$('<input type="hidden" name="file_'+count+'" value="'+data.files[i]+'">').insertBefore('#extraupload');
$('#count').val(count);
count++;
}
}
},
});
});
</script>
each successful upload,will add one to input count value
and will append an hidden input with the value of uploaded file name.
In php I check for file type and change file name:
upload_url.php:
if ($_FILES['file']['type']=='image/jpeg' || $_FILES['file']['type']=='image/pjpeg') {
$ext = '.jpg';
}
elseif ($_FILES['file']['type']=='image/png') {
$ext = '.png';
}
elseif ($_FILES['file']['type']=='application/pdf') {
$ext = '.pdf';
}
else {
echo json_encode('Only images and pdf files are allowed!');
die();
}
$fileName = md5(uniqid());
$fileName = $fileName.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"], 'image/tmp'.$fileName);
$result = array('status'=> 'success','files' => $fileName);
echo json_encode($result);
After changing the file's name to a unique hash, I save that in a tmp folder.
then when the main form is submitted this is what happens:
//validation method: if that file exists in tmp folder
if(isset($this->request->post['count']) && is_numeric($this->request->post['count'])) {
for($i=1; $i<=$this->request->post['count']; $i++ ) {
if(isset($this->request->post['file_'.$i])){
if(!file_exists('image/tmp/'.$this->request->post['file_'.$i])){
//throw error
}
} else{
//throw error
}
}
}
// hidden input count can only be integer
if(isset($this->request->post['count']) && !is_numeric($this->request->post['count'])) {
//throw error
}
and then mailing the file and saving file name in database(I did not include database part because I'm kind of sure it's ok)
//by every submition delete files in tmp folder older than 1 day
$oldFiles = glob($tmp_dir."*");
$now = time();
foreach ($oldFiles as $oldFile) {
if (is_file($oldFile)) {
if ($now - filemtime($oldFile) >= 60 * 60 * 24) {
unlink($oldFile);
}
}
}
$mail = new Mail();
//Mail Setting and details deleted
//if there's any file uploaded
if($this->request->post['count'] != 0) {
//unique directory for every form submition
$dir_path = 'image/submitted/'.uniqid();
mkdir($dir_path, 0764, true);
//for all hidden inputs move file from tmp folder to $dir_path
for ($i=1; $i <= $this->request->post['count']; $i++) {
$file = $this->request->post['file_'.$i];
rename('image/tmp'.$file, $dir_path.'/'.$file);
$mail->AddAttachment($dir_path.'/'.$file);
}
}
$mail->send();
now my question is: Is it safe this way? especially when I append hidden inputs with file's name and get the number of uploaded files from hidden input count??
This code already works, but I think this might be a security issue.
Thanks a lot for your patience and sorry for my poor english!
ps: I use opencart
There is the general misconception that in AJAX applications are more secure because it is thought that a user cannot access the server-side script without the rendered user interface (the AJAX based webpage). XML HTTP Request based web applications obscure server-side scripts, and this obscurity gives website developers and owners a false sense of security – obscurity is not security. Since XML HTTP requests function by using the same protocol as all else on the web (HTTP), technically speaking, AJAX-based web applications are vulnerable to the same hacking methodologies as ‘normal’ applications.
I am new to php. I am writing a php script which will take only c, cpp and java files and upload them to a server.
Here is my code:
<?php
if(!empty($_POST["file_submit"]))
{
$allowed_xtensions = array("c","cpp","java");
$tmp_xtension_array = explode(".",$_FILES["file_name"]["name"]);
$xtension = end($tmp_xtension_array);
$type = $_FILES["file_name"]["type"];
if((($type == "text/x-java-source") || ($type == "text/x-csrc") || ($type == "text/x-c")) && in_array($xtension,$xtensions))
{
if($_FILES["file"]["error"] > 0)
{
exit( "Unable to process file.\nError : ".$_FILES["file_name"]["error"]);
}
else
{
if(!file_exists("/code/test.",$xtension))
{
if(move_uploaded_file($_FILES["file_name"]["tmp_name"],"/code/test.",$xtension) == false)
{
exit("Unable to process the file.\n");
}
}
}
}
else
{
exit("Invalid File.");
}
}
else
{
$file_form = ' <html>
<body>
<form action="test.php" method="post" enctype="multipart/form-data">
<label for="file"> Select File : </label>
<input type="file" name="file_name" id="file_id"/><br />
<input type="submit" name="file_submit" value="Submit">
</form>
</body>
</html>';
echo $file_form;
}
?>
But whenever I upload c,cpp or java files, I get INVALID FILE in response, although I have uploaded the correct file. Can anyone tell me why my code is showing this behaviour?
shouldn't that be
... && in_array($xtension,$allowed_xtensions) ...
instead of
.... && in_array($xtension,$xtensions) ...
Otherwise, second parameter isn't an array and you might get an error on that and it's always false?
It appears that your variable $type is not being set.
As a test, you might want to stick in this statement near the beginning of your script:
print_r($_FILES);
I suspect that there is no key ['file']['type'] in what's being passed to your script (or at least the values aren't what you're expecting). You can also test for existence using isset($_FILES['file']['type']).
It is also possible that $_FILES is empty. If it is, then try adding enctype="multipart/form-data" to the form tag and make sure file uploads are enabled.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 9 years ago.
Im trying to build an image upload for my site, I have the following only nothing is output at all, yet my page renders okay? Can anybody see where I may be going wrong?\
//if they DID upload a file...
if($_FILES['profile_image']['name'])
{
//if no errors...
if(!$_FILES['profile_image']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['profile_image']['tmp_name']); //rename file
if($_FILES['profile_image']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['profile_image']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['profile_image']['error'];
}
}
else {
echo 'success';
}
<form method="post" action="./process-signup.php" enctype="multipart/form-data" >
<input type="file" class="profile_image text-input" name="profile_image" placeholder="Upload a picture"/><br />
<input type="submit" id="signup-com-btn" value="Complete Signup" />
</form>
In you PHP script, you have assigned the variable $message to different values, on different stages, like this:
$message = 'Oops! Your file\'s size is to large.';
$message = 'Congratulations! Your file was accepted.';
$message = 'Ooops! Your upload triggered the following error:
but you are not actually echoing it out, so you are not getting any message.
SO, I would recommend echoing it, obviously.
In my form I have 3 input fields for file upload:
<input type=file name="cover_image">
<input type=file name="image1">
<input type=file name="image2">
How can I check if cover_image is empty - no file is put for upload?
You can check by using the size field on the $_FILES array like so:
if ($_FILES['cover_image']['error'] == 4 || ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0))
{
// cover_image is empty (and not an error), or no file was uploaded
}
(I also check error here because it may be 0 if something went wrong (ie. a file was selected, but there's no data received). I wouldn't use name for this check since that can be overridden). error with a value of 4 is UPLOAD_ERR_NO_FILE, so we can check for that too.
Method 1
if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
Method 2
if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}
You can check if there is a value, and if the image is valid by doing the following:
if(empty($_FILES['cover_image']['tmp_name']) || !is_uploaded_file($_FILES['cover_image']['tmp_name']))
{
// Handle no image here...
}
if (empty($_FILES['cover_image']['name']))
simple :
if($_FILES['cover_image']['error'] > 0)
// cover_image is empty
check after the form is posted the following
$_FILES["cover_image"]["size"]==0
if (!$_FILES['image']['size'][0] == 0){ //}
if( ($_POST) && (!empty($_POST['cover_image'])) ) //verifies if post exists and cover_image is not empty
{
//execute whatever code you want
}
if(!empty($_FILES)) { // code if not uploaded } else { // code if uploaded }
$_FILES is an associative POST method array, if You want to check anything about $_FILES You must take into account the index... I tried a lot of suggested options, and the only method that worked for me, was when I included an index in my verification method.
$_FILES['Your_File']['name'][0];
So bye doing this:
if(empty($_FILES['Your_File']['name'][0])){
print('this thing is empty');
}else{
print('Something, something, something');
}
There's nothing like good old experimentation and lots of reading.
if($_FILES['img_name']['name']!=""){
echo "File Present";
}else{
echo "Empty file";
}
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
// Code comes here
}
This thing works for me........
<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]" multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >
if($_FILES['imagefile']['name'] == '')
{
$img = $_POST['hidden_imagefile'];
}
else{
$img = '';
$uploadFolder = 'uploads/gallery/';
foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
$imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
$imageName = time() .$_FILES['imagefile']['name'][$key];
$img .= $imageName.',';
$result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
}
}
if ($_FILES['cover_image']['error'] == 4){
// the user did not choose any file
}else{
// the user chose a file to be uploaded
}
This will work
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
// checking if file is selected and not an error
{
// file is not selected and it is not an error
}
UPDATED:
Use this method:
First check if 'cover_image' key exists in $_FILES then check other file errors
if (in_array('cover_image', array_keys($_FILES) && $_FILES['cover_image']['error'] == 0) {
// TODO: write your code
} else {
// return error
}
On my site I have a page where users can upload files to go with the news post they're adding. I allow them to upload one image and one sound file. They don't have to add files if they don't want to, or they can just add one if they want. Problem I'm having is that my script only works if the user selects both files. If they choose none, or only one, then the script spits out 'Invalid File' as it can't find a file where one hasn't been selected.
I tried using:
if (isset($_FILES['filetoupload1'])) {
if (($_FILES["filetoupload1"]["type"] == "image/gif")
|| ($_FILES["filetoupload1"]["type"] == "image/jpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/pjpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/png")
|| ($_FILES["filetoupload1"]["type"] == "image/jpg")
) {
if ($_FILES["filetoupload1"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload1"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload1"]["name"])) {
echo $_FILES["filetoupload1"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload1"]["tmp_name"],
"media/" . $_FILES["filetoupload1"]["name"]
);
}
} else {
echo "Invalid file";
}
}
if (isset($_FILES['filetoupload2'])) {
if ($_FILES["filetoupload2"]["type"] == "audio/mp3") {
if ($_FILES["filetoupload2"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload2"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload2"]["name"])) {
echo $_FILES["filetoupload2"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload2"]["tmp_name"],
"media/" . $_FILES["filetoupload2"]["name"]
);
}
} else {
echo "Invalid file";
}
}
and then
if((isset($_FILES['filetoupload1'])) && (isset($_FILES['filetoupload2']))) { }
before both first and second upload scripts if the user had selected both image and audio file. In other words it did this:
if filetoupload1 isset then run upload script that filters images.
if filetoupload2 isset then run upload script that filters audio.
if filetoupload1 AND filetoupload2 isset then run both upload scripts.
I have it set like that. The above should allow for all combinations of file uploads. right? but it doesnt work so..
Now I have no idea what to do. Here's the upload script for the audio, the image one is pretty much the same:
Can someone tell me what I'm doing wrong please!
"I get the error: Invalid file"
This is correct, since your code just does this.
Do not check if the file is set but if i.e. $_FILES["filetoupload1"]["type"] is not empty.
Your script makes your server vulnerable to a malicious user being able stomp on any file the webserver has access to:
$_FILES[...]['name'] - user supplied
$_FILES[...]['type'] - user supplied
You're trusting that the client has supplied the proper MIME type for the file, but nothing stops someone from forging a request and uploading "virus.exe" and setting the mime type to 'image/jpeg'. As well, since the remote filename is under user control, it can be subverted with malicious data. Consider:
$_FILES['picture']['type'] = 'image/gif'
$_FILES['picture']['name'] = 'remote_server_control.php'
Completely legitimate according to your script, because the mime type is "right", and yet you've now put a user-supplied PHP script on your server and with that they can take total control of your site and/or server.
Never EVER trust the data in the $_FILES array. Always determine MIME types via server-side utilities. If the script is only supposed to handle images, then use getimagesize(). As well, never use user-supplied filenames. Use something determined server-side to give the file a name, like a databasde auto_increment ID number. Even though your code doesn't allow for overwriting existing files, it's trivial to just come up with a new name and boom... new version of the remote takeover script.
I suggest to you to add a hidden text, this hidden will check witch upload fields are active, you make this check with javascript:
<html lang="en">
<head>
<meta charset="utf-8">
<style>
</style>
<script type="text/javascript">
function uploadForm()
{
var size = 0;
var x = document.forms["myForm"]["upload1"].value.length;
var y = document.forms["myForm"]["upload2"].value.length;
if (x > 0)
{
size = 3;
}
if (y > 0)
{
size += 2;
}
return size;
}
</script>
</head>
<body>
<form name="myForm" action="" method="GET" onsubmit="chose.value = uploadForm()">
<input type="file" name="upload1"><br>
<input type="file" name="upload2"><br>
<input type="hidden" name="chose" value=""><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Now, when you receive the form, you have to check the value of chose filed, if its 2, that is mean the image field is not empty, 3 audio filed is not empty, 5 both not empty:
<?php
switch($_GET["chose"])
{
case 2:
//
break;
case 3;
//
break;
case 5:
//
break;
default:
// here the user doesn't use any field
}
?>