controller:
public function student()
{
if($this->input->post('save'))
{
$client_id[0]['client_id'] = $this->session->userdata('client_id');
$radio = $this->input->post('class');
$client = $client_id[0]['client_id'];
$filename = $_FILES['students_list']['name'];
$path = base_url()."resources/imported_file/".$filename;
$path = FCPATH."resources/imported_file/";
$move=move_uploaded_file($_FILES['students_list']['tmp_name'],$path.$_FILES['students_list']['name']);
if($_FILES["students_list"]["size"] > 0)
{
$file = fopen($path, "r");
while (($importdata = fgetcsv($file, 10000, ",")) !== FALSE)
{
$data = array(
'name' => $importdata[0],
'email' =>$importdata[1],
'phone' =>$importdata[2],
'uploaded_date' => date('d-m-y'),
'session' => date('Y'),
'client_id' => $client[0]['client_id'],
'class' => $radio
);
$this->partner_model->insertCSV($data);
echo $this->db->last_query();
}
fclose($file);
$this->session->set_flashdata('err_csv', '<p style="color: #87b87f;font-weight: bold;text-align:center;">Data are imported successfully..</p>');
}
else
{
$this->session->set_flashdata('err_csv', '<p style="color: red;font-weight: bold;text-align:center;">Something went wrong..</p>');
}
}
}
view:
<?php echo $this->session->flashdata('err_csv')?>
<form class="form-horizontal" method="post" role="form" enctype="multipart/form-data">
<input type="radio" name="class" value="11th"/><b>XI</b>
<input type="radio" name="class" value="12th Appearing"/><b>XII Appearing</b>
<input type="radio" name="class" value="12th Passed"/><b>XII Passed</b>
<input type="file" id="students_list" name="students_list" accept=".csv" class="required">
<input type="submit" name="save" id="save" value="save" class="btn btn-info" />
</form>
model:
<?php
class Partner_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function insertCSV($data)
{
$this->db->insert('students', $data);
return TRUE;
}
}
In this code I have an input having name student_list where I am uploading only csv file. Now, I want to import data from csv file into database but right now it can't work. So, How can I do this ? Please help me.
Thank You
Unless you have some compelling reason to perform the import in code, I suggest you look at Pentaho (https://sourceforge.net/projects/pentaho/), which can upload data from a csv file to most popular databases.
Hey you need to add the library csvReader in your project and use the below code to setup this helps you lot
public function student(){
$this->load->library('CSVReader');
if (isset($_FILES['csv']))
{
if($_FILES["csv"]["error"] > 0)
{ //if there was an error uploading the file
$this->session->set_flashdata('bulkUploadError', 'Invalid CSV File.');
redirect('/');
}
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "csv" . date('m-d-Y') . ".xls";
move_uploaded_file($_FILES["csv"]["tmp_name"], realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename);
if ($file = fopen(realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename, 'r+'))
{
$result = $this->csvreader->parse_file('uploads/' . $storagename);
$finalResult = $array = array_values(array_filter($result));
$this->data['worksheet'] = $finalResult;
foreach ($this->data['worksheet'] AS $key => $val)
{
$data['id'] = $val['table field name'];
$this->common->save('table_name',$data);
}
}
}
}
You can use PHPExcel to fetch data and insert it to database:
https://github.com/PHPOffice/PHPExcel
<?php
$target_dir = "/tmp/";
$target_file = $target_dir . basename($_FILES["students_list"]["name"]);
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
$filename = $_FILES["students_list"]["name"];
if (isset($_FILES["students_list"])) {
if($FileType == "csv" ) {
if (move_uploaded_file($_FILES["students_list"]["tmp_name"], $target_file)) {
$target_file = $target_dir . $filename;
set_include_path(get_include_path() . PATH_SEPARATOR . 'resources/imported_file/');
include 'PHPExcel/IOFactory.php';
try {
$objPHPExcel = PHPExcel_IOFactory::load($target_file);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($filename,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$name = trim($allDataInSheet[$i]["A"]);
$email = trim($allDataInSheet[$i]["B"]);
$phone = trim($allDataInSheet[$i]["C"]);
$uploaded_date = trim($allDataInSheet[$i]["D"]);
$session = trim($allDataInSheet[$i]["E"]);
$client_id = trim($allDataInSheet[$i]["F"]);
$class = trim($allDataInSheet[$i]["G"]);
$insert = $db->Queryinsert("students",array('',$name,$email,$phone,$uploaded_date,$session,$client_id,$class));
}
}
}
}
?>
This sample helps you to get data from csv file as row by row and after row 1 that involves column title, you try to get other rows then insert them to database.
In top of script i am saving file in /tmp/ folder and then doing needed actions.
You must set your own folder directions and needed Codeigniter syntaxes in this snippet.
Related
I'm trying to import CSV file to the database using yii2 framework.
Controller
public function actionIndex($message=””)
{
// $model = new ProjectDocument;
//error_reporting(E_ALL);
//ini_set('display_error', 1);
$model = new ProjectDocument();
if ($model->load(Yii::$app->request->post()) ) {
$model->file = UploadedFile::getInstance($model, 'file');
// if ($model->load(Yii::$app->request->post())){
// $filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$title = _file[1];
$description = $file[2];
$phase = $file[3];
$modelnew->title = $title;
$modelnew->description = $description;
$modelnew->phase = $phase;
$modelnew->save();
}
unlink('uploads/'.$filename);
return $this->render('create',array('model'=>$model, 'message'=>$message));
}
}else{
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
But I getting an error like this,
"Access to undeclared static property: Yii::$app"
Anyone can help me to rectify the error, Thank you in advance..
I get "Fail: Code: 403 Value: This request is not authorized to perform this operation. details (if any): AuthorizationFailureThis request is not authorized to perform this operation. RequestId:a433a473-e01e-005a-2fa7-30f90a000000 Time:2020-05-23T02:12:36.6988696Z." error. Please see my code below.
require_once 'vendor/autoload.php';
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Blob\BlobSharedAccessSignatureHelper;
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
use MicrosoftAzure\Storage\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Common\Exceptions\InvalidArgumentTypeException;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings;
use MicrosoftAzure\Storage\Common\Models\Range;
use MicrosoftAzure\Storage\Common\Models\Logging;
use MicrosoftAzure\Storage\Common\Models\Metrics;
use MicrosoftAzure\Storage\Common\Models\RetentionPolicy;
use MicrosoftAzure\Storage\Common\Models\ServiceProperties;
use MicrosoftAzure\Storage\Blob\Models\Block;
use MicrosoftAzure\Storage\Blob\Models\BlockList;
use MicrosoftAzure\Storage\Blob\Models\BlobBlockType;
$blobendpoint = "<Blob service SAS URL>"
$connectionString = "BlobEndpoint=".$blobendpoint.";SharedAccessSignature=sv=2019-10-10&ss=bfqt&srt=sco&sp=rwdlacupx&se=2020-06-06T08:58:51Z&st=2020-05-23T00:58:51Z&sip=52.175.254.10&spr=https,http&sig=<Signature>";
$containerName = "samples";
$blobRestProxy = BlobRestProxy::createBlobService($connectionString);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$file_name = $_FILES["resFile"]["name"];
$blob_name = basename($file_name);
$block_list = new BlockList();
define('CHUNK_SIZE', 4 * 1024 * 1024);
try {
$fptr = fopen($file_name, "rb");
$index = 1;
while (!feof($fptr)) {
$block_id = base64_encode(str_pad($index, 6, "0", STR_PAD_LEFT));
$block_list->addUncommittedEntry($block_id);
$data = fread($fptr, CHUNK_SIZE);
$blobRestProxy->createBlobBlock($containerName, $blob_name, $block_id, $data);
++$index;
}
echo "Index :".$index;
$blobRestProxy->commitBlobBlocks($containerName, $blob_name, $block_list);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
?>
<form action="fileuploadblock.php" method="POST" enctype="multipart/form-data">
<input type="file" class="btn btn-default" name="resFile" id="resFile" value="" />
<input type="submit" class="btn btn-default" name = "share "value="Submit" data-inline="true"/>
</form>
Edit:
After removing the IP from SAS I get different error :The value for one of the HTTP headers is not in the correct format. details (if any): InvalidHeaderValueThe value for one of the HTTP headers is not in the correct format. RequestId:cdb1b3c1-b01e-0078-29fd-303c15000000 Time:2020-05-23T12:28:57.6060563ZContent-Length0.
This is the New $connectionString
BlobEndpoint=https://<account>.blob.core.windows.net/;SharedAccessSignature=sv=2019-10-10&ss=bfqt&srt=sco&sp=rwdlacupx&se=2020-05-23T20:17:23Z&st=2020-05-23T12:17:23Z&spr=https,http&sig=<SignatureValue>
I was sending the empty data from file upload.. now I am storing the data in the hosting server and uploading in to the blob..
require_once 'vendor/autoload.php';
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Blob\BlobSharedAccessSignatureHelper;
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
use MicrosoftAzure\Storage\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Common\Exceptions\InvalidArgumentTypeException;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings;
use MicrosoftAzure\Storage\Common\Models\Range;
use MicrosoftAzure\Storage\Common\Models\Logging;
use MicrosoftAzure\Storage\Common\Models\Metrics;
use MicrosoftAzure\Storage\Common\Models\RetentionPolicy;
use MicrosoftAzure\Storage\Common\Models\ServiceProperties;
use MicrosoftAzure\Storage\Blob\Models\Block;
use MicrosoftAzure\Storage\Blob\Models\BlockList;
use MicrosoftAzure\Storage\Blob\Models\BlobBlockType;
$connectionString = "BlobEndpoint=https://<account>.blob.core.windows.net/;SharedAccessSignature=sv=2019-10-10&ss=bfqt&srt=sco&sp=rwdlacupx&se=2021-05-26T17:39:04Z&st=2020-05-27T09:39:04Z&spr=https,http&sig=<Signature>";
$containerName = "samples";
$blobRestProxy = BlobRestProxy::createBlobService($connectionString);
/*****************Upload file to hosting ********/
function uploadFile($fieldName, $fileType)
{
$flg = 0;
$MaxID = "";
$ext = "";
$uploadfile = "";
if (isset($fieldName) AND $fieldName['name'] != '')
{
$flg = 1;
$allowed_filetypes = $fileType;
$max_filesize = 40548576;
$filename = $fieldName['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 = $filename;//$MaxID . $ext;
if (move_uploaded_file($fieldName['tmp_name'], $uploadfile) == FALSE)
{
echo "<h1>Error in Uploading File...</h1>";
$MaxID = "";
}
else
$MaxID = $filename;
echo "file uploaded success!!";
}
}
return $MaxID;
}
/***************************************/
if(isset($_POST['share']))
{
if($_FILES['resFile']['name']!="")
{
$file_name=uploadFile($_FILES['resFile'],array(".xls",".xlsx",".csv"));
}
if ($file_name != '')
{
$blob_name = basename($file_name);
$block_list = new BlockList();
define('CHUNK_SIZE', 1 * 1024 * 1024);
try {
$fptr = fopen($file_name, "rb");
$index = 1;
while (!feof($fptr)) {
$block_id = base64_encode(str_pad($index, 6, "0", STR_PAD_LEFT));
$block_list->addUncommittedEntry($block_id);
$data = fread($fptr, CHUNK_SIZE);
//echo "Data :".$block_id;
$blobRestProxy->createBlobBlock($containerName, $blob_name, $block_id, $data);
//echo "ID :".$block_id;
++$index;
}
$blobRestProxy->commitBlobBlocks($containerName, $blob_name, $block_list);
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo "Error Code :".$code."Error Message : ".$error_message."<br />";
}
}
else
{
echo " No file selected";
}
}
?>
<html lang="en">
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="upload_excel"
enctype="multipart/form-data">
<input type="file" class="btn btn-default" name="resFile" id="resFile" value="" />
<input type="submit" class="btn btn-default" name = "share" value="Submit" data-
inline="true"/>
<!--<div id="res"></div>-->
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</body>
</html>
I am creating a form with 20+ fields to submit the details of the employee's. In the form the employee has to fill their details and upload their document. There are five fields for documents namely (photo,idcard,licence,cv,attest) so the name of each uploaded document has to be stored in a particular field . If i upload all the files in sequence then it is working fine but how to insert the name of a file to their designated field if the employee only inserts one or two files.
Hope i am making sense.
controller
public function register()
{
//form validation
if($this->form_validation->run() === False){
$this->load->view('form');
}
else{
//uploading files
$number_of_files = sizeof(array_filter($_FILES['file']['tmp_name']));
$files = $_FILES['file'];
$errors = array();
for($i=0;$i<$number_of_files;$i++)
{
if($_FILES['file']['error'][$i] != 0)
{
$error[$i] = array('error' => 'Couldn\'t upload file '.$_FILES['file']['name'][$i]);
$this->load->view('form',$error);
}
}
//create a new directory for each new user
$dir = $this->input->post('fname').'_'.$this->input->post('country');
if( is_dir(FCPATH . 'uploads/'.$dir) === false )
{
mkdir(FCPATH . 'uploads/'.$dir);
}
$this->load->library('upload');
$config['upload_path'] = FCPATH . 'uploads/'.$dir;
$config['allowed_types'] = 'gif|jpg|png|docx';
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['file']['name'] = $files['name'][$i];
$_FILES['file']['type'] = $files['type'][$i];
$_FILES['file']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['file']['error'] = $files['error'][$i];
$_FILES['file']['size'] = $files['size'][$i];
$this->upload->initialize($config);
// we retrieve the number of files that were uploaded
if ($this->upload->do_upload('file'))
{
$data['uploads'][$i] = $this->upload->data();
}
else
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('form',$error);
}
}
//assign names of uploaded files to insert in database
if($data){
foreach($data as $value){
$photo = FCPATH . 'uploads/'.$dir.$value[0]['file_name'];
$idProof = FCPATH . 'uploads/'.$dir.$value[1]['file_name'];
$cv = FCPATH . 'uploads/'.$dir.$value[2]['file_name'];
$license = FCPATH . 'uploads/'.$dir.$value[3]['file_name'];
$attest = FCPATH . 'uploads/'.$dir.$value[4]['file_name'];
}
}
$this->form_model->insert_users($photo,$idProof,$cv,$license,$attest);
redirect('form/registered');
}
}
model
public function insert_users($photo,$idProof,$cv,$license,$attest){
$data = array(
//other fields...
'other' => $this->input->post('other'),
'photo' => $photo,
'idProof' => $idProof,
'cv' => $cv,
'license' => $license,
'attest' => $attest
);
return $this->db->insert('employee',$data);
}
View
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
I am trying to upload images to a directory that is defined on input page and passed to the $path variable within the function. Right now it uploads the image in to the same directory as the upload script and not the defined image folder. I have re-worked this several ways the the result is always the same. Both $path and $this->destination remain empty and the image is uploaded to the wrong place. Can anyone else see what I have done wrong?
<?php
//set the max upload size in bytes
$max = 51200;
if(isset($_POST['upload'])){
//define path to the upload directory
$destination = '../../../../image_folder/test/';
require_once('upload.php');
try {
$upload = new Ps2_Upload("$destination");
$upload->move();
$result = $upload->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<body>
<?php
if (isset($result)) {
echo '<ul>';
foreach ($result as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
echo "the place the files will be put is $destination";
?>
<form action="" method="post" enctype="multipart/form-data" id="uploadImage">
<label for="image">Upload New Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input type="file" name="image" id="image" />
<input type="submit" name="upload" id="upload" value="Upload" />
</form>
</body>
</html>
<?php
class Ps2_Upload {
//protected variables
protected $_uploaded = array();
protected $_destination;
protected $_max = 51200;
protected $_messages = array();
protected $_permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
protected $_renamed = false;
public function __construct($path){
if(!is_dir($path) || !is_writable($path)){
throw new Exception("$path must be a valid, writable directory.");
}
$this->_destination = $path;
$this->_uploaded = $_FILES;
}
public function move(){
$field = current($this->_uploaded);
$success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
if($success){
$this->_messages[] = $field['name'] . " uploaded successfully to $this->destination";
} else {
$this->_messages[] = 'Could not upload ' . $field['name'];
}
}
public function getMessages() {
return $this->_messages;
}
}
?>
In your constructor, you have this: $this->_destination = $path;
In your move() method, you have this: $success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
your protected variable is _destination but what you are using in the move() method is destination. No underscore before it. Work on that, might solve your problem:
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
Should work.
$success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
should be
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
note that you have a typo in $this->destination, and it should be $this->_destination
I'm trying to upload multiple images at once to my database. I was able to do it with single files but i'm not able to get it going with the html5 multiple option.
This is my form:
<form action="includes/saveImage.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" multiple="multiple" name="image[]" accept="image/*"> <input type="submit" value="upload">
</form>
and this is my saveImage.php
$files = array();
$fdata = $_FILES["image"];
if (is_array($fdata["name"]))
for ($i = 0; $i < count($fdata['name']); ++$i) {
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
'image' => file_get_contents($fdata['tmp_name'][$i]),
);
}
} else {
$files[] = $fdata;
}
foreach ($files as $file)
{
if (!$album_mysqli->query("INSERT INTO '1' VALUES ('','{$file['name']}','{$file['image']}',NOW())"))
{
print"error while uploading";
}
// print_r( $file );
}
If i uncomment the last print_r($file); it shows the binary data of the image file.
Any ideas why it won't upload to my database?
The database I want to write to uses a BLOB field for the image.
Solved my problem
There was some problem with the SQL-statement
Adding the pictures in this way works just fine...
foreach ($files as $file)
{
$image = file_get_contents($file['tmp_name']);
$result = $album_mysqli->prepare("INSERT INTO '1' VALUES ('', ?, ?, CURDATE())");
$result->bind_param("ss", $file['name'], $image);
if (!$result->execute())
{
echo"Problem on file {$file['name']}. <br/>";
}
else
{
echo("{$file['name']} was added to the database. <br/>");
}
$result->close();
}
You cant upload images to your database like this. You should eiter upload the image via PHP to a certain directory and insert into your database their filenames so that you can fetch them after that, or you can upload their base64 code into the database and put it in the image tag like this <img src="base64_code_of_the_image" />
foreach ($files as $file)
{
#move_uploaded_file($file['tmp_name'],<destinationfile>);
if (!$album_mysqli->query("INSERT INTO '1' VALUES
('','{$file['name']}','',NOW())"))
{
print"error while uploading";
}
print_r( $file );
}
You can't upload the images into the database directly as you are trying. If you want to do that you need to create BLOB object for that specific field in the database table.
Solved my problem
There was some problem with the SQL-statement
Adding the pictures in this way works just fine...
$files = array();
$fdata = $_FILES["image"];
if (is_array($fdata["name"]))
for ($i = 0; $i < count($fdata['name']); ++$i) {
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
'image' => file_get_contents($fdata['tmp_name'][$i]),
);
}
} else {
$files[] = $fdata;
}
foreach ($files as $file)
{
$image = file_get_contents($file['tmp_name']);
$result = $album_mysqli->prepare("INSERT INTO '1' VALUES ('', ?, ?, CURDATE())");
$result->bind_param("ss", $file['name'], $image);
if (!$result->execute())
{
echo"Problem on file {$file['name']}. <br/>";
}
else
{
echo("{$file['name']} was added to the database. <br/>");
}
$result->close();
}
<?php
//include connection here
include'connect.php';
if(isset($_POST['submit']))
{
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$data = $_FILES['image']['tmp_name'];
for($i=0; $i<=count($data)-1; $i++)
{
$name = addslashes($file_name[$i]);
$type = addslashes($file_type[$i]);
$size = addslashes($file_size[$i]);
$tmp = addslashes(file_get_contents($data[$i]));
$sql = "INSERT INTO t_home_pix(name, type, size, content) VALUES('".$name."','".$type."','".$size."','".$tmp."')";
mysqli_query($conn, $sql);
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
File:
<input type="file" multiple="multiple" name="image[]" accept="image/*">
<input type="submit" name="submit" value="upload">
</form>