Hi i am trying to upload file and sets the limit 1 mb.
when file size is greater than 1 mb file doesn't move in folder but it updates in in mysql database.
<?php
$fileName = $_FILES['myfile']['name'];
$fileNameTmp = $_FILES['myfile']['tmp_name'];
$fileSize = $_FILES["myfile"]["size"];
$fileExtension = explode('.',$fileName);
$fileExtension = strtolower(end($fileExtension));
$maxsize = 1000000;
$fileUniqueName = uniqid().'.'.$fileExtension;
$store = 'uploads/'.$fileUniqueName;
if($fileSize>$maxsize)
{
echo 'size exceed';
}
else
{
move_uploaded_file($fileNameTmp,$store);
$query = mysql_query("update users set image = '$fileUniqueName' where id = '$_SESSION[id]'");
}
?>
Expected result: file name should not update in database if size exceeds 1 mb.
I'm guessing the file didn't upload and you're getting $fileSize equal to 0, bypassing your if condition.
Change it to if($fileSize > $maxsize || $fileSize == 0) to capture the error.
Related
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'].
I'm trying to create a form where users can select an image and set their profile picture. After this I want to get this specific information and display it within HTML.
I have the following code inside profile.php;
if(isset($_POST['submit']) ){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$mysql->setUserAvatar($fileName, $fileTmpLoc, $fileType, $fileSize, $fileErrorMsg, $s_email);
}
I have the following code inside mysql.php (this code is inside a class name mysql):
function setUserAvatar($fileName, $fileTmpLoc, $fileType, $fileSize, $fileErrorMsg, $s_email){
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "Image is too small";
exit();
}
$db_file_name = rand(100000000000,999999999999) . "." . $fileExt;
echo $db_file_name;
if($fileSize > 1048576) {
echo "Image can't be larger than 1MB";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "The file extension should be .gif, .jpg or .png";
exit();
} else if ($fileErrorMsg == 1) {
echo "An unknown error occurred";
exit();
}
$sql = "SELECT avatar FROM users WHERE email='$s_email' LIMIT 1";
$query = mysqli_query($this->db, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$s_email/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, SITE_ROOT . "/../user/$s_email/". $db_file_name);
if ($moveResult != true) {
echo "File upload failed";
exit();
}
$sql = "UPDATE users SET avatar='$db_file_name' WHERE email='$s_email' LIMIT 1";
$query = mysqli_query($this->db, $sql);
}
After this is done, I want to do something like:
<img src="user/" . $s_email . "/" . $data['avatar'] . " />
How ever, when I try to reach the avatar element from the MySQL database, I always get the same number, which is: 2147483647 (but in the user folder everything went right). So there is a problem with the value that is getting inserted into the database. Any suggestions what this problem might be?
EDIT: I've fixed the issue by decreasing the length of the random number. However, the problem is still that the value in the database hasn't receive the extension? The column datatype of avatar is VARCHAR.
It's this line:
$db_file_name = rand(100000,999999) . "." . $fileExt;
Yes, a nice feature of most random number generators is that they produce repeatable results unless you tell them not to.
In the case of PHP you tell it not to start at the same place using srand()
Your number is to big. and not very random.
$db_file_name = rand(100000000000,999999999999)
Your min and max are very close to each other/in wrong order, and to large because the number your getting 2147483647 = 2^30 -1 is most likely the size limit for the type of column input you decided to use for the name.
rand documentation http://php.net/manual/en/function.rand.php
Change your column type to something like varchar(40)
I'd also recommend not using random numbers greater than php's signed 32 bit integer rand(0,2147483647);
I have to upload excel file's data to MySQL database using php. I have found the code for that but I am unable to upload large files.
Can anyone please tell me that how can I increase the max file size limit for the code mentioned in below link:
http://www.9code.in/how-to-import-excel-file-to-mysql-database-using-php/
<!DOCTYPE html>
<?php
include 'db.php';
include 'Excel/reader.php';
function uploadFile($fieldName, $fileType, $folderName, $name = "")
{
$flg = 0;
$MaxID = "";
$ext = "";
$uploadfile = "";
if (isset($fieldName) AND $fieldName['name'] != '')
{
$flg = 1;
$allowed_filetypes = $fileType;
// I Need to increase this..... I tried changing values but nothing happened
$max_filesize = 1048576;
$filename = $fieldName['name'];
if ($name == "")
$MaxID = time() . time() . rand(1, 100);
else
$MaxID = $name;
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if($ext==".xlsx")
$ext=".xls";
if (!in_array($ext, $allowed_filetypes))
echo "<h1>The file you attempted to upload is not allowed...</h1>";
else if (filesize($fieldName['tmp_name']) > $max_filesize)
echo "<h1>The file you attempted to upload is too large...</h1>";
else
{
$uploadfile = $folderName . "/" . $MaxID . $ext;
if (move_uploaded_file($fieldName['tmp_name'], $uploadfile) == FALSE)
{
echo "<h1>Error in Uploading File...</h1>";
$MaxID = "";
}
else
$MaxID = $MaxID . $ext;
}
}
return $MaxID;
}
if(isset($_POST['submit']))
{
if($_FILES['csvFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".csv"),"excel_file");
$row=0;
if(($handle = fopen("excel/".$fileName , "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
//print_r($data);
$query="INSERT INTO StudentData(FirstName,LastName,MobileNo,City)VALUES('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
mysql_query($query);
}
fclose($handle);
}
}
else if($_FILES['excelFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".xls",".xlsx"),"excel_file");
$data = new Spreadsheet_Excel_Reader();
$data->read('excel_file/'.$fileName);
for($i=1;$i<=$data->sheets[0]['numRows'];$i++)
{
$firstname=$data->sheets[0]['cells'][$i][1];
$lastname=$data->sheets[0]['cells'][$i][2];
$mobile=$data->sheets[0]['cells'][$i][3];
$city=$data->sheets[0]['cells'][$i][4];
$query="INSERT INTO StudentData(FirstName,LastName,MobileNo,City)VALUES('".$firstname."','".$lastname."','".$mobile."','".$city."')";
mysql_query($query);
}
}
}
if(isset($_POST['delete']))
{
mysql_query("DELETE FROM StudentData");
}
?>
You can use LOAD DATA command in MySQL : Read More
you have to used load data in mysql statement. This can load your large file in database.
mysqli_query($dblink, '
LOAD DATA LOCAL INFILE "'.$file.'"
INTO TABLE transactions
FIELDS TERMINATED by ","
OPTIONALLY ENCLOSED BY "\'"
LINES TERMINATED BY "\n"
');
Look at these values in your php.ini
upload_max_filesize = 10M
post_max_size = 10M
You need to set the value of upload_max_filesize and post_max_size in your php.ini :
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
I have to add that you have to restart the server
According to ASNAOUI Ayoub I made the following changes:
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
But Stil the Problem was same then I tried to change the
$max_filesize = 41943040
Now It perfectly works.....
Thanks Everyone for the help
I have created a website that uploads anything. The problem I have is that I'm new to all this. I have tried every code that generates random strings but I have nothing. Here is the code anyway:
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "uploads/$fileName")) {
echo '<a href="uploads/'.$fileName.'"><input type="button" class="button"
value="Download" /></a>';
} else {
echo "move_uploaded_file function failed";
}
?>
Could there be a way to generate random file names so that when someone uploads the same name as a file already on the server, it does not overwrite the existing file?
$fileName = "image_".uniqid();
The uniqid() function generates a unique ID based on the microtime
(current time in microseconds).
About uniqid function: http://www.php.net/manual/en/function.uniqid.php
You can use md5(microtime()) to get unique file name even you uploading more than one file at a time
you can use microtime time to make sure file name is unique.
$file_name = "custom_name_" . microtime();
Because a folder is limited to 65535 files, you need to create subfolders. This technique creates 3 subfolders (with 3 characters each) depending on the timestamp then creates a random filename.
For more randomness and future-proofness (because using time() and microtime() is weak if you have multiple users uploading at the same time) :
//Get the extension of the file
$fileExtension = end(explode(".", $_FILES['item']['name']));
$randOctalName = openssl_random_pseudo_bytes(5);
$randName = bin2hex($randOctalName).".".$fileExtension;
//Save it into uploads/123/456/789/
$path = "";
$timestamp = time();
$path = substr($timestamp,0,3)."/".substr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;$timestamp = time();
$path = substr($timestamp,0,3)."/".ubstr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;
_r_mkdir($relativePath);
And the mkdir recursive function :
private function _r_mkdir($path, $mode = 0755, $recursive = true)
{
if(empty($path)){
return false;
}
if($recursive) {
$toDo = substr($path, 0, strrpos($path, '/'));
if($toDo !== '.' && $toDo !== '..'){
_r_mkdir($toDo, $mode);
}
}
if(!is_dir($path)){
mkdir($path, $mode);
}
return true;
}
use the timestamp (or microtime), so you know it is necessarily different every time
$fileName = "image_".time();
TimeStamp
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Microtime
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.
//you can use both random and time function to get more unique no count:
$fileName = 'mypic'.mt_rand(100000, 999999).'_'.time(). $_FILES["file1"]["name"];
use are:-
mt_rand(100000, 999999)// for randm no.
time()// for timestring
$_FILES["file1"]["name"]//also you can give your file name
Study this code thoroughly. This is all you need.
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != "")
{
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileError = $_FILES["avatar"]["error"];
$kaboom = explode(".",$fileName);
$fileExt = end($kaboom);
list($width,$height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10)
{
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 5048576)
{
header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb");
exit();
}
else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) )
{
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
}
else if ($fileErrorMsg == 1)
{
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx,$sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != "")
{
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl))
unlink($picurl);
}
$moveResult = move_uploaded_file($fileTmpLoc,"../user/$log_username/$db_file_name");
if ($moveResult != true)
{
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../user.php?u=$log_username");
exit();
}
?>
try this
$now=date('d/m/y');
if(move_uploaded_file($fileTmpLoc, "uploads/$now.$fileName"))
it will add date infront of the filename
I've run into a conundrum and was wondering if anyone might be able to give me a straight answer. So I built a photo upload script using PHP/MySQL. Within the script photos are re-sized and given a temporary name while being uploaded. I tested it using several pictures (file size 220 KB | 960 x 720) and everything was working just fine. Then I attempted to upload several pictures from my digital camera (file size 2.47 MB | 3000 x 4000) and all of a sudden I got this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /php_parsers/photo_system.php on line 94
Warning: Cannot modify header information - headers already sent by (output started at /php_parsers/photo_system.php:94) in /php_parsers/photo_system.php on line 96
I checked stackoverflow for a post with a similar issue and came upon one however it didn't seem to apply to the scenario I'm experiencing.
Here is the applicable code for "photo_system.php". I have commented the offending lines 94 and 96. Any help/ideas you could give would be greatly appreciated!
<?php
if (isset($_FILES["photo"]["name"]) && isset($_POST["gallery"])){
$sql = "SELECT COUNT(id) FROM photos WHERE user='$log_username'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] > 79){
header("location: ../message.php?msg=The system allows only 80 pictures total");
exit();
}
$gallery = preg_replace('#[^a-z 0-9,]#i', '', $_POST["gallery"]);
$fileName = $_FILES["photo"]["name"];
$fileTmpLoc = $_FILES["photo"]["tmp_name"];
$fileType = $_FILES["photo"]["type"];
$fileSize = $_FILES["photo"]["size"];
$fileErrorMsg = $_FILES["photo"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = date("DMjGisY")."".rand(1000,9999).".".$fileExt; // WedFeb272120452013RAND.jpg
list($width, $height) = getimagesize($fileTmpLoc); //Offending Line 94
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions"); //Offending Line 96
exit();
}
if($fileSize > 4194304) {
header("location: ../message.php?msg=ERROR: Your image file was larger than 4mb");
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
} else if ($fileErrorMsg == 1) {
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$wmax = 800;
$hmax = 600;
if($width > $wmax || $height > $hmax){
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
}
$sql = "INSERT INTO photos(user, gallery, filename, uploaddate) VALUES ('$log_username','$gallery','$db_file_name',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../photos.php?u=$log_username");
exit();
}
?><?php
if (isset($_POST["delete"]) && $_POST["id"] != ""){
$id = preg_replace('#[^0-9]#', '', $_POST["id"]);
$query = mysqli_query($db_conx, "SELECT user, filename FROM photos WHERE id='$id' LIMIT 1");
$row = mysqli_fetch_row($query);
$user = $row[0];
$filename = $row[1];
if($user == $log_username){
$picurl = "../user/$log_username/$filename";
if (file_exists($picurl)) {
unlink($picurl);
$sql = "DELETE FROM photos WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
mysqli_close($db_conx);
echo "deleted_ok";
exit();
}
?>
OK everyone. I figured out what the issue was. Hopefully this will help someone in the future. So I checked my phpinfo() and found that upload_max_filesize was only set to 2M. I added php.ini to the directory of the offending file and included:
upload_max_filesize = 250M
post_max_size = 250M
max_execution_time = 300
date.timezone = "America/Los_Angeles"
I had to add the date.timezone because my system didn't like the fact that I didn't have it defined. Anyway this has resolved the issue.