I can not upload a file in codeigniter - codeigniter

I cannot upload a file in codeigniter. Code I'm using:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('upload');
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
$this->load->model('User_m');
}
public function form()
{
if($_POST){
//print_r($_POST);exit;
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = "./uploads/";
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['userfile']['name'];
//Load upload library and initialize configuration
//print_r($config);exit;
$this->load->library('upload',$config);
//$this->upload->initialize($config);
if($this->upload->do_upload('userfile')){
$uploadData = $this->upload->data();
$userfile = $uploadData['file_name'];
//echo $userfile;exit;
}
else
{
$userfile = '';
}
}
else
{
$userfile = '';
}
$data['name']=$this->input->post('name');
$data['email']=$this->input->post('email');
$data['phone']=$this->input->post('phone');
$data['userfile']=$userfile;
$this->User_m->form_insert($data);
}
$this->load->view('form');
}
}
This is my controller function code for processing multipart form data in codeigniter. But file is not uploading.

as you have given code i have modified code to trace it.Here below i have attached the view file as well as controller file :
1) Below is a view file code.In this i have submitted form by giving method name in action attribute.If you are submitting the form through ajax then you can pass the method name over there.
<div id="container">
<h1>Please Fill up the Registration Form.!</h1>
<div id="body">
<!-- <?php echo $error;?> -->
<form method="post" action="<?php echo site_url() . '/Main/form' ?>" enctype="multipart/form-data"> Full name:<br> <input type="text" name="name"><br> Email:<br> <input type="text" name="email"><br> Phone:<br> <input type="text" name="phone"><br><br> Image:<br> <input type="file" name="userfile" /> <br /><br /> <input type="submit"><br> </form>
</div>
</div>
2) Below is a controller code.
<?php
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url','html'));
}
public function index()
{
$this->load->view('form');
}
public function form()
{
if($_POST){
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = "./uploads/";
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['userfile']['name'];
//Load upload library and initialize configuration
//print_r($config);exit;
$this->load->library('upload',$config);
//$this->upload->initialize($config);
if($this->upload->do_upload('userfile')){
$uploadData = $this->upload->data();
$userfile = $uploadData['file_name'];
//echo $userfile;exit;
}
else
{
$userfile = '';
}
}
else
{
$userfile = '';
}
$data['name']=$this->input->post('name');
$data['email']=$this->input->post('email');
$data['phone']=$this->input->post('phone');
$data['userfile']=$userfile;
// Below $data getting all the form data
print_r($data);
}
$this->load->view('form');
}
}
Hope this will help you!

You can try this
public function form()
{
if($_POST){
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['userfile']['name'];
$this->upload->initialize($config);
$this->load->library('upload',$config);
if($this->upload->do_upload('userfile')){
$userfile = $_FILES['userfile']['name'];
}
else
{
$userfile = '';
}
}
else
{
$userfile = '';
}
$data['name']=$this->input->post('name');
$data['email']=$this->input->post('email');
$data['phone']=$this->input->post('phone');
$data['userfile']=$userfile;
$this->User_m->form_insert($data);
}

Related

Multi image uploader using CodeIgniter

I am a new user to using code igniter in my project, I am facing one problem while uploading multiple files but only function image uploading images and save into the database and function sliderimage is not uploading images or save into the database?
Controller
public function manage($id = FALSE) {
$data = array();
if ($id) {
$this->{$this->model}->{$this->_primary_key} = $id;
$data['item'] = $this->{$this->model}->get();
if (!$data['item'])
show_404();
} else {
$data['item'] = new Std();
}
$this->load->library("form_validation");
$this->form_validation->set_rules("image", 'Image', "trim|callback_image[$id]");
$this->form_validation->set_rules("sliderimage", 'sliderimage', "trim|callback_image[$id]");
if ($this->form_validation->run() == FALSE)
$this->load->view($this->module . '/manage', $data);
else {
$this->{$this->model}->save();
redirect('admin/' . $this->module);
}
}
public function image($var, $id) {
$config['upload_path'] = './cdn/sliders/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
$data = $this->upload->data();
if ($data['file_name'])
$this->{$this->model}->image = base_url() . '/cdn/sliders/' . $data['file_name'];
}
return true;
}
public function sliderimage($var, $id) {
$config['upload_path'] = './cdn/sliders/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if ($this->upload->do_upload('sliderimage')) {
$data = $this->upload->data();
if ($data['file_name'])
$this->{$this->model}->sliderimage = base_url() . '/cdn/sliders/' . $data['file_name'];
}
return true;
}
Html Form
<form role="form" class="form-horizontal" role="form"
method="post" enctype="multipart/form-data">
<input class="form-control" type="file" name="image" >
<input class="form-control" type="file" name="sliderimage">
</form>
insted of calling both time image function call:
$this->form_validation->set_rules("sliderimage", 'sliderimage', "trim|callback_sliderimage[$id]");

