I need to create a folder by using codeigniter without button click - codeigniter

I need to create a folder to store user information at login. One login button should perform 2 actions.
They are
Login
Create folder
I need this in CODEIGNITER, please someone help me, I've been stuck with this for 4 weeks.
This is my code
<?php
ob_start();
defined('BASEPATH') OR exit('No direct script access allowed');
class LoginTwo extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model("login_model", "login");
}
public function login()
{
$username = $this->input->post("username");
$password = $this->input->post("password");
$isCorrect = $this->login->validate_user($username, $password);
if($isCorrect)
{
// Start your user session
$dirName = $username;
$dirPath = "folder/".$dirName."/";
if (!file_exists($dirPath)) {
mkdir("folder/" . $dirName, 0777, true);
}
redirect("your user page");
}
else
{
redirect("homepage");
}
}
}?>

Try to use below mentioned solutions.
$path = FCPATH.'/uploads/';
$new_directory = 'name';
mkdir($path.$name,0755,TRUE);
In this
First_Param: pathname :Name of directory
Second_Param: mode: Permissions
Third Param : recursive : Allows the creation of nested directories

Check out the following code. You need to fit your requirements within this code block (you can change it if you have to do something more).
You controller function :
public function login()
{
$username = $this->input->post("username");
$password = $this->input->post("password");
$isCorrect = $this->user_model->checkCredentials($username, $password);
if($isCorrect)
{
// Start your user session
$dirName = $username;
$dirPath = "folder/".$dirName."/";
if (!file_exists($dirPath)) {
mkdir("folder/" . $dirName, 0777, true);
}
redirect("your user page");
}
else
{
redirect("homepage");
}
}

Related

Try to use the codeigniter's file upload library as a general function from Helpers

Can anybody help as I am trying to use the codeigniter's upload library from the helpers folder but I keep getting the same error that I am not selecting an image to upload? Has any body tried this before?
class FileUpload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'file_uploading'));
$this->load->library('form_validation', 'upload');
}
public function index() {
$data = array('title' => 'File Upload');
$this->load->view('fileupload', $data);
}
public function doUpload() {
$submit = $this->input->post('submit');
if ( ! isset($submit)) {
echo "Form not submitted correctly";
} else { // Call the helper
if (isset($_FILES['image']['name'])) {
$result = doUpload($_FILES['image']);
if ($result) {
var_dump($result);
} else {
var_dump($result);
}
}
}
}
}
The Helper Function
<?php
function doUpload($param) {
$CI = &get_instance();
$CI->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|png|jpg|jpeg|png';
$config['file_name'] = date('YmdHms' . '_' . rand(1, 999999));
$CI->upload->initialize($config);
if ($CI->upload->do_upload($param['name'])) {
$uploaded = $CI->upload->data();
return $uploaded;
} else {
$uploaded = array('error' => $CI->upload->display_errors());
return $uploaded;
}
}
There are some minor mistakes in your code, please fix it as below,
$result = doUpload($_FILES['image']);
here you should pass the form field name, as per your code image is the name of file input.
so your code should be like
$result = doUpload('image');
then, inside the function doUpload you should update the code
from
$CI->upload->do_upload($param['name'])
to
$CI->upload->do_upload($param)
because Name of the form field should be pass to the do_upload function to make successful file upload.
NOTE
Make sure you added the enctype="multipart/form-data" in the form
element

Saving multiple images for one product using one to many in codeigniter

