error in uploading the image to the upload folder - php

I've been trying to get this to work since this morning, but have no idea why it doesn't. The uploaded image gets stored in the database, but when I check my upload folder --where I want to store the images -- there's nothing there.
Can anyone help me with this problem?
Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
//load database libray manually
$this->load->database();
//load Model
$this->load->model('Contact_model');
// load form and url helpers
$this->load->helper(array('form', 'url'));
// load form_validation library
$this->load->library('form_validation');
}
public function Latest_news()
{
$this->form_validation->set_rules('first_content', 'First content', 'required');
$this->form_validation->set_rules('second_content', 'Second content', 'required');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (($this->form_validation->run() == FALSE )&&(!$this->upload->do_upload('filename')))
{
$this->load->view('Latest_news');
}
else
{
//insert
$data = array();
$data['first_content']=$this->input->post('first_content');
$data['second_content']=$this->input->post('second_content');
$data['filename']=$this->input->post('filename');
//Transfering data to Model
$this->Contact_model->latest_news($data);
//Redirecting to success page
redirect(site_url('Home/Latest_news'));
}
}
?>
Contact_model.php
<?php
class Contact_model extends CI_Model
{
function latest_news($data)
{
//saving records
$this->db->insert('latest_news', $data);
}
}
?>
Latest_news.php
<?php echo form_open(); ?>
<div style="padding-top:10%; padding-left:30%">
<div>
<textarea name="first_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("first_content");?></span>
</div><br>
<div>
<textarea name="second_content" rows="4" cols="50"></textarea>
<span><?php echo form_error("second_content");?></span>
</div><br>
<div>
<input type="file" name="filename">
<span><?php echo form_error("filename");?></span>
</div><br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>

Use function form_open_multipart() in Latest_news.php instead form_open()

Related

Form validation does not work properly in codeIgniter

I have created an employee controller for inserting data into database and I would like to set validation before inserting data into the database.
I have tried following way but every time it shows message field is required even though I have filled values in text box.
1) Controller
<?php
class Employee_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
/* Load form validation library */
$this->load->library('form_validation');
$this->load->library('email');
$this->load->library('session');
$this->load->helper('form');
$this->load->database();
}
function add_employee(){
$this->load->view('Employee_add');
}
function insert_emp(){
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('Employee_add');
} else {
$this->load->model('Employee_model');
$inserData = array(
'name' =>$_POST['emp_name'],
'salary' => $_POST['emp_salary']
);
$this->Employee_model->insert_employee($inserData);
$emp_list['emp_records']= $this->Employee_model->list_employee();
$this->load->view('Employee_list',$emp_list);
}
}
}
2) Model code ( following is my model code )
<?php
class Employee_model extends CI_Model {
function __construct() {
parent::__construct();
}
function insert_employee($inserData){
$this->db->insert('employee',$inserData);
return true;
}
}
?>
3) View
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="center">
<form action="<?php echo site_url('Employee_controller/insert_emp');?>" method="post">
<?php echo validation_errors(); ?>
<div class="element">
<label>Name</label>
<input type="text" name="emp_name" value="">
</div>
<div class="element">
<label>Salary</label>
<input type="text" name="emp_salary" value="">
</div>
<input type="submit" name="submit" value="Add Employee">
</form>
</div>
</body>
</html>
</body>
</html>
Check your $this->form_validation->set_rules method, you are passing name when your fields are emp_name and emp_salary

Validating a form hiding controller from URL Codeigniter

I'm facing a problem when trying to create a simple login system. This is how it works and shows what my problem is.
The login page contains a simple form, and opens a form to the controller 'Verify_login'. This Verify_login controller does some basic form validations, and then queries the database to check if the user entered correct credentials. When this form is submitted, it automatically directs the user to website.com/verify_login, while I would like it to remain website.com/login. I am not able to solve this problem using the routes file, because this causes the two pages to be both redirected to the same page. Does anyone have a solution to this? I'm using the Codeigniter framework.
login.php
<div class="content-block">
<h1>Login</h1>
<div class="content-inner-block">
<?php echo validation_errors(); ?>
<?php echo form_open('Verify_login'); ?>
<div class="login wrap">
<input type="text" name="username" id="user" placeholder="Username">
<input type="password" name="password" id="pass" placeholder="**********">
<input type="submit" value="Log in">
</div>
<?php echo form_close("\n")?>
</div>
Verify_login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Verify_login extends CI_Controller{
public function index(){
$this->load->model('User_model');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('pages/login');
return false;
}
$result = $this->User_model->login($this->input->post('username'), $this->input->post('password'));
if($result){
echo 'loggedin';
} else {
echo 'wrong';
}
}
}
?>

Cant validate form data or insert into database (Codeigniter)