Codeigniter Modular HMVC extension - cant upload file

I have a problem with uploading files by form. Everytime I try, I get the error "File type not allowed". I am using HMVC modular extension and my controllers extends MX_Controller.
I already tried to $var_dump($_FILES) from my form-view and the result is fine, but when I try to use method do_upload() in controller it doesnt work.
Does anyone have any idea? Here is the controller:
Class Store_data extends MX_Controller
{
function __construct()
{
parent::__construct();
}
function upload_pic()
{
//$data['item_id'] = $item_id;
$template = "bootstrap_theme";
//$current_url = current_url();
//$data['form_location'] = $current_url;
$data['view_file'] = "upload_pic";
$this->load->module('template');
$this->template->$template($data);
}
function do_upload()
{
//var_dump($_FILES);
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$config['max_width'] = '4024';
$config['max_height'] = '4768';
$this->load->library('upload', $config);
$this->upload->overwrite = true;
$this->upload->initialize($config);
if ( ! $this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$template = "bootstrap_theme";
$data['view_file'] = "upload_pic";
$this->load->module('template');
$this->template->$template($data);
}
else
{
$data['upload_data'] = $this->upload->data();
$template = "bootstrap_theme";
$data['view_file'] = "upload_success";
$this->load->module('template');
$this->template->$template($data);
}
}
And here is the upload form view:
<?php echo $error;?>
<?php echo form_open_multipart('store_data/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
I solved the problem.
I had to uncomment extension=php_fileinfo.dll in php.ini and comment ;extension=php_mime_magic.dll
Thanks anyway

Codeigniter - Facebook Login and registeration sing PHP SDK

I am using Facebook PHP SDK with Codeigniter to do login and registration using Facebook. For this I am using This tutorial
my controller 'facebooktest.php' code is:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Facebooktest extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('input');
$this->load->library('session');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('security');
}
function Facebooktest() {
parent::Controller();
$cookies = $this->load->model('facebook_model');
}
function index() {
$this->load->view('facebooktest/test2');
}
function test1() {
$data = array();
$data['user'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test1', $data);
}
function test2() {
$data['friends'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test2', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>
view 'test2.php' has code as:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Kent is Learning CodeIgniter - Test 2</title>
</head>
<body>
<fb:login-button autologoutlink="true"
onlogin="window.location.reload(true);"></fb:login-button>
<div style="width:600px;">
<?
if(isset($friends)){
foreach($friends as $friend){
?>
<img src="http://graph.facebook.com/<?=$friend['id'];?>/picture" title="<?=$friend['name'];?>" />
<?
}
}
?>
</div>
<p><?=anchor('facebook_connect/page4','Go back to page 4 of the tutorial');?></p>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '457228377680583', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
// A user has logged in, and a new cookie has been saved
window.location.reload(true);
} else {
// The user has logged out, and the cookie has been cleared
}
});
</script>
</body>
</html>
And model 'facebook_model.php' has code:
<?php
class Facebook_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_facebook_cookie() {
$app_id = '457228377680583';
$application_secret = '01f660b73bc085f0b78cd22322556495';
if (isset($_COOKIE['fbs_' . $app_id])) {
echo "dfgdsf";exit;
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
} else {
return null;
}
}
function getUser() {
$cookie = $this->get_facebook_cookie();
$user = #json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']), true);
return $user;
}
function getFriendIds($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friend_ids = array();
foreach ($friends['data'] as $friend) {
$friend_ids[] = $friend['id'];
}
if ($include_self == TRUE) {
$friend_ids[] = $cookie['uid'];
}
return $friend_ids;
}
function getFriends($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
print_r($cookie);
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
if ($include_self == TRUE) {
$friends['data'][] = array(
'name' => 'You',
'id' => $cookie['uid']
);
}
return $friends['data'];
}
function getFriendArray($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friendlist = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friends = array();
foreach ($friendlist['data'] as $friend) {
$friends[$friend['id']] = array(
'name' => $friend['name'],
'picture' => 'http://graph.facebook.com/'.$friend['id'].'/picture'
);
}
if ($include_self == TRUE) {
$friends[$cookie['uid']] = 'You';
}
return $friends;
}
}
?>
The problem is that, in model, it is coming inside 'getFriends()'. From there it is going inside 'get_facebook_cookie()'. But it is not going inside if(isset($_COOKIE['fbs_' . $app_id])))
and hence, it is nor displaying data that I want.
So, if possible, please let me know whats wrong with my code.
Thanks in advance....