I am new in code igniter.
Here is what I am trying to do. I have lists of products stored in database table name products. For each products i need to insert multiple images. I have created two tables, products and productimage. I have made the product_id of table productimage the foreign key, referencing the product_id of table products. Now i want to save the datas from form. Here is what i did previously Saving images in a single row by imploding
But it became quite difficult for me to manage CRUD(like editing and deleting pictures).
So i am trying to do the above mentioned way. I am not finding the way to start. Can anyone please instruct me, how can I start?
Okay now I have done some coding here. This is my controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('product_model');
$this->load->helper(array('form','url'));
//Codeigniter : Write Less Do More
}
public function index()
{
$data['products']=$this->product_model->get_product();
$this->load->view('/landing_page',$data);
}
public function create()
{
#code
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('product_name','Product_Name','required');
if($this->form_validation->run()=== FALSE)
{
$this->load->view('products/create');
}
else {
$this->product_model->set_product();
$data['products']=$this->product_model->get_product();
redirect('/');
}
}
}
This is my model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product_model extends CI_Model{
public function __construct()
{
$this->load->database();
parent::__construct();
//Codeigniter : Write Less Do More
}
public function get_product()
{
#code
$query=$this->db->get('products');
return $query->result_array();
}
public function set_product($id=0)
{
#code
// if($this->input->post('userSubmit')){
$picture=array();
$count=count($_FILES['picture']['name']);
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
foreach($_FILES as $value)
{
for($s=0; $s<=$count-1; $s++)
{
$_FILES['picture']['name']=$value['name'][$s];
$_FILES['picture']['type'] = $value['type'][$s];
$_FILES['picture']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['picture']['error'] = $value['error'][$s];
$_FILES['picture']['size'] = $value['size'][$s];
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture[] = $uploadData['file_name'];
}
else{
$picture = '';
}
}
}
}//end of first if
else{
$picture = '';
}
$data=array(
'product_name'=>$this->input->post('product_name')
);
$picture=array(
'product_id'=>$this->db->get('products',$id),
'picture_image'=>$picture
);
if ($id==0)
{
return $this->db->insert('products',$data);
return $this->db->insert('images',$picture);
}
else {
$this->db->where('id',$id);
return $this->db->update('products',$data);
return $this->db->update('images',$picture);
}
}
}
Noe the case is when my form opens i am being able to fill product name and upload image files. When i submit it doesn't throws any errors too. But only product name is stored in products table and nothing happens to images table. No any images are inserted. Neither any error is thrown by browser. Simply images
table is empty. What's the problem here?
Let me help you with the Controller .. You need to check for all the uploaded files. They are $_FILES. Loop through the array, upload them on the server and than call a model function to add them in your product Images table
If CI Upload is too tricky for you. Use the following Controller function
public function upload_images()
{
// following IF statement only checks if the user is logged in or not
if($this->session->userdata['id'] && $this->session->userdata['type']=='user')
{
if($_FILES)
{
// check whether there are files uploaded / posted
if(isset($_FILES['files'])){
$data['errors']= array();
$extensions = array("jpeg","jpg","png");
//Loop through the uploaded files
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$i=1;
if($file_size > 2097152){
$data['errors'][$i]='File '.$i.' size must be less than 2 MB';
$i++;
}
// Set upload destination directory
$desired_dir="uploads";
if(empty($data['errors'])==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
// Upload the file.
move_uploaded_file($file_tmp,"uploads/".$file_name);
// Call a function from model to save the name of the image in images table along with entity id
$this->post_model->addImage('property_images',$file_name,$this->uri->segment(3));
}else{ //rename the file if another one exist
$new_dir="uploads/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
}else{
$data['contact']=$this->admin_model->getContactDetails();
$data['images']=$this->post_model->getPropertyImages($this->uri->segment(3));
//load views
}
}
if(empty($data['errors']))
{
redirect(base_url().'dashboard');
}
else
{
$data['contact']=$this->admin_model->getContactDetails();
$data['images']=$this->post_model->getPropertyImages($this->uri->segment(3));
//load views
}
}
}
else
{
//Load view
}
}
else
{
redirect(base_url().'user/login');
}
}
Incase anyone is having the same problem then here is the solution. Just do this in your upload function.(code by my friend Amani Ben azzouz)
public function set_product($id=0){
$picture=array();
$count=count($_FILES['picture']['name']);
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
foreach($_FILES as $value){
for($s=0; $s<=$count-1; $s++){
$_FILES['picture']['name']=$value['name'][$s];
$_FILES['picture']['type'] = $value['type'][$s];
$_FILES['picture']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['picture']['error'] = $value['error'][$s];
$_FILES['picture']['size'] = $value['size'][$s];
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture[] = $uploadData['file_name'];
}
}
}
}//end of first if
$data=array('product_name'=>$this->input->post('product_name'));
if ($id==0){
$this->db->insert('products',$data);
$last_id = $this->db->insert_id();
if(!empty($picture)){
foreach($picture as $p_index=>$p_value) {
$this->db->insert('images', array('product_id'=>$last_id,'images'=>$p_value));
}
}
}
else {
$this->db->where('id',$id);
$this->db->update('products',$data);
if(!empty($picture)){
foreach($picture as $p_index=>$p_value) {
$this->db->update('images', array('product_id'=>$last_id,'images'=>$p_value) ); // --> this one?
}
}
}
}
This is for inserting and updating too. If you simply want do insert just delete the parameter passed as 'id' and cut that if and else part write a plain code of inside 'if'.
function contract_upload(){ // function to call from your view.
$data = array();
// If file upload form submitted
if(!empty($_FILES['files']['name']) AND !empty('user_id')){
$filesCount = count($_FILES['files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
// File upload configuration
$uploadPath = './uploads/contract/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['encrypt_name'] = TRUE;
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if($this->upload->do_upload('file')){
// Uploaded file data
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['emp_id'] = $this->input->post('user_id');
}
}
if(!empty($uploadData)){
// Insert files data into the database
$insert = $this->Contract_model->insert($uploadData);
// Upload status message
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('messageactive', $statusMsg);
}
}
redirect('contract'); // redirect link, where do you want to redirect after successful uploading of the file.
}
// Model Function
public function insert($data = array()){
$insert = $this->db->insert_batch('employee_contract_files', $data); // table name and the data you want to insert into database.
return $insert?true:false;
}
Remember one thing, you should write your HTML as below:
<input type="file" name="files[]" multiple />

How to display custom error message without using codeigniter session flashdata

On my project I am trying to create a error message for my session. I am trying to make it so that if session redirects to main page then will echo message that is on login controller.
Note: I am trying not to use session flashdata if possible. I
already know how to use flashdata.
When I login to my dashboard it displays token in url
Example http://localhost/project-session/index.php/dashboard/32118fa09a0ef2df16851d1f35e3f7d5
On my dashboard __construct() I have this code below.
if ($this->session->userdata('user_id') == FALSE) {
redirect('/');
}
The code above redirects session to home if token is false.
And if it has been redirected because session expires then below message should be activated, On login controller
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
echo "Session Token Invalid";
}
Login Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('form_validation');
$this->load->library('encryption');
$key = bin2hex($this->encryption->create_key(16));
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
echo "Session Token Invalid";
}
$this->form_validation->set_rules('username', 'Username');
$this->form_validation->set_rules('password', 'Password');
if ($this->form_validation->run() == FALSE) {
$this->load->view('welcome_message');
} else {
$data = array(
'token' => $key
);
$this->session->set_userdata($data);
redirect('dashboard' .'/'. $key);
}
}
}
Question: Without using codeigniter session flashdata how can I echo my message in my login controller when it is redirect to login because session expire. When I am redirect the echo message does not get activated.
Updated Login Controller
I have got message working but when I go to reload page it does not clear message. Any Suggestions.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
private $error = array();
public function index() {
$this->load->library('form_validation');
$this->load->library('encryption');
$key = bin2hex($this->encryption->create_key(16));
$this->form_validation->set_rules('username', 'Username');
$this->form_validation->set_rules('password', 'Password');
if ($this->form_validation->run() == TRUE) {
$this->session->set_userdata(array('token' => $key));
redirect('dashboard' .'/'. $key);
}
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
$this->error['warning'] = 'Session Token';
}
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$this->load->view('welcome_message', $data);
}
}