I am working with Codeigniter framework these days. I am trying to validate my form data using codeigniter's form_validation library. The problem is I cant get it to work. I dont know where the problem is no error is being shown.
Here is the view page I am calling controller core and function postad in form action
<div class="container table-responsive" id="con1">
<div class="row" id="h4_subad">
<div class="col-md-4"><h4>Submit an Ad</h4></div>
</div>
<form class="form-horizontal" role="form" method="get" action="/core/postad">
<table id="form_table" class="table-responsive table table-striped" id="table_form">
<td>Ad Title*</td><td><input class="form-control" name="ad_title" id="ad_title" type="text" placeholder="Enter Title" id="ad_form"></td>
<tr> <td>Select Category*</td> <td><select name="ad_form" class="form-control" id="ad_form">
<option>Electronics</option>
<option>Mobiles & Accessories</option>
<option>Computers & Accessories</option>
<option>Kitchen Applicances</option>
<option>Clothing</option>
</select></td></tr>
<tr><td>Ad Description*</td><td><textarea name="txt_area" id="txt_area" class="form-control" type="text" placeholder="Enter Description" ></textarea></td></tr>
<tr><td><button type="button" class="btn btn-warning" onclick="core/postad">Submit Ad</button></td></tr>
</table>
</form>
</div>
Controller for this view
class Core extends CI_Controller {
public function index() {
$this->load->view('header1');
$this->load->view('body');
$this->load->view('footer');
}
public function product() {
$this->load->view('header1');
$this->load->view('product');
$this->load->view('footer');
}
public function contact() {
$this->load->view('header1');
$this->load->view('contact');
$this->load->view('footer');
}
public function aboutus() {
$this->load->view('header1');
$this->load->view('aboutus');
$this->load->view('footer');
}
public function reg() {
$this->load->view('header1');
$this->load->view('reg');
$this->load->view('footer');
$this->input->get('username');
}
public function postad() {
$this->load->view('header1');
$this->load->view('postad');
$this->load->view('footer');
$this->load->model('insert_model');
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('txt_area', 'Text Area', 'required|min_length[5]|max_length[15]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('postad');
}
else {
//Setting values for tabel columns
$data = array(
'description' => $this->input->post('txt_area'),
);
//Transfering data to Model
$this->insert_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('insert_view', $data);
}
}
}
Model for database connectivity
<?php
class insert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
$this->db->insert('post_ad', $data);
}
}
?>
Only trying it for just one field txt_area
I dont want to use codeigniter's form helper as I am using bootstrap form.
You should echo the validation_errors(); as below in your html . For more information you can vist this
<?php echo validation_errors(); ?>
<div class="row" id="h4_subad">
<div class="col-md-4"><h4>Submit an Ad</h4></div>
</div>
<form class="form-horizontal" role="form" method="get" action="/core/postad">
<table id="form_table" class="table-responsive table table-striped" id="table_form">
<td>Ad Title*</td><td><input class="form-control" name="ad_title" id="ad_title" type="text" placeholder="Enter Title" id="ad_form"></td>
<tr> <td>Select Category*</td> <td><select name="ad_form" class="form-control" id="ad_form">
<option>Electronics</option>
<option>Mobiles & Accessories</option>
<option>Computers & Accessories</option>
<option>Kitchen Applicances</option>
<option>Clothing</option>
</select></td></tr>
<tr><td>Ad Description*</td><td><textarea name="txt_area" id="txt_area" class="form-control" type="text" placeholder="Enter Description" ></textarea></td></tr>
<tr><td><button type="button" class="btn btn-warning" onclick="core/postad">Submit Ad</button></td></tr>
</table>
</form>
</div>
You need to use validation_errors(); in posted.php file (HTML) for display error message which you validate.
<?php echo validation_errors(); ?>
Form Validation User Manual
Your button to submit the form is incorrect. When you try to submit a form make sure to set the type to submit too.
<button type="submit">Submit form</button>
or
<submit>Submit form</submit>

Incorrect use of the CodeIgniter form_validation() function throwing fatal error

