I am trying to upload a zipped file using codeigniter framework with following code
function do_upload()
{
$name=time();
$config['upload_path'] = './uploadedModules/';
$config['allowed_types'] = 'zip|rar';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->library('unzip');
// Optional: Only take out these files, anything else is ignored
$this->unzip->allow(array('css', 'js', 'png', 'gif', 'jpeg', 'jpg', 'tpl', 'html', 'swf'));
$this->unzip->extract('./uploadedModules/'.$data['upload_data']['file_name'], './application/modules/');
$pieces = explode(".", $data['upload_data']['file_name']);
$title=$pieces[0];
$status=1;
$core=0;
$this->addons_model->insertNewModule($title,$status,$core);
}
}
But the main problem is that when extract function is called, it extract the zip but the result is empty folder. Is there any way to overcome this problem?
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);//to get the file type
$zip->close();
try this :
<?php
exec('unzip filename.zip');
?>
Hmm.., I think you set an incorrect path of your uploaded zip file OR your destination path ('./application/modules/') is incorrect.
Try this :
$this->unzip->extract($data['upload_data']['full_path'], './application/modules/');
I use this -> $data['upload_data']['full_path'], to make sure that it's a real path of the uploaded file.
Hope it helps :)
same problem i faced few min back.if you observe carefully you find
please copy zip file and paste to folder contain programe file(.php) after that you
i think file is not store in temp folder.
if(preg_match("/.(zip)$/i", $fileName))
{
$moveResult= move_uploaded_file($fileTmpLoc, $fileName);
if($moveResult == true)
{
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);
$zip->close();
} else {
echo 'failed';
}
}
unlink($fileName); // Remove the uploaded file from the PHP temp folder
//exit();
}`
class Upload extends CI_Controller {
function __construct(){
parent::__construct();
// load ci's Form and Url Helpers
$this->load->helper(array('form', 'url'));
}
function index(){
$this->load->view('upload_form_view', array('error' => ' ' ));
}
function file_upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'zip';
$config['max_size'] = '';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form_view', $error);
}else{
$data = array('upload_data' => $this->upload->data());
$zip = new ZipArchive;
$file = $data['upload_data']['full_path'];
chmod($file,0777);
if ($zip->open($file) === TRUE) {
$zip->extractTo('./uploads/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
$this->load->view('upload_success_view', $data);
}
}
}
In case anyone comes here for same question, just add chmod($file,0777); to the original code posted yetAnotherSE. That solves the issue of empty files.
Related
I want to make a codeigniter controller that can retrieve a "POST" base64 image, decode it, then save it into a local folder then having that path into my MySQL.
I am stuck at this point.
Can you please give me some references of this case?
The following code snippet is a copy=paste from CodeIgniter's official user documentation.
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
CodeIgniter does have built-in file upload class with very good documentation which I really suggest you give a quick look.
The one part or modification you will have to check carefully looks like this:
$config['file_name'] = 'a_'.md5(microtime()).'.jpg';
which tells codeigniter where to save the file in any local path you want, then from here you can simply save that to your database like this:
$result = $this->db->query('INSERT INTO AVATARS VALUES (NULL, 'user1', '" . $config['file_name'] . "') ');
Please notice that this is pseudo-code only and has not been tested in any production environment; yet, shall perfectly work.
Good luck
$base should have a base64 encoded image string:
$base = $_POST["profile_image"];
$filename = $_POST["file_name"];
$filename = $_POST["user_id"];
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('./Images/'.$filename, 'wb');
fwrite($file, $binary);
fclose($file);
I get following error when trying to upload .ini files
"The filetype you are attempting to upload is not allowed."
Below is the function for uploading files
private function _upload_config_file() {
$config['upload_path'] = APPPATH . 'config/ini/';
$config['allowed_types'] = 'ini';
$config['max_size'] = '2000000';
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$this->upload_status = 'File uploaded succesfully !';
return true;
} else {
$this->upload_status = $this->upload->display_errors();
return false;
}
}
In View
$upload_file_attr = array(
'name' => 'userfile',
'id' => 'userfile',
'disabled' => 'disabled'
);
echo form_open_multipart('sys_setting', $form_sys_setting_multi);
echo form_label('Configure Manually' . form_checkbox($upload_checkbox, '', FALSE, $js_checkbox));
echo form_button($download_button);
echo form_upload($upload_file_attr);
echo form_reset($upload_reset);
echo form_submit($upload_submit);
echo form_close();
Is there any changes to be made in php.ini for uploading .ini files ?
Or Is it codeigniter's upload library that doesn't allow to upload .ini files ?
Need suggestions to solve this issue.
you forgot to put the field_name
Try adding this:
if ($this->upload->do_upload('userfile')) { //parameter should the your input file name attribute
$this->upload_status = 'File uploaded succesfully !';
return true;
} else {
$this->upload_status = $this->upload->display_errors();
return false;
}
I got this issue solved.In config/mimes.php modified $mimes array
$mimes = array('ini' => 'application/octet-stream')
If any one knows how to solve this issue without modifying the core files, *Please do comment.*
I used the Codeigniter's Upload Class to upload images to a folder in the project. In the database I only store the the url generated after upload the image, so when I want to delete a row in the db I also need to delete the image. How can I do it in codeigniter?
I will be grateful for your answers.
You can delete all the files in a given path, for example in the uploads folder, using this deleteFiles() function which could be in one of your models:
$path = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
function deleteFiles($path){
$files = glob($path.'*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
//echo $file.'file deleted';
}
}
delete_row_from_db(); unlink('/path/to/file');
/path/to/file must be real path.
For eg :
if your folder is like this htp://example.com/uploads
$path = realpath(APPPATH . '../uploads');
APPPATH = path to the application folder.
Its working...
if(isset($_FILES['image']) && $_FILES['image']['name'] != '')
{
$config['upload_path'] = './upload/image';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['file_name'] = base64_encode("" . mt_rand());
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg', 'We had an error trying. Unable upload image');
}
else
{
$image_data = $this->upload->data();
#unlink("./upload/image/".$_POST['prev_image']);
$testData['image'] = $image_data['file_name'];
}
}
$m_img_real= $_SERVER['DOCUMENT_ROOT'].'/images/shop/real_images/'.$data['settings']->shop_now;
$m_img_thumbs = $_SERVER['DOCUMENT_ROOT'].'/images/shop/thumbs/'.$data['settings']->shop_now;
if (file_exists($m_img_real) && file_exists($m_img_thumbs))
{
unlink($m_img_real);
unlink($m_img_thumbs);
}
View:
<input type="file" name="new_file" data-required="1" class="" />
<input type="hidden" name="old_file" value="echo your old file name"/>
<input type="submit" name="submit"/>
Controller:
function edit_image() {
if(isset($_FILES['new_file']['name']) && $_FILES['new_file']['name'] != '') {
move_uploaded_file($_FILES['new_file']['tmp_name'],'./public_html/banner/'.$_FILES['new_file']['name']);
$upload = $_FILES['new_file']['name'];
$name = $post['old_file'];
#unlink("./public_html/banner/".$name);
}
else {
$upload = $post['old_file'];
}
}
Try using delete_files('path') function offered by CI framework itself:
https://ellislab.com/codeigniter/user-guide/helpers/file_helper.html
$image_data = $this->upload->data();
unlink($image_data['full_path']);
This line $this->upload->data() will return many information about uploaded file. You can print information and work accordingly.
i am using CI 2.1.0 and mysql database for one of my projects. i am facing a problem with my image uploading method. the image i am uploading should be saved in uploads directory and create a thumbnail version of the image and the image path should be saved in database.
the code i have done works fine but there is one problem that when i upload an image, in the upload directory i get two copies of the same image and in the thumbs directory a single copy of the uploaded image. i want to have only one copy of the image instead of those two copies .
here is my code->
model:
function do_upload() //to upload images in upload directory
{
$i=$this->db->get('portfolio')->num_rows();
$i=$i+1;
$image_path=realpath(APPPATH . '../uploads');
$config=array(
'allowed_types'=>'jpeg|png|gif|jpg',
'upload_path'=>$image_path,
'max_size'=>2097152,
'file_name'=>'_'.$i.'_'
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config=array(
'source_image'=>$image_data['full_path'],
'new_image'=>$image_path.'/thumbs',
'maintain_ration'=>TRUE,
'width'=>150,
'height'=>100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
if( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
return $image_data;
}
}
some please tell me why two copies of images are being uploaded.
there is anothe thing, i want images to be overwritten if an image with same name exists. i have changed the upload.php file inside system->libraries to this
public $overwrite = TRUE;
but it is not working. someone please help.
you are calling $this->upload->do_upload() twice ..
Please try this code
Warning : Untested
function do_upload()
{
$i=$this->db->get('portfolio')->num_rows();
$i=$i+1;
$image_path=realpath(APPPATH . '../uploads');
$config=array(
'allowed_types'=>'jpeg|png|gif|jpg',
'upload_path'=>$image_path,
'max_size'=>2097152,
'overwrite'=>TRUE,
'file_name'=>'_'.$i.'_'
);
$this->load->library('upload', $config);
if( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$image_data = $this->upload->data();
$config=array(
'source_image'=>$image_data['full_path'],
'new_image'=>$image_path.'/thumbs',
'maintain_ration'=>TRUE,
'width'=>150,
'height'=>100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
return $image_data;
}
}
I will give an alternate uploader class for handling file uploads properly. You can re use this code anywhere .
<?php
//Save file as Uploader.php
//File Uploading Class
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats(){
$this->allowAll = true;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}
function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}
}
?>
Using Uploader.php
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>
Hi I need to put a permission 777 to my uploaded files but I dont find any docs for uploaded files in codeigniter... Is it possible to put permission 777 with the upload class of codeigniter ??
$group_id = $this->input->post('group_id', TRUE);
// unlink('static/images/uploads/44');
// rmdir('static/images/uploads/45');
$dir = is_dir('../www/static/images/uploads/'.$group_id);
if($dir){
$config['upload_path'] = '../www/static/images/uploads/'.$group_id;
echo "test";
}
else{
mkdir('../www/static/images/uploads/'.$group_id, 0777);
$config['upload_path'] = '../www/static/images/uploads/'.$group_id;
}
$config['allowed_types'] = 'docx|pdf|doc|gif|jpg|png|tiff';
$config['max_size'] = '10000000';
$config['max_width'] = '999999';
$config['max_height'] = '99999';
$this->load->model('Teacher_model');
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
//$this->load->view('school/teacher/upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$name = $this->input->post('name', TRUE);
$path = $data['upload_data']['file_name'];
$group_id = $this->input->post('group_id', TRUE);
$this->Teacher_model->add_ressources($group_id,$name,$path);
redirect('school/teachers/#tabs_group_ressource'.$group_id, 'location', 301);
}
You can use chmod to change the permissions. Something like this may work.
After the do_upload you could try adding the following line
if(is_file($config['upload_path']))
{
chmod($config['upload_path'], 777); ## this should change the permissions
}
You can use chmod along with umask.
$old = umask(0);
$logofilepath = $config['upload_path'].$filename;
if(is_file($logofilepath))
{
chmod($logofilepath, 0777);
}
umask($old);