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';
}
Related
I need to handle a file in a Laravel controller,
TL;DR
How to handle big files through laravel requests?
When I make the request with the small file, its tempPath is normal: /tmp/php3Hijl5
But when I make a request for a large file it comes: /home/p.../public
This can happen because php defines a maximum size in php.ini called upload_max_filesize.
Trying to solve this problem, I'm setting the project to a larger upload_max_filesize:
ini_set('upload_max_filesize', '50M');
But this thing is not reflecting in the project, because when I give ini_get('upload_max_filesize');
it returns a '2M'.
When I try to handle the file with fgetcsv() it says that this tempPath is a directory.
Im using dd() to check the file tempPath.
Controller.php
public function assignToClients(Request $request, $id)
{
$file = $request->file('csv_joining_clients');
if (!$file) {
return response([
'message' => 'You have to upload a CSV file'
], 400);
}
$array = $this->parseCsvToString($file);
dd($array);
}
private function parseCsvToString($file)
{
$i = 0;
$importData_arr = [];
$tempPath = $file->getRealPath();
dd($tempPath);
$file = fopen($tempPath, 'r');
while (($filedata = fgetcsv($file, 10000, ",")) !== false) {
$num = count($filedata);
for ($c = 0; $c < $num; $c++) {
$importData_arr[$i][] = $filedata[$c];
}
$i++;
}
fclose($file);
return $importData_arr;
}
Code
if(is_array($_FILES) && isset($_FILES['photography_attachment'])) {
if(is_uploaded_file($_FILES['photography_attachment']['tmp_name'])) {
$fileName = $_FILES["photography_attachment"]["name"]; // The file name
$fileTmpLoc = $_FILES["photography_attachment"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["photography_attachment"]["type"]; // The type of file it is
$fileSize = $_FILES["photography_attachment"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["photography_attachment"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
$error = $error."<p>Please browse for a file before clicking the upload button.</p>";
} else if($fileSize > 10485760) { // if file size is larger than 2 Megabytes
$error = $error."<p><span>Your file was larger than</span> 10 <span>Megabytes in size</span>.</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if (!preg_match("/.(gif|jpg|png|jpeg)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
$error = $error."<p>Your file was not .gif, .jpg, .png</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
$error = $error."<p>An error occured while processing the file. Try again.</p>";
}
}else{ $error = "Please try again !!!"; }
}else{ $error = "Attachment field cannot be blank!"; }
Always goto "Please try again !!!" else while uploading image in windows, but it worked well in linux system.
Can you please any one help me for this issue?
On windows platforms you musst replace inside the file path the "\" with an "/"
Like this:
$file = str_replace ("\\", "/", $_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
Or use the php build in method, for all systems:
$file = realpath($_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
I am using Slim Framework to upload files. I need to upload 10 files in single request of 500MB size. How can I accomplish this. I am using following code for this.
$uploadedFiles = $request->getUploadedFiles();
foreach ($uploadedFiles['aws_file'] as $uploadedFile) {
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$uploadFileName = $uploadedFile->getClientFilename();
$fileDetails = pathinfo($uploadedFile->getClientFileName());
$fileName = explode('_',$fileDetails['filename']);
if(count($fileName)==3) {
$orgIdArray[] = $fileName[1];
}
} else {
$responseObj->status = 'error';
$responseObj->message = 'Error in file or file is empty ';
$responseObj->errorFileList[] = $uploadedFile->getError();
}
}
I am getting memory issue.
Increase your memory_limit PHP setting.
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
Why does the following code echo "Your files have been successfully loaded." when I try to upload a 20mb .gif file, when it actually a)should have been prevented, and b) doesn't actually get uploaded? Basically, I'm trying to limit file upload type, size using php. Page one has a form, which submits up to 10 photos.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$namebase = $_POST['projectID'].'_';
$ProjID = $_POST['projectID'];
$counter = 0;
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if ($_FILES['userfile']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$counter = $counter + 1;
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
if (empty($file['name'])) {
break; /* You could also write 'break 1;' here. */
}
$url_base="";
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 1MB).
$upload_path = '../dev/images/uploaded/'; // The place the files will be uploaded to (currently a 'files' directory).
$allowed_filetypes = array('.jpg','.JPG'); // These will be the types of file that will pass the validation.
$ext = substr($file['name'], strpos($file['name'],'.'), strlen($file['name'])-1);// Get the extension from the filename.
$a='photo'.$counter;
${$a} = 'http:xxxxxxxxx'.$namebase.$counter.$ext;
if(!in_array($ext,$allowed_filetypes))
die('The file type of '.$file['name'].' you attempted to upload is not allowed. <INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($file['tmp_name']) > $max_filesize)
die($file['name'].' you attempted to upload is too large.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Upload the file to your specified path. can rename here.move_uploaded_file(original file name, destination path and filename)
if(move_uploaded_file($file['tmp_name'],$upload_path.$namebase.$counter.$ext)){
echo '<b> '.$file['name'].'</b>'.' Accepted. Renamed '.'<b>'.$namebase.$counter.$ext.'</b>'.'<br>';
// It worked.
}
else
die('There was an error during the file upload. Please try again.'); // It failed :(.
}
}
echo 'Your files have been successfully loaded.<br>';
?>
It's possible that your if ($_FILES['userfile']) is false, so it goes directly to the end of the file ;)
Print out $_FILES array
print_r($_FILES)
if it empty then you will get success message.