get uploaded file size in bytes in php - php

I am uploading a file which is an image. I want to get the size of that image every time in bytes only using PHP. I had done this by far
$name=$_FILES['image']['name'];
if($name!=null)
{
$tmpDest=$_FILES['image']['tmp_name'];
$size=$_FILES['image']['size'];
$perDestination="main/$name";
$result=move_uploaded_file($tmpDest,$perDestination);
echo $size;
}

Your code is right, the below line will give you the size in bytes:
size=$_FILES['image']['size'];
You can also get the file size after the file has been uploaded this way:
echo filesize($perDestination) . ' bytes';
This option will also give you the file size in bytes

You can check like this
<?php
if(isset($_FILES['file']) {
if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
// File too big
} else {
// File within size restrictions
}
}
check this out
http://www.w3schools.com/php/php_file_upload.asp

Related

Save processes in cache and save at once in a text file

I use the following code to get the size of the files in a folder. As you can see, to save the size of a file in a text file, you have to open and close the text file from the hard drive each time. I want to first store all the information in cache (RAM) and then at once in a text file. Do you think this will speed things up? Do you have an idea and code to do this?
<?php
$dir = 'img/';
foreach (glob($dir."*.png") as $filename) {
$filesize = 'File Size: '.round((filesize($filename)/1024/1024),2).' MB';
echo $filesize."</br>";
fwrite(fopen("result.txt", "a"), $filesize."\n");
fclose("result.txt");
}
?>
<?php
$dir = 'img/';
$result='';
foreach (glob($dir."*.png") as $filename)
{
$filesize = 'File Size: '.round((filesize($filename)/1024/1024),2).' MB';
echo $filesize."</br>";
$result.=$filesize."\n";
}
fwrite(fopen("result.txt", "a"), $result."\n");
fclose("result.txt");
?>
This way you saving all content to $result and write content to file once after all sizes checked.

PHP Limit upload size validation

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'].

PHP File Upload Size Issue

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';
}

Warning: getimagesize(): Filename cannot be empty php

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.

Restrict file upload to just jpegs with php

Please can someone help? I have the following code which uploads a file to my server and renames it to whoever the logged in user is. For example the user 'coca-cola-lover' uploads a jpeg - the script would also rename the jpeg 'coca-cola-lover.jpg'.
My problem is that I need it to limit the upload to just jpegs - and also limit the file size to 2mb.
Please help - I was trying to find a solution all night.
Thanks in advance
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
getimagesize tells you what format the file is in
as per bgy's comment, you should also force the file extension to be what you want:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
never trust and never use filenames provided by the client.
I would recommend exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
For details see here: http://php.net/manual/en/function.exif-imagetype.php
You can use any of the four to detect a mimetype of the file:
finfo_open (by default enabled as of 5.3)
getimagesize (requires enabled GD)
exif_imagetype (requires enabled Exif)
mime_content_type (deprecated as of 5.3)
You can also limit the MimeType from the FileUpload element, but since this is client-side code, it can easily be removed by malicious users (and it's also buggy across browsers):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
For further information on how to handle file uploads with PHP (including limiting file size), check the manual.
There is also a lot of very similar questions on Stack Overflow already, one being:
Check picture file type and size before file upload in php
You restrict the size via the normal mechanisms, but you'll need to use the fileinfo functions to determine the filetype after uploading.
A few advices for the current code
Use $_FILES instead of $HTTP_POST_FILES.
If you need to get file extensions use $extension = pathinfo($filename, PATHINFO_EXTENSION);.
Use is_uploaded_file and move_uploaded_file.
Don't relay on $_FILES['file']['type'] - it can be modified by user.
Indent your code.
If you want to limit file upload to the following requirements:
Filesize: max 2mb.
File type: image/jpeg
Do something like that:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}

Categories