I want to ask about PHP Limit upload size validation
I have made the code to limit size upload, but thats still get error
My limit size is 500 Kb
when I upload file above 500Kb to 2Mb, the validation is working
but when my file size above 2Mb, the validation isnt working
here is my first code
$maxsize = 500000;
if(($_FILES['myfile']['size'] >= $maxsize) || ($_FILES["myfile"]["size"] == 0)) {
$error = true;
array_push($error_cause, "<li>File size is over limit");
}
and this is my second code
if ($myfile->getSize() > 500000) {
$error = true;
array_push($error_cause, "<li>File size is over limit");
}
To make it clearer, i make a GIF about the problem
Here
Arithmetic 101: 5MB ===> 5 * 1024 * 1024 bytes
To keep code clear, I often define units as constants:
<?php
define('KB', 1024);
define('MB', 1048576);
define('GB', 1073741824);
define('TB', 1099511627776);
// Then you can simply do your condition like
ini_set('upload_max_filesize', 5*MB);
if (isset ( $_FILES['uploaded_file'] ) ) {
$file_size = $_FILES['uploaded_file']['size'];
$file_type = $_FILES['uploaded_file']['type'];
if (($file_size > 0.5*MB) && ($file_size < 2*MB)){
$message = 'File too large. File must be more than 500 KB and less than 2 MB.';
echo $message;
}
Simple method:
$min = 500; //KB
$max = 2000; //KB
if($_FILES['myfile']['size'] < $min * 1024 || $_FILES['myfile']['size'] > $max * 1024){
echo 'error';
}
The value of upload_max_filesize in php.ini is 2MB by default. Any file larger than this will be rejected by PHP.
You'll want to change the value in your php.ini file, and make sure to also adjust the post_max_size setting, as this is also considered for uploaded files.
When the uploaded file size is larger than the limit, the $_FILES array will be empty and you won't detect the upload at all (and thus, you won't show any errors).
You can see the actual uploaded file size by looking at the value fo $_SERVER['CONTENT_LENGTH'].
Related
I've used this private function to file upload in CodeIgniter Project. I've never set max_size in this function. Here, how to set max_size in this private function?
private function do_upload($value){
$type = explode('.', $_FILES[$value]["name"]);
$type = $type[count($type)-1];
$url = "./assets/uploads/products/".uniqid(rand()).'.'.$type;
if(in_array($type, array("jpg","jpeg","gif","png")))
if(is_uploaded_file($_FILES[$value]["tmp_name"]))
if(move_uploaded_file($_FILES[$value]["tmp_name"], $url))
return $url;
return "";
}
just simply do this.
if($_FILES["my_file_name"]['size'] > 1900000){ //set my_file_name to yours <input type="file" name="my_file_name">
echo "file is too large";
}else{
echo "file meets the minimum size";
}
if you want to set bigger upload size to your system, you need to go to php.ini file and change this.
upload_max_filesize = 2M; //change this to your desired size.
hope that helps.
You can get size of that file by $_FILES['uploaded_file']['size'],
for example:
$maxsize=2097152;
if(($_FILES['uploaded_file']['size'] >= $maxsize)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
you can create a php.ini file at your websites base folder
and add following (2M = 2 megabyte you can add your desired size )
upload_max_filesize = 2M;
on it
AS recommend: https://codeigniter.com/userguide3/libraries/file_uploading.html
2MB (or 2048 KB) So that:
$config['max_size'] = 1024 * 10; // <= 10Mb;
I have to upload 5.7MB database in drupal-7 using module "backup and migrate". But, when I upload the file it throws out following error:
The file email839805758.zip could not be saved, because it exceeds 2 MB, the maximum allowed size for uploads.
I have changed post_max_size = 20M and upload_max_filesize = 40M in php.ini file and created user.ini in /etc/php/5.6/apache2/conf.d/user.ini. and pasted post_max_size and upload_max_filesize greater than 2M. I have checked phpinfo(). It just gives the default value to 2M. Does anybody have any solution to such kind of scenerio in drupal 7?
I have found some additional stuff in drupal backup_migrate.module file which might be the barrier. Help me crack this function.
/**
* A custom version of format size which treats 1GB as 1000 MB rather than 1024 MB
* This is a more standard and expected version for storage (as opposed to memory).
*/
function backup_migrate_format_size($size, $langcode = LANGUAGE_NONE) {
$precision = 2;
$multiply = pow(10, $precision);
if ($size == 0) {
return t('0 bytes', array(), array('langcode' => $langcode));
}
if ($size < 1024) {
return format_plural($size, '1 byte', '#count bytes', array(), array('langcode' => $langcode));
}
else {
$size = ceil($size * $multiply / 1024);
$string = '#size KB';
if ($size >= (1024 * $multiply)) {
$size = ceil($size / 1024);
$string = '#size MB';
}
if ($size >= 1000 * $multiply) {
$size = ceil($size / 1000);
$string = '#size GB';
}
if ($size >= 1000 * $multiply) {
$size = ceil($size / 1000);
$string = '#size TB';
}
return t($string, array('#size' => round($size/$multiply, $precision)), array('langcode' => $langcode));
}
}
Put in phpinfo() in your script and see which php.ini file you are using. Go into that file and change those values. Please keep in mind the daemon has to be restarted (php-fpm or apache) in order for the changes to be activated.
If you can not do that for some reason, you can always use the ini_set() function locally while this is highly discouraged!
Check with phpinfo() what php config file was used. To me it looks like you edited wrong php.ini. Also, don't forget to restart your web server (Apache?).
I am kind of experimenting with the PHP Image saving.
I want to compare the image's actual file sizes before upload and after resize/compress processing, but want to know the file size that will going to be if I save it to the disk.
So that if the file size is less, then the newly processed file will replace old one, else no change will be made.
This is the code I am using to save jpeg image.
imagejpeg($this->newImage, $savePath, $imageQuality);
I tried getting the actual file size and size after
print_r(filesize($actual_file_size));
print_r($this->newImage);
where $actual_file_size gives the data by reading from tmp object file, however $this->newImage is giving blank (no value).
I am using ResizeImage class from github
Is there any way I can get the file size before saving to disk? So that I can keep the minimal size version.
This is how you do it:
$original_file = 'original.jpg';
$resized_file = 'resized.jpg';
$max_file_size = '10000';
$original_image = imagecreatefromjpeg($original_file);
$image_quality = 100;
do {
$temp_stream = fopen('php://temp', 'w+');
$saved = imagejpeg($original_image, $temp_stream, $image_quality--);
rewind($temp_stream);
$fstat = fstat($temp_stream);
fclose($temp_stream);
$file_size = $fstat['size'];
}
while (($file_size > $max_file_size) && ($image_quality >= 0));
if (-1 == $image_quality) {
echo "Unable to get the file that small. Best I could do was $file_size bytes at image quality 0.\n";
}
else {
echo "Successfully resized $original_file to $file_size bytes using image quality $image_quality. Resized file saved as $resized_file.\n";
imagejpeg($new_image, $resized_file, $image_quality + 1);
}
This requires no file to be written until you've successfully found the ideal compression ratio.
This loop starts with an $image_quality of 100, then counts downward trying each new value on a temporary in-memory buffer. If gets down to trying 0 and the file would still be too big, it returns an error message. Otherwise, if it gets to a value that works, it reports that and saves the new file using that image quality setting.
If you're feeling adventurous, you could implement a binary search algorithm to find the ideal compression ratio more quickly, but this quick-fix gives the same result, albeit possibly a tad slower.
There is no way to calculate the size before saving it to the disk. I advice you create some kind of temporary folder to save the image, then check the size and if it is what you want move it to the folder you see fit, if you dont want to save it, delete it from the temporary folder.
Not really true.
There is a way..
The following piece of code works with JPEG and PNG :-)
///######## GET THE TOTAL PIXELS
$total_pixels = $image_width * $image_height;
$size_at_max = (3 * $total_pixels) * 0.001; /// **** IN KB
Brian's answer was a bit slow with large numbers of pictures... so I used a loop which modified by half the distance each time (how some digital volt meters work)...
So quality changes in steps 50, 25, 12.5 ... etc and can go up or down as needed...
$max_file_size = 100000; //100k max saved file size
$delta = 10000; //10k distance off max when OK to stop optimizing...
$n = 1;
$quality = 100;
$size = image_size($image, $quality);
if ($size > $max_file_size) {
while ((($size > $max_file_size + $delta) or ($size < $max_file_size - $delta))) {
if ($size > $max_file_size) $quality = $quality - (100 / (2 ** $n));
elseif( $size < $max_file_size) $quality = $quality + (100 / (2 ** $n));
else break;
$size = image_size($image, $quality);
$n++;
}
}
function image_size ($image, $quality) {
ob_start();
imagewebp($image, NULL, $quality);
$size = ob_get_length();
ob_end_clean();
return $size;
}
I am trying to upload PDF file using PHP Script, The below is my code. It works perfectly for any file which is less than 1 MB, but when I upload more than 1 MB, It goes to the else statement and gives this message - "Max File Size Upload Limit Reached, Please Select Any Other File".
I have already seen php.ini configuration, this is set at 16M. Please help
ini_set('upload_max_filesize', '16M');
ini_set('post_max_size', '16M');
//$ImageName=addslashes($_REQUEST['txtimagename']);
//$ImageTitle=addslashes($_REQUEST['txtimagetitle']);
$filepath="files/";
//$filedt=date("dmYhisu")."_.".pathinfo($_FILES['imagefile']['name'], PATHINFO_EXTENSION);
$filedt=$_POST['vehregistration'].".".pathinfo($_FILES['imagefile']['name'], PATHINFO_EXTENSION);
//basename($_FILES['photoimg']['name']);
$destination_img=$_POST['vehregistration'].".".pathinfo($_FILES['imagefile']['name'], PATHINFO_EXTENSION);
$filename=$filepath.$destination_img;
//$filename=$filepath.basename($_FILES['Photo']['name']);
//echo "$filepath".$_FILES[" imagefile "][" name "];
if(move_uploaded_file($_FILES["imagefile"]["tmp_name"], $filename))
{
//echo $filedt;exit;
//rename($_FILES['Photo']['tmp_name'],$filedt);
return $filedt;
}
else
{
echo "Max File Size Upload Limit Reached, Please Select Any Other File";
}
}
Add this in else condition $_FILES['imagefile']['error'] and see what is exact error . For more details http://php.net/manual/en/features.file-upload.errors.php
Instead of using ini_setuse $_FILES["imagefile"]["size"]
$fileSize = $_FILES["imagefile"]["size"]; // File size in bytes
$maxFileSz = 16777216; // set your max file size (in bytes) in this case 16MB
if($fileSize <= $maxFileSz) {
// everything is okay... keep processing
} else {
echo 'Max File Size Upload Limit Exceeded, Please Select Any Other File';
}
I had asked this question and found out that the PHP configuration was limiting my uploads to 2MB, so I fixed it to 3MB. However, I have another problem now: I am also checking for image dimension and it is failing if the image appears to be over 3MB, throwing the below error. So how could I stop the error and check the size by myself instead of the PHP config?
Warning: getimagesize(): Filename cannot be empty
Here is the code:
$size = $_FILES['image']['size'];
list($width, $height) = getimagesize($_FILES['image']['tmp_name']);
$minh = 400;
$minw = 600;
$one_MB = 1024*1024; //1MB
if($size > ($one_MB*3))// this is not checking the size at all, the last echo is what I get if I try to upload over 3mb.
{
echo"File exceeds 3MB";
}
elseif ($width < $minw ) {
echo "Image width shouldn't be less than 600px";
}
elseif ($height < $minh){
echo "Image height shouldn't be less than 400px";
}
else{
if (move_uploaded_file($_FILES['image']['tmp_name'], $new_location)){
//do something
}
else{
echo "Image is too big, try uploading below 3MB";
}
}
Looks like the upload went wrong at some point. Try adding some error handling before getimagesize():
if (!file_exists($_FILES['image']['tmp_name'])) {
echo "File upload failed. ";
if (isset($_FILES['upfile']['error'])) {
echo "Error code: ".$_FILES['upfile']['error'];
}
exit;
}
It's hard to say why it has failed, as there are many parameters involved. The Error code might give you a hint.
Otherwise maybe start reading here: http://de2.php.net/manual/en/features.file-upload.php
I was also having the same error, go to php.ini and go to line 800 "upload_max_filesize".
Choose your max upload file size, i set mine to 4M and in my actual website code I dont allow anything after 3mb.
For some reason having them both the same size doesnt work, PHP.ini needs to be atleast 1mb bigger than what you allow to be uploaded.