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
Related
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.
Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer
I want to upload files from my server. I had written this piece of code months ago when it worked fine, but now I have no idea what's going wrong.
I basically want to move the file to a folder "uploads" in my server and then store the path in the database.
The uploaded file doesn't get reflected in the database.
if(isset($_POST['submit']))
{
require("dbconn.php");
$filename = $_POST['filename'];
$name = $filename . "." . pathinfo($_FILES['ufile']['name'],PATHINFO_EXTENSION);
//$name = $_FILES['ufile']['name'];
//$size = $_FILES['file']['size']
//$type = $_FILES['file']['type']
$tmp_name = $_FILES['ufile']['name']; //was tmp_name
$error = $_FILES['ufile']['error'];
if(isset($name))
{
if(!empty($name))
{
$location = 'uploads/';
if(move_uploaded_file($tmp_name, $location.$name))
{
echo "hi";
$filename = $_POST['filename'];
$filepath = $location.$name;
$advname = $_POST['advname'];
$year = $_POST['year'];
$cname = $_POST['cname'];
$ctype = $_POST['ctype'];
$sqlq = "INSERT INTO file(filename, filepath, advname, year, cname, ctype) VALUES ('".$filename."','".$filepath."','".$advname."','".$year."','".$cname."','".$ctype."');";
$result = mysql_query($sqlq);
if(!$result)
{
die("Error in connecting to database!");
}
}
}
}
}
There seems to be a problem in the
if(move_uploaded_file($tmp_name, $location.$name))
statement. This condition is evaluated as false.
If $_FILES['ufile']['error'] gives you a value of 1 then the upload_max_filesize in your config is set to a smaller value that the file you are trying to upload.
You cannot change the upload_max_filesize from within your code.
If you have access to your php.ini, .htaccess, httpd.conf or .user.ini you can change this value in any of those files.
So you would need to add or modify the parameter from its default of 2M (2meg)
upload_max_filesize = 20M
Its also a good idea to check the post_max_size at the same time as this may also have an effect on the max size of the file uploaded, make sure post_max_size is larger than upload_max_filesize as this should allow extra space for the other fields that you will be uploading as part of the post
Using php 5.4.34 And Laravel 4 with apache 2.2.22 and Ubuntu.
Using the library https://github.com/goodby/csv to parse a csv uploaded.
here is my code :
$file = Input::file('file');
//echo $file->getClientOriginalName();
$config = new LexerConfig();
$config
->setDelimiter(";")
->setToCharset('UTF-8')
;
$lexer = new Lexer($config);
$interpreter = new Interpreter();
$salarie_csv = [];
$errors = [];
$lineNb = 0;
$interpreter->addObserver(function (array $rows) use (&$salarie_csv, &$lineNb, &$errors) {
//some code
});
$lexer->parse($file, $interpreter);
return Response::json($errors, 200);
When I upload a 1.5Mb size csv with 20.000 rows it works.
When I upload a 2.5Mb size csv with 38.500 rows it give me the error :
SplFileObject::__construct():Filename cannot be empty in Lexer.php line 50.
i tried with the same file (just removed or add some rows for the test)
Is there a way to fix this ?
Check your post_max_size and upload_max_filesize in your php.ini config file.
PHP probably does not allow too big files to be uploaded, so it cuts it off from post.
var_dump( ini_get('post_max_size') );
Note, that post_max_size overrides upload_max_filesize (as explained in answer here), you should make sure that both of those settings allow sizes that you'll be uploading.
Try This..........
$type=$_FILES['file']['type'];
$filename=$_FILES["file"]["tmp_name"];
$filename_csv = explode(".", $_FILES["file"]["name"]);
$extension = end($filename_csv);
if($extension=="csv")
{
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = mysql_query("insert into upload_data(spent,click,filename,date) values('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')") or die (mysql_error());
mysql_query($sql);
}
fclose($file);
echo $error1=ucwords('<div style="margin-left:60px;position: absolute;width: 400px; color: #006400;">CSV File has been successfully Imported</div>');
}
}
else
{
echo $error1=ucwords('<div style="margin-left:60px;position: absolute;width: 400px; color: #CC0000;">Invalid File:Please Upload CSV File</div>');
// echo 'Invalid File:Please Upload CSV File';
}
Whenever I try to upload a ZIP File via PHP, the Filesize is 0.
Everything else works: 7z, rar, png, xml
for example (I output filesize and location for testing):
File Location: /tmp/phpKNortG/feba81fed1ff5d2c04aa0c42975eb94f.7z
Filesize: 1284
File Location: /tmp/phpEWrmLT/feba81fed1ff5d2c04aa0c42975eb94f.zip
Filesize: 0
My form has enctype="multipart/form-data" and the file is definitely not too big to be uploaded. (I've also set the memory limit to 128 MB to make sure it's not that)
ini_set('memory_limit', '128M');
set_time_limit(0);
$session_id = "3423840093480344";
mkdir('uploaded_files/' . $session_id);
for($i = 0; $i < count($_FILES['backup_file']['name']); $i++) {
$file_name = $_FILES['backup_file']['name'][$i];
$file_type = $_FILES['backup_file']['type'][$i];
$file_error = $_FILES['backup_file']['error'][$i];
$file_size = $_FILES['backup_file']['size'][$i];
$file_tmp = $_FILES['backup_file']['tmp_name'][$i];
print($file_name . "<br />");
print($file_type . "<br />");
print($file_error . "<br />");
print($file_size . "<br />");
print($file_tmp . "<br />");
if($file_error != 0) {
echo "Error-Code: ".$file_error;
continue;
}
move_uploaded_file($file_tmp, 'uploaded_files/' . $session_id);
}
The following code outputs this:
feba81fed1ff5d2c04aa0c42975eb94f.zip
application/zip
0
0
/tmp/phpEWrmLT
It even recognizes the MIME-Type, but the file is always zero bytes in size. (even before moving it with move_uploaded_file)
Is there any server setting that could prevent .zip files to be uploaded?
The memory_limit setting has no bearing on file uploads.
What are the values for your post_max_size and upload_max_filesize and how does the .zip filesize compare with those values?