Set the image upload size - php

I am trying to limit the upload file size to 1MB using the following jQuery code :
<td><label> Upload image </label>
<input type="file" class="upload" name="image" value="<?php echo set_value('image'); ?>" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on('change','.upload',function(){
files = this.files;
size = files[0].size;
//max size 50kb => 50*1000
if( size > 1000141) {
alert('Please upload less than 1mb file');
return false;
}
return true;
});
</script>
When I upload a file greater than 1MB, it displays the error message but the upload goes through successfully. What's causing this?

You can use a hidden field to set the max size.
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
The field must be before the input type=file.
But be careful its easy to bypass the MAX_FILE_SIZE.
You should also check the file size with php.
$size= $_FILES["myfile"]["size"];
if($size > 1000141)
{
//dont upload file
}
else {
//upload file
}

Related

How to check if $_POST[image] is set

Re asking how to check if $_POST[FILE] isset
I have a file input and if I submit my form without an image I want something to happen if I uploaded a file in the input I want something different to happen.
if (!isset($_POST[image])) { }
seems to trigger regardless of whether or not I have uploaded a file in the input or not.
<label>
<p>Profile Picture:</p>
<input type="file" name="image" value="" />
</label>
My last question was marked as a duplicate of this answer Check whether file is uploaded however
if (!file_exists($_FILE['image'])) { }
didn't work either it is still showing truthy even when an image is uploaded. So not the answer I need.
To check if there is a file uploaded is you need to check the size of the file.
Then to check if its an image or not is you need to use the getimagesize() function. See my script below:
HTML:
<form action="index.php?act=s" method="post" enctype="multipart/form-data">
<input type="file" name="image" value=""/>
<input type="submit">
</form>
PHP:
<?php
if(isset($_GET['act'])){
// Check if there is a file uploaded
if($_FILES["image"]["size"]>0){
echo "There is a file uploaded<br>";
// Check if its an image
$check_if_image = getimagesize($_FILES["image"]["tmp_name"]);
if($check_if_image !== false) {
echo "Image = " . $check_if_image["mime"] . ".";
} else {
echo "Not an image";
}
}
else{
echo "There is NO file uploaded<br>";
}
}
?>

move_uploaded_file() only uploads small files

I want to implement a small file upload on a web portal. I found this solution on PHP.net:
<form action='action.php' method='post' enctype="multipart/form-data">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file:
<input name="userfile" type="file"/>
<!-- hidden input fields to sent variables to action.ph -->
<innput type="hidden" name='casenumber' id="caseForFileUpload" />
<input type="hidden" name='key' id="keyForFileUpload" />
<input type="submit" value="Send File" name="uploadfiles"/>
</form>
and this is the relevant part of action.php
if(isset($_POST['uploadfiles'])){
if(!empty($_FILES)){
$target_dir = "upload/";
$target_file = $target_dir.basename($_FILES['userfile']['name']);
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($fileType == "pdf"){
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_file)){
echo "<br><br>File uploaded";
}else{
echo "<br><br>File could not be uploaded";
}
}
}
}
This works well for small files <150KB, but fails for files larger than that and I don't know why this is happening.
Relevant info from php.ini:
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 30
max_input_time = 60
So it really should work for files that are larger than 150KB. There is no message in the PHP log and no .htaccess is used that may override these settings.
Where else can I look to track down this behavior or how else can I implement a file upload to allow file sizes for up to 2MB?
PS: Please also note that the server is still running with PHP 5.2.17 and that it's not in my power to update it to a newer version.
As request by the OP:
name="MAX_FILE_SIZE" value="30000"
That is 30,000 bytes. As per the manual http://php.net/manual/en/features.file-upload.post-method.php
"The MAX_FILE_SIZE hidden field (measured in bytes)".
Either remove that input, or increase it.

Filename cannot be empty