I'm trying to apply CodeIgniter's form validation feature for an input form in one of my view pages. In that form, all fields are required. If all the fields are successfully filled up and then if the user clicks the submit button, it will redirect to another view page with the list of entries. If any field is left empty, validation messages will be displayed.
Here's my form in first view page - employee_add.php:
<div id="content" class="box">
<form action="<?php echo base_url();?>index.php/employee_adds/insert_employee_db" method="post">
<?php echo validation_errors(); ?>
<fieldset>
<legend id="add_employee_legend">Add New Employee</legend>
<div>
<label id= "emp_id_add_label">Employee ID:</label>
<input type="text" name="emp_id" id = "employee_id_add" placeholder="Employee ID"/>
</div>
<div>
<label id= "emp_name_add_label">Employee Name:</label>
<input type="text" name="emp_name" id = "employee_name_add" placeholder="Employee Name"/>
</div>
<input type="submit" name="submit" id = "employee_info_submit" value="Send"/>
</fieldset>
</form>
</div>
Here's my controller - employee_adds.php:
<?php
if ( ! defined('BASEPATH')){ exit('No direct script access allowed');}
class Employee_adds extends CI_Controller
{
function __construct()
{
parent::__construct();
#$this->load->helper('url');
$this->load->model('employee_model');
}
//Show all Employees or validate employees
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('emp_id', 'Employee ID', 'required');
$this->form_validation->set_rules('emp_name', 'Employee Name', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin_logins/employee_add');
}
else
{
$data['employee_list'] = $this->employee_model->get_all_employees();
$this->load->view('admin_logins/employee_list');
}
}
//Insert an employee
public function insert_employee_db()
{
$edata['emp_id'] = $this->input->post('emp_id');
$edata['emp_name'] = $this->input->post('emp_name');
$res = $this->employee_model->insert_employee($edata);
if($res)
{
header('location:'.base_url()."index.php/employee/".$this->index());
}
}
}
?>
Here's controller for master page named admin_logins.php:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin_logins extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('admin_logins/index');
}
function employee()
{
$this->load->view('admin_logins/employee_add');
}
}
Here's my model - employee_model.php:
<?php
class Employee_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
//To retrieve all employees
public function get_all_employees()
{
$query = $this->db->get('employee');
return $query->result();
}
//To add a new employee to the database
public function insert_employee($data)
{
return $this->db->insert('employee', $data);
}
}
?>
Another view page named employee_list.php is going to load the list of successful entries in its central div:
<div id="content" class="box">
<table id = "employee_list_table" width="600">
<tr>
<th scope="col">Employee Id</th>
<th scope="col">Employee Name</th>
</tr>
<?php foreach ($employee_list as $e_key){ ?>
<tr>
<td><?php echo $e_key->emp_id; ?></td>
<td><?php echo $e_key->emp_name; ?></td>
</tr>
<?php }?>
</table>
</div>
Whenever I try to run the employee_add.php view page, I get the following error:
Fatal error: Call to undefined function validation_errors() in C:\wamp\www\CI\application\views\admin_logins\employee_add.php
From what I'm guessing, it may be due to one of the two following reason:
My code designing and layout was incorrect (disorganized coding in views, controller and model)
My code syntax was incorrect (most likely in the uses of form and form validation)
Or maybe, there are other reasons. I just can't figure out why, and exactly where in my code the errors occurred.
EDIT-1: As per user Ghost's solution, I've loaded the form_validation library in my admin_logins/employee method in controller - admin_logins.php. The fatal PHP error's gone, but still the validation is not working. As soon as I click submit button after keeping those fields empty, instead of validation message, I get the following error message:
A Database Error Occurred
Error Number: 1146
La table 'ci_test.employee' n'existe pas
INSERT INTO `employee` (`emp_id`, `emp_name`) VALUES ('', '')
Filename: C:\wamp\www\CI\system\database\DB_driver.php
It seems I still have more syntactical mistakes in my code.
It seems that both:
Employee_adds -> index() and Admin_logins ->employee() share the same view file:
'admin_logins/employee_add'
And when you put <?php echo validation_errors(); ?> What triggers the error is that looking on Admin_logins ->employee()
It seems that $this->load->library('form_validation'); is not loaded:
function employee()
{
$this->load->view('admin_logins/employee_add');
}
So by the time you access admin_logins/employee, it causes the error since the validation library hasn't been initialized.

User registration with CodeIgniter