CodeIgniter Vagrant Redirection Loop

I try to use CodeIgniter with vagrant (machine created with puphpet).
The ip address is 192.168.56.101 and when I try to access the main page I get a loop redirection to /index.php/login
This code is working when trying to access it from inside the VM, but within the host browser I get a loop...
Here is an header from the response :
Refresh:0;url=http://192.168.56.101/index.php/login
And some configuration settings :
// application/config/config.php
$config['base_url'] = 'http://192.168.56.101/';
$config['index_page'] = 'index.php';
Any idea ? I can post more code if it's needed.
Thanks
Edit : as requested, here's more infos :
//index.php
define('ENVIRONMENT', 'development');
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
$system_path = 'system';
$application_folder = 'application';
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
if (realpath($system_path) !== FALSE)
{
$system_path = realpath($system_path).'/';
}
$system_path = rtrim($system_path, '/').'/';
if ( ! is_dir($system_path)){
exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME));
}
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
define('EXT', '.php');
define('BASEPATH', str_replace("\\", "/", $system_path));
define('FCPATH', str_replace(SELF, '', __FILE__));
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ( ! is_dir(BASEPATH.$application_folder.'/'))
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ( ! is_dir(BASEPATH.$application_folder.'/'))
{
exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
}
define('APPPATH', BASEPATH.$application_folder.'/');
}
require_once BASEPATH.'core/CodeIgniter.php';
The main controller :
// application/core/MY_Controller.php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
if ($this->session->userdata('username') === false)
{
redirect('login', 'refresh');
}
}
}
The login controller :
// application/controller/login.php
class Login extends CI_Controller
{
public function index()
{
$username = $this->session->userdata('username');
if ($username === false) {
$view_data = array();
$view_data['alert'] = $this->session->flashdata('alert');
$this->load->view('login',$view_data);
}
else {
redirect('home', 'refresh');
}
}
public function connect() {
$this->load->model('user_model');
$username = $this->session->userdata('username');
if ($username === false) {
$post_username = $this->input->post('username');
$post_password = $this->input->post('password');
$data_bdd = $this->user_model->get_user($post_username);
$this->session->set_flashdata('alert', 'user unknown');
foreach ($data_bdd as $user) {
$this->session->flashdata('alert');
if ($this->encrypt->decode($user->USER_PASSWORD) == $post_password) {
$this->session->set_userdata('username',$post_username);
}
else{
$this->session->set_flashdata('alert', 'incorrect password');
}
}
}
redirect('login', 'refresh');
}
public function disconnect() {
$this->session->unset_userdata('username');
redirect('login', 'refresh');
}
}
I found a solution by removing the following lines :
// application/core/MY_Controller.php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
//if ($this->session->userdata('username') === false)
//{
// redirect('login', 'refresh');
//}
}
}
But I have no longer access to any of the website functionalities (because I am not logged in). I still cannot have access to the login page...