I get this error everytime i hit the submit button. Everything else is submitted to the database, only the image isn't.
Warning: file_get_contents(): Filename cannot be empty
Any idea? Here is my code.
if(isset($_POST['consultationbutton'])){
$image = addslashes(file_get_contents($_FILES['selectedfile']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['selectedfile']['name']);
$checkedcondition = implode(",",$_POST['skincondition']);
$checkedproduct = implode(",",$_POST['skincareinuse']);
$consultquery="INSERT INTO counsel(nric,dateconsulted,editableface,skincarecurrentlyinuse,skincondition,imagename) VALUES('132','$_POST[storedate]','{$image}','$checkedproduct','$checkedcondition','{$image_name}')";
mysqli_query($dbconn,$consultquery);
// mysqli_escape_string($dbconn,$image);
echo $checkedcondition;
echo $checkedproduct;
}
<form action="BAConsult.php" enctype="multipart/form-data" method='post'>
<img id="customerface" src="#" alt="your image" class ="consultimg"></img>
Select a file to upload: <input type="file" name="selectedfile" onchange="readURL(this);">
<input type='submit' name='consultationbutton' class='consultationbutton' value='Complete Consultation' onclick='submitclick();'>
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#customerface')
.attr('src', e.target.result)
.width(400)
.height(400);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
In the $_FILES array, you've said you're getting [name]=>DSC_0770.JPG[type]=> [tmp_name]=>[error]=>1[size]=>0
If tmp_name is not given, that means the file was not uploaded.
The error you're given is 1, and according to the upload error messages explained page this means: that the uploaded file exceeds the upload_max_filesize directive in php.ini.
You can do the following to fix this.
Find your php.ini file and increase the size of upload_max_filesize.
Use ini_set('upload_max_filesize', '20M'); or whatever size you want at the start of your script.
Compress your images before uploading.
make sure you add enctype="multipart/form-data" attribute in your <form> tag. like
<form action="your_action_file" method="post" enctype="multipart/form-data">

How to upload file temporarily and then submit form?

See EDITED QUESTION BELOW
I am currently uploading file with following code. But I want to upload file temporarily and then want to submit form. I mean after selecting audiofile >> Click on upload button next to file upload field..>> Message= file uploaded successfully >> Then click on "Submit" Button to upload all data and temporarily uploaded file in mysql and audio file in related folder....
Currently , with this code I am unable to upload larger files. And after long wait, I get error message like "webpage in not available"
I tried php.ini and .htaccess file update for max_execution_time, upload_max_filesize etc... also mod_security is disabled on server...
PHP code :
<?php
session_start();
// Database connection
include("../include/function.php");
include("commonfiles/validate.php");
// Create an object for an class
$bsq=new bsq();
//use class function to connect the database
$bsq->connect_db();
//
$fileName = $_FILES["audio"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["audio"]["tmp_name"];
// Path and file name
$pathAndName = "uploadsaudio_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
$fileName1 = $_FILES["doc"]["name"];
$fileNameNew1 = preg_replace('/\s+/', '_', $fileName1);
$fileTmpLoc1 = $_FILES["doc"]["tmp_name"];
// Path and file name
$pathAndName1 = "uploadsaudiodoc_admin/".$fileNameNew1;
// Run the move_uploaded_file() function here
$moveResult1 = move_uploaded_file($fileTmpLoc1, $pathAndName1);
// Evaluate the value returned from the function if needed
$fileName2 = $_FILES["pdf"]["name"];
$fileNameNew2 = preg_replace('/\s+/', '_', $fileName2);
$fileTmpLoc2 = $_FILES["pdf"]["tmp_name"];
// Path and file name
$pathAndName2 = "uploadsaudioppt_admin/".$fileNameNew2;
// Run the move_uploaded_file() function here
$moveResult2 = move_uploaded_file($fileTmpLoc2, $pathAndName2);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$all_columns[]="file_subject";
$all_columns[]="full_name";
$all_columns[]="upload_date";
$all_columns[]="display_date";
$all_columns[]="message";
$all_columns[]="audio";
$all_columns[]="doc";
$all_columns[]="pdf";
$display=date('Y-m-d', strtotime("+1 Day"));
//Get All values to insert in to table
$all_values[]=addslashes($_POST["file_subject"]);
$all_values[]=addslashes($_POST["full_name"]);
$all_values[]=addslashes($_POST["upload_date"]);
$all_values[]=$display;
$all_values[]=addslashes($_POST["message"]);
$all_values[]=addslashes($pathAndName );
$all_values[]=addslashes($pathAndName1 );
$all_values[]=addslashes($pathAndName2 );
//=====================
$qry=$bsq->webdreaminsert("eo_uploadsaudio_by_admin",$all_columns,$all_values,'');
echo mysql_error();
header("location:upload_audiofile_for_downloading_list.php");
}
?>
And HTML Form code:
<form action="" method="post" enctype="multipart/form-data" name="addtwebinar1" id="addtwebinar1" onsubmit="javascript:return validateimage1();" >
<input type="hidden" value="add" name="action" />
1) Audio File Subject* : <input name="file_subject" id="file_subject" type="text" value="" />
2) File Owner Name : <input name="full_name" id="full_name" type="text" value="" />
3) Session Conducted On : <input type="text" autocomplete="off" name="upload_date" id="upload_date" placeholder="Click To Open calendar" readonly="readonly" />
4) Your Audio File For Upload : <label for="audio">Audio File To Upload: </label><br>
<input type="file" name="audio" id="audio" />
// Here I want temporary upload button with message "Upload successfully / Not Uploaded..." etc.....
5) Your Doc File For Upload : <label for="doc">Doc File To Upload: </label><br>
<input type="file" name="doc" id="doc" />
6) Your Question Answer File For Upload : <label for="pdf">Question Answer For Practice File To Upload: </label><br>
<input type="file" name="pdf" id="pdf" />
7) Message If Any : <textarea name="message" id="message" cols="" rows="3" placeholder="Message"></textarea>
<button>SUBMIT</button>
</form>
I want to add Upload Button Next to field number 4 where audio file will be uploaded temporarily and then after filling up other fields, form will be get submitted....
Or Any other solution to upload larger files ( around 40 to 50 MB size each) without any error with low internet speed ?
EDITED QUESTION :
I used ajax for file uploading..... Now file gets uploaded to folder even 26 MB But mysql database is not getting updated.....
I have edited HTML code as follow with javascript :
1) Audio File Subject* : <input name="file_subject" id="file_subject" type="text" value="" />
2) File Owner Name : <input name="full_name" id="full_name" type="text" value="" />
3) Session Conducted On : <input type="text" autocomplete="off" name="upload_date" id="upload_date" placeholder="Click To Open calendar" readonly="readonly" />
4) Your Audio File For Upload : <label for="audio">Audio File To Upload: </label><br>
<input type="file" name="audio" id="audio" />
// Here I want temporary upload button with message "Upload successfully / Not Uploaded..." etc.....
5) Your Doc File For Upload : <label for="doc">Doc File To Upload: </label><br>
<input type="file" name="doc" id="doc" />
6) Your Question Answer File For Upload : <label for="pdf">Question Answer For Practice File To Upload: </label><br>
<input type="file" name="pdf" id="pdf" />
7) Message If Any : <textarea name="message" id="message" cols="" rows="3" placeholder="Message"></textarea>
<button>SUBMIT</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"> </script>
<script src="source/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%' + '' + 'Completed...';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
window.location.href='upload_audiofile_for_downloading_list.php';
}
});
})();
</script>
And Code in upload_audiofile_process.php :
<?php
session_start();
include("../include/function.php");
include("commonfiles/validate.php");
include("fckeditor.php");
//=================================================================================
// Create an object for an class
$bsq=new bsq();
//use class function to connect the database
$bsq->connect_db();
$fileName = $_FILES["image"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image"]["tmp_name"];
// Path and file name
$pathAndName = "uploadsaudio_admin/".$fileNameNew;
// Evaluate the value returned from the function if needed
$fileName1 = $_FILES["doc"]["name"];
$fileNameNew1 = preg_replace('/\s+/', '_', $fileName1);
$fileTmpLoc1 = $_FILES["doc"]["tmp_name"];
// Path and file name
$pathAndName1 = "uploadsaudiodoc_admin/".$fileNameNew1;
// Evaluate the value returned from the function if needed
$fileName2 = $_FILES["pdf"]["name"];
$fileNameNew2 = preg_replace('/\s+/', '_', $fileName2);
$fileTmpLoc2 = $_FILES["pdf"]["tmp_name"];
// Path and file name
$pathAndName2 = "uploadsaudioppt_admin/".$fileNameNew2;
// Evaluate the value returned from the function if needed
if (isset($_FILES["image"])) {
if ($_FILES["image"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
move_uploaded_file($fileTmpLoc, $pathAndName);
move_uploaded_file($fileTmpLoc1, $pathAndName1);
move_uploaded_file($fileTmpLoc2, $pathAndName2);
$all_columns[]="file_subject";
$all_columns[]="full_name";
$all_columns[]="upload_date";
$all_columns[]="display_date";
$all_columns[]="message";
$all_columns[]="image";
$all_columns[]="doc";
$all_columns[]="pdf";
$display=date('Y-m-d', strtotime("+1 Day"));
//Get All values to insert in to table
$all_values[]=addslashes($_POST["file_subject"]);
$all_values[]=addslashes($_POST["full_name"]);
$all_values[]=addslashes($_POST["upload_date"]);
$all_values[]=$display;
$all_values[]=addslashes($_POST["message"]);
$all_values[]=addslashes($pathAndName );
$all_values[]=addslashes($pathAndName1 );
$all_values[]=addslashes($pathAndName2 );
//=====================
$qry=$bsq->webdreaminsert("eo_uploadsaudio_by_admin",$all_columns,$all_values,'');
echo mysql_error();
}
}
?>
This code is working for 10-15 MB file upload.... BUT if file is larger than 20 MB...NOT WORKING....
You can solve your problem with this way.
First call ajax function on your upload button.
$.ajax({
url: 'example.php',
type: 'POST',
data: fileData,
success: function(data) {
// set file name or file id in some field using jquery.
$('#fileHiddenFieldId').val(data);
// and then set css property 'display:block' for submit button.
$('#submitButtonId').css('display','block');
}
});
Here url example.php is filepath where you put your php file upload code.
'fileData' is your uploaded file data which you post.
When you get success response then set file id or file name in some hidden field then display submit button.

PHP - Image Upload , move_uploaded_file not working?

I have coded a image upload script but when I click upload i get redirected to the upload page?
Here is the code:
$image1name = $_FILES['image1']['name'];
$image1crntloc = $_FILES['image1']['tmp_name'];
$image1ext = pathinfo($image1name, PATHINFO_EXTENSION);
$image1size = $_FILES['image1']['size'];
$allowedext = array("jpg","gif","png");
//check image 1 extension.
if (!in_array($image1ext,$allowedext))
{
echo "<script>alert(\"Image 1 has an invalid file.\");</script>";
}
else{
$image1final = md5(time($image1name));
$saveimage1 = "../images/".$image1final.".".$image1ext;
$image1uploadresult = move_uploaded_file($image1crntloc, $saveimage1);
if ($image1uploadresult == TRUE)
{
echo "uploaded.";
}
else{
echo "image not uploaded.";
}
as soon as i click upload, i get redirected to the page where the user selects the image ,i have also checked the directory and nothing gets uploaded?
There is no PHP error shown as well.
Any help?
Thanks.
CODE FOR FORM:
<form id="new-ad" name="new-ad" method="post" action="includes/create.php" enctype="multipart/form-data">
<div class="form-group animated fadeIn">
<label class="labelcustom" for "image1">Image #1:</label>
<br />
Select image to upload:
<input type="file" class="form-control" name="image1" id="image1" />
<input type="submit" name="submit" />
</form>
In your code you are missing the closing bracket on your else statement:
else {
echo "image not uploaded.";
}
Should be:
else {
echo "image not uploaded.";
}
}
In your form, you forgot the max file size. Add <input type="hidden" name="MAX_FILE_SIZE" value="2097152" /> to it, were value is the max size in bytes to accept in the form.

Categories