I'm trying to build a registration system with CodeIgniter. I have a controller called Register with the following code:
class Register extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
$this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
$this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
$this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
$this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim');
$this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|trim');
$this->load->view('header');
if(!$this->form_validation->run())
{
$this->load->view('register_form');
}
else
{
$this->load->view('register_done');
}
$this->load->view('footer');
}
}
So far so good. If I go to the register page I get the registration form displayed. If I send the form and it passes the form validation checks, I get the success page, if the form has errors, I get the form back with some error messages.
Now what I want to do is the database stuff. I have some idea of how I can get the POST values from the registration form into my database, but no clue how I can check if a username or email already exists, and if so, display that error on the registration form. Here's my registration form view:
<?php $this->load->helper('form'); ?>
<?php echo form_open('register'); ?>
<ul id="register">
<ul>
<h3>Account information</h3>
<li>
<label for="username">Choose a username</label>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" />
<span class="desc">The name you'd like to be known by</span>
<?php echo form_error('username'); ?>
</li>
<li>
<label for="password">Pick a password</label>
<input type="password" name="password" />
<span class="desc">The best passwords are random and more than 6 characters long</span>
<?php echo form_error('password'); ?>
</li>
<li>
<label for="email">Enter your valid email address</label>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" />
<span class="desc">We'll send you an activation email</span>
<?php echo form_error('email'); ?>
</li>
</ul>
<ul>
<h3>About you</h3>
<li>
<label for="band">Who's your favorite artist?</label>
<input type="text" name="artist" value="<?php echo set_value('artist'); ?>" />
<span class="desc">Don't put Lady GaGa.</span>
<?php echo form_error('artist'); ?>
</li>
</ul>
<ul>
<h3>Security question</h3>
<li>
<label for="captcha">Enter the letters you see in the image</label>
<?php $this->load->helper('captcha');
$cap = create_captcha(array('img_path' => './captcha/', 'img_url' => 'http://localhost/captcha/', 'img_width' => 200, 'img_height' => 30));
$data = array('captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word']);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo $cap['image']; ?>
<input type="text" name="captcha" />
<?php echo form_error('captcha'); ?>
</li>
</ul>
<ul>
<h3 class="submit">
<input type="submit" value="Register" />
</h3>
</ul>
</ul>
<?php echo form_close(); ?>
As you can see, I'm taking advantage of the form_error() function of CI to display form errors right under the field, and I would like the "username already exists" error to also be displayed under the username field.
Can anyone provide some help? Even a nudge in the right direction?
Thanks!
I would strongly urge you to think about using another library that already does this very well: TankAuth. TankAuth is easily modifiable and offers email confirmation, very secure password hashing, a solid database schema, and very clean code.
There's no reason to reinvent the wheel, especially when it comes to something that's very hard to get right like user authentication.
EDIT:
For example, here's everything TankAuth provides security-wise that you'd have to code yourself (if you cared about security) - how much time would that take?
Using phpass library for password hashing (instead of unsafe md5).
Counting login attempt for bruteforce preventing (optional). Failed login attempts determined by IP and by username.
Logging last login IP-address and time (optional).
CAPTCHA for registration and repetitive login attempt (optional).
Unactivated accounts and forgotten password requests auto-expire.
You need to create a model for your controller.
Your model would look like this:
class Register_model extends CI_Model {
function register_user()
{
$data['username'] = $this->input->post('username');
$data['password'] = sha1($this->input->post('password'));
... (your other post data) ...
$this->db->insert('users', $data);
}
}
In your controller you will call the model this way:
$this->load->model('Register_model');
and the method goes here:
else
{
$this->Register_model->register_user();
$this->load->view('register_done');
}
If you want to check if the username is available, you simply put SELECT query on the first lines of the register_user() method (function).
To do the check you should have functions in your model that can look up those types of things for you:
class Model{
function getUserByEmail($email);
function getUserByUsername($username);
...
}
Then in your controller you can call these methods
...
$result = $model->getUserByEmail($_POST['email']); // You'll need to sanitize your POST
if(count($result) > 0){
// Sent error about email already existing and flag to not insert/update user
}
...
The easiest solution in CodeIgniter is to use a callback function as one of the rules in your form validation.
I've used this method myself to check the username and e-mail.
Here's the docs for it.
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
// Load session library
$this->load->library('session');
// Load database
$this->load->model('User_model');
}
public function index()
{
$this->load->view('index');
}
public function project()
{
$this->data['posts'] = $this->User_model->getPosts(); // calling Post model method getPosts()
$this->load->view('tables', $this->data);
// $this->load->aview('project');
}
public function get_project()
{
$this->User_model->get_project($data);
}
public function signin()
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$this->User_model->signin($data);
}
public function logout()
{
$this->session->unset_userdata($_SESSION['email']);
// $this->session->sess_destroy();
redirect('User');
}
public function signup()
{
$data = array(
'name' => $this->input->post('name'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
if($this->User_model->signup($data))
{
echo "no insert";
}
else
{
$this->load->view('index', $data);
}
}
}
<?php
Class User_model extends CI_Model {
function __construct() {
parent::__construct();
$this->load->library('session');
}
public function signup($data)
{
$this->db->insert('user_signup',$data);
}
public function getPosts()
{
$this->db->select("*");
$this->db->from('user_data');
$query = $this->db->get();
return $query->result();
}
public function signin($data)
{
$this->db->where('email',$data['email']);
$this->db->where('password',$data['password']);
$query=$this->db->get('user_signup');
if($query->num_rows()==1){
$_SESSION['email'] = $data['email'];
$this->load->view('popup',$data);
return true;
}
else{
echo "no";
return false;
}
}
}

Categories