I have create a web application using CodeIgniter making at first a login interface. Here are the controller I used but I think something doesn't work but I don't know what.The home page, where the user is granted, it doesn't show.Unfortunately I didn't have a debugger to check what doesn't work. maybe there is a problem to handle the session but really I don't know what can be. maybe you are smarther than me to find the error
Login Controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('User','user'); /* This call the model to retrieve data from db */
}
public function index()
{
if(!file_exists('application/views/_login.php'))
{
show_404();
}
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 style="text-align:center;">','</h4>');
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','password','trim|required|xss_clean|callback_pass_check');
if($this->form_validation->run() == FALSE)
{
/* Data to pass to view */
$data['title'] = "User Access";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header',$data);
$this->load->view('_login',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('home', 'refresh');
}
}
public function pass_check($pass)
{
$result = $this->user->find_user($this->input->post('username'),$pass);
if(!empty($result))
{
foreach ($result as $row)
{
$session_array = array('id'=> $row->id, 'username'=> $row->username); /* Create a session passing user data */
$this->session->set_userdata('logged_in', $session_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('pass_check',"Invalid username or password!</br>Try again, please!");
return FALSE;
}
}
}
/* END OF FILE */
Home Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
session_start();
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$data['title'] = "Management Emergency";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header', $data);
$this->load->view('_home',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('login', 'refresh');
}
}
public function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home','refresh');
}
}
/* END OF FILE */
The model in the login controller works very well so It isn't a problem of query. Before adding session everything works but when I added session stopped to worked so I think that can be a problem or redirect() or session
Home View
<div data-role = "page">
<div data-role = "header" data-position = "inline">
<?php echo heading($title,1) ?>
</div>
<div class = "menu-content">
<ul data-role = "listview" data-inset="true">
<li data-role = "list-divider">Emergency Menù</li>
<li class = "menu-item">
<a href="">
<div class = "image-wrapper">
<img src="/assets/images/user.png" class = "ui-li-icons" />
</div>
Add patient
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/home.png" class = "ui-li-icons" />
</div>
Show all hospital
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/favorite.png" class="ui-li-icons" />
</div>
Find patients
</a>
</li>
<li class="menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/email.png" class="ui-li-icons" />
</div>
Send medical infos
</a>
</li>
</ul>
Login View
<div data-role ="dialog">
<div data-role = "header" data-theme="e">
<?php echo heading($title,1) ?>
</div>
<div data-role ="content">
<?php
$var = validation_errors();
if(!empty($var))
{
echo form_error('username');
echo form_error('password');
}
else
{
echo heading('911 - First Aid',2,'style="text-align:center; color:red;"');
echo form_open('login');
?>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="name" value="" placeholder="Username"/>
</div>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="password">Password</label>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
</div>
<div data-role ="fieldcontain">
<input type="submit" value="Login" data-theme ="b"/>
</div>
</form>
<?
}
?>
There is a problem with CodeIgniter retaining it's session data after a redirect. Your if($this->session->userdata('logged_in')) in your home.php controller will evaluate false every time because the session is resetting. You could use the native php sessions to skip over this problem.
See: http://codeigniter.com/wiki/Native_session/. Good luck!
UPDATE
Apparently, this is only true of CodeIgniter 1.7.2 when used with IE6. It doesn't affect most browsers.
open the application/config/autoload.php file and add the 'url' in the helper array;
$autoload['helper'] = array('url');
i hope this will help you to fix the problem.
Related
Controller:
public function latestnews()
{
$data['news'] = $this->New_model->getById($id);
$this->load->view('news',$data);
}
Model:
public function getById($id)
{
return $this->db->get_where($this->_table, ["new_id" => $id])->row();
}
View:
<?php
if (isset($news) and $news) {
foreach($news as $new) {
?>
<div class="col-sm-12">
<div class="section">
<img src="<?php echo site_url('uploads/'.$new->image); ?>" />
</div>
<p><?php echo $new->description;?> </p>
</div>
<?php
}
}
?>
How and where to define the variable id?
While clicking a dynamic image,it should be opened in another page containing details but instead showing Undefined variable: id
In the latestnews() function you have no $id defined.
Try to call the latestnews() function with the right $id parameter.
you can write function like this,
function latestnews($id)
{
Controller:
function single_news($id) { // This $id variable comes from URL Ex: example.com/single_news/15. So $id = 15
$this->data['news_data'] = $this->new_model->getNewsByID($id);
$this->load->view('single-news', $this->data); // Create New View file named single-news.php
}
Model:
function getNewsByID($id) {
$this->db->where('id', $id);
$q = $this->db->get('news');
if($q->num_rows() > 0) {
return $q->row();
}
return false;
}
View: (Single News Page)
<div>
<img src="<?php echo site_url('uploads/'.$news_data->image); ?>" />
</div>
I am trying to call an external function within a class method property. It actually does gets called but at the end of the page and whatever is inside the method property, remains separate.
Since I am a self taught student, it is recent that I have started learning PHP classes so I am not really sure if this can be done or not.
Please guide me how this can be done correctly or if not, then what could be the workaround?
The class I have written is as follows:
It will take the input from user while creating of instance and render a modal box based on the input and options selected.
class modalBox{
private $modal_id, $modal_anim, $header_title, $modal_content,$footer;
private $headerOpt,$titleOpt,$footerOpt,$closeBtn;
public function setID($id){
$this->modal_id = $id;
}
public function getID(){
$modal_id = $this->modal_id;
return $modal_id;
}
public function setTitle($title){
$this->header_title = $title;
}
public function getTitle(){
$title = $this->header_title;
return $title;
}
public function setBodyContent($content){
$this->modal_content = $content;
}
public function getBodyContent(){
$modalContent = $this->modal_content;
return $modalContent;
}
public function setFooterContent($footer){
$this->footer = $footer;
}
public function getFooterContent(){
$footerContent = $this->footer;
return $footerContent;
}
public function initiateModal($modal_anim, $headerOpt, $titleOpt, $closeX, $footerOpt, $footerCloseBtn){ ?>
<div class="modal <?php if($modal_anim != 'false'){echo $modal_anim;} ?>" id="<?php echo $this->getID(); ?>" style="z-index: 2;">
<div class='modal-dialog'>
<div class='modal-content'>
<?php
// display if header option is set to true
if ($headerOpt){
?>
<div class="modal-header">
<h4><?php echo $this->getTitle(); ?></h4>
<?php
// display if close button (X) is set to true
if($closeX){
?> <button type="button" class="close" data-dismiss="modal">×</button> <?php } ?>
</div>
<?php } ?>
<div class="modal-body"><?php echo $this->getBodyContent(); ?></div>
<?php if($footerOpt){ ?>
<div class="modal-footer"><?php echo $this->getFooterContent(); ?>
<?php if($footerCloseBtn){ ?>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
}
}
?>
The function I am trying to call within property is as follows;
This function is not inside a class. This is present independently in functions.php which I have included in index file.
function getDocNameList() {
global $db;
$getDoc = $db->prepare("SELECT id,doc_name from doctor");
$getDoc->execute();
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
// print the returned rows in options list of <select>
echo "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
}
The initiation of class instance is as follows, Please note where I am calling the function
// create class instance
$rangeModal = new modalBox;
//set the modal id
$rangeModal->setID ("rangeFields");
//set the modal title in header
$rangeModal->setTitle("Select Date Range");
// set the body content
$rangeModal->setBodyContent("
<form method='post' action='expenditure.php'>
<div role='wrapper' class='input-group mb-3'>
<input id='datepicker1' name='exp_date_from' value='From Date' required/>
</div>
<div role='wrapper' class='input-group mb-3'>
<input id='datepicker2' name='exp_date_to' value='To Date' required/>
</div>
<div role='wrapper' class='input-group mb-3'>
<select>" . getDocNameList() . "</select>
</div>
");
//set the footer content
$rangeModal->setFooterContent("
<input type='submit' class='btn btn-success' name='submitRange' />
</form>
");
/*
* #args ---
* modal animation
* modal header (boolean)
* modal title (boolean)
* modal close X (boolean)
* modal footer (boolean)
* modal footer close button (boolean)
*/
// initiate modal
$rangeModal->initiateModal('fade',true,true,true,true,true);
I expect the output of the function to be displayed as .... within the block but instead it gets rendered at the bottom of the page just before tag.
You echo it here, so it will be displayed immediately:
echo "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
So it is not concatenated here, the function does not return anything:
<select>" . getDocNameList() . "</select>
Build it and return it instead:
$output = '';
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
$output .= "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
return $output;
Or build an array and join the elements:
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
$output[] = "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
return implode($output);
When i logged in to the site the session is not setting. It was working fine earlier but somehow it is not working now.
My controller code:
public function login_subadmin()
{
$email=$this->input->post('Email');
$password=sha1($this->input->post('Password'));
$this->sb->login_sub_admin($email,$password);
}
My Model code:
public function login_sub_admin($email,$password)
{
$this->load->library('session');
$query=$this->db->where(['Email'=>$email,'Password'=>$password])->get('dc_user');
$res=$query->row();
$this->session->set_userdata('user',$res->Employee_Name);
if(!isset($this->session->userdata['user']))
{
$this->session->set_userdata('user',"No session");
}
redirect(base_url());
}
My view Navigation:
<?php
if(!isset($this->session->userdata['user']))
{
$this->session->set_userdata('user',"No session");?>
<!-- Login -->
<li class="nav-item">
<a href="sub_Admin" class="nav-item-child radius-3">
Login
</a>
</li>
<!-- End Login -->
<?php }
if (isset($this->session->userdata['user'])) {$user=$this->session->userdata['user'];?>
<!-- Home -->
<li class="nav-item">
<a href="#" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<?php echo $user;?> <img style="width: 30px; height: 30px;" class="image-circle" src="<?php echo base_url(); ?>profileimages/<?php if (isset($this->session->userdata['profile'])) {
echo $this->session->userdata['profile'];
}?>" alt="">
When i load the page / login into the site the it says no session. i use session library in autoload, and individually also but i don't know why it suddenly stops working, It was working fine the last time i close the project, i also clear my browser cache but still did not able to fix it, i have searched a lot and applied many steps / procedures on it but did not get the issue reason.
Any help will be appreciated.
try below code
Errors:
To access profile in session you need to set it
wrong declaration of the session and few codes have been modified.
As well Session setting part should move to the controller.
In Controller
public function login_subadmin()
{
$this->load->library('session');
$email=$this->input->post('Email');
$password=sha1($this->input->post('Password'));
$result = $this->sb->login_sub_admin($email,$password);
if (empty($result)) {
redirect(base_url());
}
else {
$newdata = array(
'user' => $result[0]['Employee_Name'],
'profile' => $result[0]['Profile_Image'], # New Element
'logged_in' => TRUE
);
if (!$this->session->set_userdata($newdata)) {
echo "Cannot set session";
} else {
redirect(base_url());
}
}
}
In Model
public function login_sub_admin($email,$password)
{
$query = $this->db->query("SELECT * FROM dc_user WHERE email = '$email' AND password= '$password' ");
$result = $query->result_array();
return $result;
}
In View
<?php
$user = $this->session->userdata['user'];
if(empty($user))) # or can check logged_in == TRUE (recommended personally)
{
?>
<!-- Login -->
<li class="nav-item">
<a href="sub_Admin" class="nav-item-child radius-3">
Login
</a>
</li>
<!-- End Login -->
<?php
}
if (!empty($user))
{
?>
<!-- Home -->
<li class="nav-item">
<a href="#" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<?php echo $user;?> <img style="width: 30px; height: 30px;" class="image-circle"
src="<?php echo base_url(); ?>profileimages/<?php echo $this->session->userdata['Profile_Image'];?>" alt="">
</a>
</li>
<?php
}
I want to create a login with Facebook in my website. I found a code in the internet that made it simple loading the library of Facebook php sdk. I tried the code but it doesn't work in me. Please help me how to do login with facebook in codeigniter.
Here is the code :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/facebook/src/facebook.php' );
class FacebookApp extends Facebook {
var $ci;
var $facebook;
var $scope;
public function __construct() {
$this->ci =& get_instance();
$this->facebook = new Facebook(array('appId' => $this->ci->config->item('app_id'),'secret' => $this->ci->config->item('app_secret'), 'cookie' => true));
$this->scope = 'public_profile';
}
public function login_url() {
$params = array('scope' => $this->scope);
return $this->facebook->getLoginUrl($params);
}
public function logout_url() {
return $this->facebook->getLogoutUrl(array('next' => base_url() .'logout'));
}
public function getFbObj(){
return $this->facebook;
}
public function get_user() {
$data = array();
$data['fb_user'] = $this->facebook->getUser();
if ($data['fb_user']) {
try {
$data['fb_user_profile'] = $this->facebook->api('/me');
return $data;
} catch (FacebookApiException $e) {
$this->facebook->destroySession();
$fb_login_url = $this->facebook->getLoginUrl(array('scope' => $this->scope));
redirect($fb_login_url, 'refresh');
}
}
}
here is my controller :
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class User_Authentication extends CI_Controller
{
function __construct() {
parent::__construct();
// Load user model
$this->load->model('auth/user_model');
$this->load->library('facebook/FacebookApp');
}
public function index(){
$obj_fb = new FacebookApp();
$fb_user_data = $obj_fb->get_user();
$data['fb_login_url'] = $obj_fb->login_url();
}
}
and here is my view:
<div class="modal fade" id="choose" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<h3 class="modal-title">Connect with</h3>
</div><!-- modal-header -->
<div class="modal-body">
<div class="connectwith">
<form class="form-horizontal" id="payment">
<button onclick="<?php echo base_url()?>User_authentication" class="btn btn-primary"> Continue with Facebook </button>
</form><!-- form-horizontal -->
</div>
</div><!-- modal-body -->
</div><!-- modal-content -->
</div><!-- modal-dialog -->
</div><!-- choose -->
it shows no error when i check it on my console, i don't know what's happen, i am a beginner in adding libraries. Please help me with this. Thanks
First of all load url helper so you can use base_url().Load helper in controller...
function __construct() {
parent::__construct();
//Load Helper
$this->load->helper('url');
// Load user model
$this->load->model('auth/user_model');
$this->load->library('facebook/FacebookApp');
}
In your view replace
onclick="<?php echo base_url()?>User_authentication"
To
onclick="<?php echo base_url('user_authentication');?>"
Use this github https://github.com/bhawnam193/php-programs/tree/master/facebook-login for using fb login .
Firstly make a facebook app and replace the
$app_id ,$app_secret, $site_url
in file fbaccess.php.
in your framework are there any automation to build forms?
For example let's say you have this array of fields:
$fields = array('name'=>array('type'=>'input',otherparams)
'desc'=>array('type'=>'textarea',otherparams)
);
based on fields you should make HTML like this:
<form>
Name: <input name="name" type="text">
Description: <textarea name="desc"></textarea>
//>Submit
</form>
Do you build your html by-hand or is there some sort of automation?
Thanks
I work with the Yii framework. The php generates the html automatically. You write some html by hand but it's for the views. The views also have dynamic php variables that change. The actually full html document is put together by calling a controller with the web address, that controller deciding what models if any it needs to apply to the form and what view to put the model in. Then it generates the html.
SiteController.php
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
/**
* Displays the login page
*/
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
ContactForm.php = This is the model.
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
This is the view:
contact.php
<?php
$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
'Contact',
);
?>
<h1>Contact Us</h1>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('contact'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
</div>
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Going to the page: http://yoursite/index.php/contact/ activates the actionContact method in the SiteController. That grabs the posted contact information, puts it into a model, and then renders a view.
CodeIgniter allows you to build forms using the Form Helper, although I prefer to write the HTML myself.
try this(not tested)
<?php
$fields = array('name'=>array('type'=>'input',name='fname')
'desciprtion'=>array('type'=>'textarea',name='desc')
);
?>
<form name="myform" action="" method="post">
<?php
foreach($fields as $key=>$value)
{
echo "<label>$key</label>";
echo " <$key['type'] name=\"$key['name']\" id=\"$key['id']>\">
}
?>