Upload the image path into db and image in the folder name upload

This is the controller:
public function category()
{
if($this->form_validation->run()==FALSE)
{
$this->load->view('admin/home');
}
else{
$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);
$image_data=$_POST['file'];
if ( ! $this->upload->do_upload())
{
// no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/home', $error);
}
else
{
// success
$data = array('upload_data' => $this->upload->data());
$this->your_upload_model->add($title, $description, $data["file_name"]);
$this->load->view('upload_success', $data);
}
}
}
This is the view:
<?php echo validation_errors();?>
<?php echo form_open_multipart('login/category');?>
<?php
if(isset($error))
{
echo $error;
}
?>
<table>
<tr>
<td align=right>Logo:</td>
<td><input type="file" name="file"></td>
<td><input type="submit" value="submit"></td>
</tr>
</table>
I am getting two errors:
Message: Undefined index: file
You did not select a file to upload.
Even though textfield names are same and I used form_open_multipart(). Also, the image is not uploaded and the errors are not helpful.
First of all, $_POST['file'] won't work, but second, you need to supply the HTML field name in do_upload():
if ( ! $this->upload->do_upload('file'))
{
...
}
Also, remove $image_data=$_POST['file']; because it won't work anyway. You are already using $this->upload->data() which is the correct way to get uploaded file data.
The reason $this->upload->do_upload() does not work without the field name is because it looks for the field name="userfile" if the parameter is not supplied. You are using name="file".
Use this code for the first question :
public function category()
{
if (array_key_exists('submit', $_POST)) {
---------You can enter the remaining code here............
}
}
And for the second one:
if ( ! $this->upload->do_upload("file"))
{
-----------code here----------
}

Upload file to database using codeigniter

I need to upload a file in a mysql database using codeigniter.
My view is:
<?php echo form_open_multipart('home/addpagina2'); ?>
<label for="titolo">Titolo:</label>
<input type="text" size="20" id="titolo" name="titolo"/>
<br/>
<label for="testo">Testo</label><br/>
<textarea name="testo" cols="50" rows="10"></textarea>
<br/>
<label for="file">File:</label>
<input type="file" name="file" />
<br />
<input type="submit" value="Aggiungi"/>
</form>
and controller is:
function addpagina2(){
$this->form_validation->set_rules('titolo', 'Titolo', 'trim');
$this->form_validation->set_rules('testo', 'Testo', 'trim');
if($_FILES["file"]["size"] > 0){
$tmpName = $_FILES["file"]['tmp_name'];
$fp = fopen($tmpName, 'r');
$file = fread($fp, filesize($tmpName));
$file = addslashes($file);
fclose($fp);
}
$pagina = array();
$pagina['titolo'] = $this->input->post('titolo');
$pagina['testo'] = $this->input->post('testo');
$pagina['file'] = $file;
$this->db->insert('pagine', $pagina);
redirect('home/pagine');
}
When I want to display the file I call this view:
<?php
header("Content-type: ".$file['type']);
echo $file;
?>
that is called by this controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
}
function id($id){
$immagine = $this->db->get_where('pagine', array('id' => $id));
$data['file'] = $immagine->row()->file;
$this->load->view('file', $data);
}
}
the problem is that I have an error while i call the view in the browser, as you can see here: http://mattialori.net/amv/index.php/file/id/2
If I upload a file on the database using phpmyadmin it works.
How can I do?
Why don't you just save the file name into the db?
Then you can upload the img in a specific folder and in your view yuo can set the full path from your folder and append the file name at the end.
EDIT:
you can use the File Upload class in this way:
//Check if the file exists in the form
if($_FILES['file']['name']!=""){
//load library
$this->load->library('upload');
//Set the config
$config['upload_path'] = './uploads/'; //Use relative or absolute path
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = FALSE; //If the file exists it will be saved with a progressive number appended
//Initialize
$this->upload->initialize($config);
//Upload file
if( ! $this->upload->do_upload("file")){
//echo the errors
echo $this->upload->display_errors();
}
//If the upload success
$file_name = $this->upload->file_name;
//Save the file name into the db
}

Resources