How to create a codeigniter class to store all emails to a table

How can I create a helper class in codeigniter to store all email which sends and receives in my website. I need to call that class with all email functions
$this->load->library('myclass');
If I call this class then this function should store $to,time, body and subject of the email to a table (table1). How it is possible?
Create a library with the name of "myemail" and place that in application/libraries.
application/libraries/myemail.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CI_Myemail
{
public function __construct()
{
$this->CI =& get_instance();
}
public function saveEmail($to,$body,$subject)
{
$this->CI->load->model("table_model");
$this->table_model->save(array("to"=>$to,"body"=>$body,"subject"=>$subject,"mail_sent_time"=>date("Y-m-d H:i:s")));
}
}
Then you have to create table_model and write function to save the data into data.
In controller, you have to load this library as
$this->load->library('myemail');
In controller, you have to call as
$this->myemail->saveEmail($this->to,$body,$subject);// Here, $this->do is controller variable as you mentioned in comment
You can easily do this by having a helper function to send an email. Where ever you need to send the email call that function. Inside the function save the data to a table before calling the method to send the email. Also you can save the emails without sending with status pending and send it by a cronjob to improve user experience. I am doing same thing in my website.
The helper function as I am using it below. You can tune it for your needs. The data array should have all the details when called from a controller.
function sendEmail($data, $immediate=FALSE) {
$subject = $data['subject'];
$to = $data['to'];
$viewName = $data['template'];
$CI = & get_instance();
$CI->config->load("thephpcode.com");
$from = $CI->config->item('Sender');
$fromName = $CI->config->item('SenderName');
$priority = $CI->config->item('Priority');
if (isset($data['from'])) {
$from = $data['from'];
$fromName = $data['fromName'];
}
if (isset($data['priority']))
$priority = $data['priority'];
$body = $CI->load->view($viewName, $data, TRUE);
if ($from == "") {
log_message('error', 'From value is not set in Email helper for sending email');
return;
}
$bcc = '';
if (isset($data['bcc'])) {
$bcc = $data['bcc'];
}
/*
$replyto ='';
if (isset($data['reply_to'])) {
$replyto = $data['reply_to'];
$replytoname = $data['reply_to_name'];
}
*/
$status = 'Pending';
if ($immediate)
{
$status = 'Sent';
}
$dbdata = array();
$dbdata['from'] = $from;
$dbdata['fromName'] = $fromName;
if (isset($data['reply_to'])) {
$dbdata['replyto'] = $data['reply_to'];
$dbdata['replytoname'] = $data['reply_to_name'];
}
$dbdata['to'] = $to;
$dbdata['subject'] = $subject;
$dbdata['body'] = $body;
$dbdata['bcc'] = $bcc;
$dbdata['status'] = $status;
$dbdata['priority'] = $priority;
$CI->load->model('email_model', 'email_model');
$CI->email_model->insert($dbdata, 'email_queue');
if (!$immediate)
{
return TRUE;
}
//Send the email
$CI->load->library('email');
$CI->email->initialize($CI->config->item('email_config'));
$CI->email->from($from, $fromName);
$CI->email->to($to);
if (isset($data['bcc']))
{
$CI->email->bcc($data['bcc']);
}
if (isset($data['reply_to']))
{
$CI->email->reply_to($data['reply_to'],$data['reply_to_name']);
}
$CI->email->subject($subject);
$CI->email->message($body);
$CI->email->send();
return;
}

Resources