i am new to code igniter and i am developing simple login system for that i am using xampp , i uploaded code igniter in folder code/ and the following are the codes in mvc
controller login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
$this->load->database();
$this->load->library('form_validation');
//load the login model
$this->load->model('login_model');
}
public function index()
{
//get the posted values
$username = $this->input->post("txt_username");
$password = $this->input->post("txt_password");
//set validations
$this->form_validation->set_rules("txt_username", "Username", "trim|required");
$this->form_validation->set_rules("txt_password", "Password", "trim|required");
if ($this->form_validation->run() == FALSE)
{
//validation fails
$this->load->view('login_view');
}
else
{
//validation succeeds
if ($this->input->post('btn_login') == "Login")
{
//check if username and password is correct
$usr_result = $this->login_model->get_user($username, $password);
if ($usr_result > 0) //active user record is present
{
//set the session variables
$sessiondata = array(
'username' => $username,
'loginuser' => TRUE
);
$this->session->set_userdata($sessiondata);
redirect("index");
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username and password!</div>');
redirect('login/index');
}
}
else
{
redirect('login/index');
}
}
}
}?>
MOdel is login_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class login_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get the username & password from tbl_usrs
function get_user($usr, $pwd)
{
$sql = "select * from tbl_usrs where username = '" . $usr . "' and password = '" . md5($pwd) . "' and status = 'active'";
$query = $this->db->query($sql);
return $query->num_rows();
}
}?>
And View is login_view
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
<!--link the bootstrap css file-->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
.colbox {
margin-left: 0px;
margin-right: 0px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-6 col-sm-6">
<h1>COLORS</h1>
</div>
<div class="col-lg-6 col-sm-6">
<ul class="nav nav-pills pull-right" style="margin-top:20px">
<li class="active">Login</li>
<li>Signup</li>
</ul>
</div>
</div>
</div>
<hr/>
<div class="container">
<div class="row">
<div class="col-lg-4 col-sm-4 well">
<?php
$attributes = array("class" => "form-horizontal", "id" => "loginform", "name" => "loginform");
echo form_open("login/index", $attributes);?>
<fieldset>
<legend>Login</legend>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="txt_username" class="control-label">Username</label>
</div>
<div class="col-lg-8 col-sm-8">
<input class="form-control" id="txt_username" name="txt_username" placeholder="Username" type="text" value="<?php echo set_value('txt_username'); ?>" />
<span class="text-danger"><?php echo form_error('txt_username'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="txt_password" class="control-label">Password</label>
</div>
<div class="col-lg-8 col-sm-8">
<input class="form-control" id="txt_password" name="txt_password" placeholder="Password" type="password" value="<?php echo set_value('txt_password'); ?>" />
<span class="text-danger"><?php echo form_error('txt_password'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-sm-12 text-center">
<input id="btn_login" name="btn_login" type="submit" class="btn btn-default" value="Login" />
<input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-default" value="Cancel" />
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</div>
</div>
</div>
<!--load jQuery library-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--load bootstrap.js-->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>
IN config i used
$config['index_page'] = '';
and in routes i used
$route['default_controller'] = 'login';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
while accessing localhost/code/ it is working fine but when click login button it is going to url http://localhost/code/localhost/login/index and showing object not found ERROR 404
Open application/config/config.php and set your base_url(). E.g: $config['base_url'] = 'http://localhost/code/';
Create .htaccess file under /code folder (Where application and system folder is) like below:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
create .htaccess file in \code\
as
RewriteEngine On
RewriteBase /code/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
and in config/config.php
$config['base_url'] = 'http://localhost/code';
Hope it will help you.
I got same error as shown below. I am using php/codeigniter. I have defined $config['base_url'] = 'http://localhost/******'; in my config file. still it was showing same issue.
Object not found! The requested URL was not found on this server. If
you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
How could I solve this.
Step 1: 1st i checked httpd.conf file. there mod_rewrite was imported.
Step 2: checked file is located at actual location or not.
Step 3: checked spelling mistake in redirection or anchor tag.
Step 4: checked $config['base_url'] variable in application/config.php file.
Step 5: checked $config['index_page'] variable in application/config.ph file. here was my actual problem. I set it to blank and there was something wrong with my mod_rewrite module. when I put $config['index_page']='index.php' it started working for me.
Related
I have a controller named : user_login_controller.php and view : user_login_view.php
code of user_login_view.php
<?php echo form_open('user_login_controller/login', 'class="form-horizontal" id="userloginform"');?>
<fieldset>
<legend>Student Login</legend>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-xs-10">
<?php echo form_input(['name'=>'rno','class'=>'form-control','placeholder'=>'Roll Number'])?>
</div>
</div>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-xs-10">
<?php echo form_password(['name'=>'pwd','class'=>'form-control','placeholder'=>'Password'])?>
</div>
</div>
<div class="col-lg-6 col-md-6 col-lg-offset-2 col-md-offset-2">
<?php echo form_reset(['name'=>'Reset','value'=>'Cancel','class'=>'btn btn-primary'])?>
<?php echo form_submit(['name'=>'Submit','value'=>'Login','class'=>'btn btn-primary'])?>
</div>
</div>
</fieldset>
</form>
On submit button click I m sending control to user_login_controller/login
here is user_login_controller.php
<?php
class User_login_controller extends MY_Controller
{
public function index()
{
$this->load->view('user/user_login_view');
}
public function login()
{
echo "User login function";
}
}
?>
but it's given me 404 error.however i have both files
and when I m going through url(http://localhost:8090/project/user_login_controller/login) :then its working. and i have loaded all the necessary helpers.
$autoload['helper'] = array('url','form');
what to do now?
You should set config['base_url'] in application/config/config.php
$config['base_url'] = 'http://localhost:8090/project/';
as form_open consider url to be set to http://localhost:80/project/ or http://[::1]/project/ if you didn't set config['base_url']
Follow below steps and it will sort-out the problem,
1. View
when you opening a form tag, if you want to add several attributes, use this method.
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'userloginform');
echo form_open('user_login_controller/login', $attributes);
?>
It's clean and error less.
2. Config.php
Go to application/config/config.php file, and set
$config['base_url'] = 'http://localhost:8090/your_project_folder_name/';
3. routes.php
Go to application/config/routes.php file, and set
$route['user_login_controller/(:any)'] = "user_login_controller/$1";
$route['user_login_controller'] = "user_login_controller";
This will work. Try it and let me know.
Why is this mod_rewrite not working?
RewriteEngine On
RewriteRule ^([a-zA-Z0-9/_-]+)(|)$ /index.php?url=$1 [L]
RewriteRule ^news/(.*)$ index.php?url=news&id=$1 [NC]
Here's the PHP code for handling the loading of the news:
<?php
$sql = DB::Query("SELECT id,title,longstory FROM news WHERE id = ".filter($_GET['id'])."");
if(DB::NumRows($sql) == 1)
{
while($news = $sql->fetch_assoc())
{
echo '
<div class="box">
<div class="title">
'.$news["title"].'
</div>
<div class="mainBox newsBox" style="float;left">
<div class="boxHeader"></div>
'.html_entity_decode($news['longstory']).'
</div>
</div>';
}
} else
{
?>
<div class='box'>
<div class='title red'>Artikel is niet gevonden.</div>
<div class='mainBox'>
Jammer genoeg is dit nieuws artikel niet gevonden!
</div>
</div>
<?php
}
?>
If I use http://127.0.0.1/index.php?url=news&id=48 it's working, but http://127.0.0.1/news/48 doesn't, even though I have added the mod_rewrite rule in my .htaccess.
your first rule does match the /news/48 pattern as well, change the order of the rules and put the specific one ^news/(.*)$ first
I'm trying to build a website that having different pages.
I'm a newbie to PHP, I have an index page with certain tables for holding header, navigation menu, main body, a sidebar and for a footer. The index page is attached to all the above-mentioned elements in it using include("filename.extension");. The problem is I tried to load the main body i.e content of the site, dynamically when the menu is changed.
Below is my code, any suggestion on this is very appreciatable. Thanks in advance.
<body>
<div> <?php Include('header.php'); </div>
<div id="menu" align="center">
<table width="790" height="35">
<tr>
<td>Home</td>
<td>Register</td> // this page need to display on the same window with other elements, after click.
</tr>
</tabel>
</div>
<div id="sidebar" align="right"> <?php include ("sidebar.php");?> </div>
<div id="Content ">
<?php include("FILE"); // here i need to display the hyper linked page.?>
</div>
<div id="footer"> <?php include("footer.php");?> </div>
</body> `
guess Diogo's answer will get you to what you want. create your index.php file like this.
//menu area
<div id="menuWrap">
link to page1
link to page2
</div>
//side bar
<div id="sidebarWrap">...</div>
//content area
<div id="contentWrap">
<?php
switch($_GET['page'])
{
case 'page1':
include '/pages/page1.php';
break;
case 'page2':
include '/pages/page2.php';
break;
default:
include '/pages/notfound.php';
}
?>
</div>
//footer
<div id="footerWrap">...</div>
This way you can display other pages in your site in the same window, only the content area will change
update:
I have got corrected your typos, here is the answer according to your code segment.
<body>
<div>
<?php Include('header.php'); ?>
</div>
<div id="menu" align="center">
<table width="790" height="35">
<tr>
<td>Home</td>
<td>Register</td>
</tr>
</table>
</div>
<div id="sidebar" align="right">
<?php include ("sidebar.php"); ?>
</div>
<div id="Content ">
<?php
switch($_GET['page'])
{
case 'page1':
include '/pages/home.php';//file path of your home page
break;
case 'page2':
include '/pages/students/reg.php';
break;
default:
include '/pages/notfound.php';
}
?>
</div>
<div id="footer">
<?php include("footer.php");?>
</div>
</body>
First, create a file with exactly the name below: (including the dot)
.htaccess
and put it in the same folder of your index.
Inside the .htaccess, write the following code:
# .htaccess mod_rewrite
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
The .htaccess on this case will rewrite the URLs to change the http://127.0.0.1/index.php?page=register to accept the "blogging pretty url" http://127.0.0.1/register
inside of your index.php folder, create a new folder "pages".
Inside of the folder pages, create 4 simple PHP files (home.php, register.php, anyother.php and notfound.php), with any content like
<?php
echo "I'm the Register Page.";
?>
This will be an example of index based on your code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8"><title>¨title</title></head>
<body>
<div>
<?php include 'header.php'; ?>
</div>
<div id="menu" align="center">
<table width="790" height="35">
<tr>
<td>Home</td>
<td>Register</td>
<td>AnyOther</td>
<td>Broken Sample</td>
</tr>
</table>
</div>
<div id="sidebar" align="right">
<?php include 'sidebar.php'; ?>
</div>
<div id="Content ">
<?php
if(!isset($_GET['page']) || $_GET['page'] == ''){
$page = 'home'; //If no page specified
} else {
$page = $_GET['page'];
}
switch($page)
{
case 'home':
include '/pages/home.php';//file path of your home page
break;
case 'register':
include '/pages/register.php';
break;
case 'anyother':
include '/pages/anyother.php';
break;
default:
include '/pages/notfound.php'; //If any page that doesn't exists, then get back to home.
}
?>
</div>
<div id="footer">
<?php include("footer.php");?>
</div>
</body>
</html>
I'm trying to create a script that logs you in and creates a session using a set usercode in the same table as my usernames.
Each usercode is different to each username as each usercode will display different data on my index.php
I am using the following code to authenticate my users and assign their usercodes:
<?php
include ("include/dbConfig.php");
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect($db_hostname, $db_username, $db_password)or die("cannot connect"); // no quotes needed around vars
mysql_select_db($db_database)or die("cannot select DB"); // no quotes needed around vars
$username = mysql_real_escape_string($_POST['username']);
$encrypted_password = mysql_real_escape_string(md5($_POST['password']));
$sql="SELECT username, password FROM $tbl_name WHERE username='$username' and password='$encrypted_password'";
$sql2="SELECT usercode FROM $tbl_name WHERE usercode='$usercode'";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$sql2= $usercode1['usercode'];
// If result matched $username and $password, table row must be *AT LEAST* 1 row
if(mysql_num_rows($result)){
session_start();
$_SESSION['isamsdata']->UserCode) != ''; //This needs fixing - array
header("Location: index.php?logged in successfully");
} else {
header("Location:login.php?msg=email or password wrong");
}
?>
My index.php:
<?php
error_reporting(E_ALL);
session_start();
//$_SESSION['isamsdata']->UserCode = 'test';
unset($_SESSION['child_id']);
unset($_SESSION['child_first_name']);
require_once('include/newuserfunction.php');
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
include "header.php";
include "topmenu.php";
include "leftmenu.php";
?>
<?php
include 'helpBox.php';
?>
<!-- BEGIN PAGE -->
<div class="page-content">
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE HEADER-->
<div class="row-fluid">
<div class="span12">
<!-- BEGIN PAGE TITLE & BREADCRUMB-->
<h3 class="page-title">
Parent Dashboard
<small>This is your dashboard.</small>
<button class="btn orange" style="float: right; width: 150px;" id="addpupil" onclick="showhidepupilbox();" >Add Pupil</button>
</h3>
<ul class="breadcrumb">
<li>
<i class="icon-home"></i>
Home
<i class="icon-angle-right"></i>
</li>
<li>Dashboard</li>
<!--<button style="float: right; background-color:green; color: white !important; margin: -1px 9px 0px 0px; border: none;" onclick="addChild();">Add Child</button>-->
</ul>
<!-- END PAGE TITLE & BREADCRUMB-->
</div>
</div>
<?php
if(isset($_GET['status']))
{
if($_GET['status'] == 1) {
echo '<div class="alert alert-success">
<button class="close" data-dismiss="alert"></button>Pupil Added Successfully. </div>';
} else {
echo '<div class="alert alert-error">
<button class="close" data-dismiss="alert"></button>Pupil Not Added Successfully. </div>';
}
}
?>
<div class="row-fluid" id="addpupilform" style="display: none;" >
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Add Pupil</h4>
</div>
<div class="portlet-body">
<div class="portlet-body form">
<form action="insert-child.php" id="add_user" class="form-horizontal add_user" method="post" name="childform">
<div class="alert alert-error hide">
<button class="close" data-dismiss="alert"></button>
You have some form errors. Please check below. </div>
<div class="alert alert-success hide">
<button class="close" data-dismiss="alert"></button>
Your form validation is successful! </div>
<div class="control-group">
<label class="control-label">First Name<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="first_name" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="last_name" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="control-group">
<label class="control-label">Date Of Birth<span class="required">*</span></label>
<div class="controls">
<input type="text" maxlength="15" name="dob" data-required="1" class="span6 inputfields m-wrap popovers field_autosave required" />
</div>
</div>
<div class="form-actions" style=" padding-left: 12px;">
<button type="submit" class="btn orange" >Add</button>
</div>
</form>
<!--- close body-form-->
</div>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="clearfix"></div>
<div class="rows">
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Pupil's Details</h4>
</div>
<div class="portlet-body">
<!--<div class="scroller" style="height: 300px;" data-always-visible="1" data-rail-visible="0">-->
<div class="portlet-body">
<?php if(getUserChilds($_SESSION['isamsdata']->UserCode) != '') { ?>
<table class="table table-striped table-bordered table-hover" id="sample_2">
<thead>
<tr>
<th >First Name</th>
<th>Last Name</th>
<th>Date Of Birth</th>
<th>Change Details</th>
<th>Progress</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
echo getUserChilds($_SESSION['isamsdata']->UserCode);
?>
</tbody>
</table>
<?php } else { ?>You have not setup any pupil account currently, please fill the form by clicking the Add Pupil icon above.<?php } ?>
</div>
</div>
<!-- scroller </div>-->
</div>
</div>
<!-- End Rows-->
</div>
<!-- Close Div span12-->
</div>
<!-- Close Row-span12 -->
</div>
<!-- Close Row-fluid -->
<div class="row-fluid">
<div class="span12">
<div class="clearfix"></div>
<div class="rows">
<div class="span12">
<div class="portlet box orange-steel">
<div class="portlet-title">
<h4><i class="icon-table"></i>Welcome Parent</h4>
</div>
<div class="portlet-body">
<!--<div class="scroller" style="height: 300px;" data-always-visible="1" data-rail-visible="0">-->
<div class="portlet-body">
Dear <i><?php echo $_SESSION['parentdetails']->title;?> <?php echo $_SESSION['parentdetails']->firstName;?> <?php echo $_SESSION['parentdetails']->surname;?>,</i><br><br>
<p>
A very warm welcome to the on-line joining forms and thank you so much for logging on. We know there's a lot to do here but we hope that completing these on-line forms will be relatively easy and stress-free. Simply enter the name of your son or daughter above by clicking on the ‘add pupil’ tab at the top right hand corner of this page and then click ‘Fill form’.
</p>
<p>
The fields which contain a red asterisk symbol must be completed. All updates to the forms are automatically saved so you can return to the on-line joining forms at any time to complete your submissions.
</p><p>
We recommend that you have a copy of the new parents' Joining Booklet in front of you whilst completing these forms. Don't worry if you haven't, because you can access a PDF of the Joining Booklet 2014 here. Information and help icons are available on all the forms in case you need guidance and, if you are still stuck, please do not hesitate to call the Admissions Office on 000000000.
</p><p>
As well as the forms, we would be very grateful if you could upload a picture of your son/daughter when prompted (this does not have to be a passport photo) and also a copy of the main page of your son or daughter's passport with all their details on it. If you do not have access to a scanner, then please feel free to send in a photocopy to Name, Registrar, at the usual School/College address.
</p><p>
I should also remind you that we do require the following to be posted in hard-copy back to the School/College:</p><p>
<ul style="width: 80%;">
<li>The Medical Forms (required) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
<li>The Direct Debit Form (if appropriate) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
<li>The Gift Aid Form (if appropriate) <a class="pull-right" href="#" target="_blank">Download Form</a></li>
</ul></p><p>
All forms should be completed by Monday 16th June. The information provided on these forms will be processed lawfully and fairly and held for our management and administrative purposes only.
</p><p>
I do hope that you all remain as excited about September as we are, and we look forward to seeing you all soon.
</p><p>
With best wishes,
</p><p>
Name here<br>
Director of Admissions
</p> </div>
</div>
<!-- scroller </div>-->
</div>
</div>
<!-- End Rows-->
</div>
<!-- Close Div span12-->
</div>
<!-- Close Row-span12 -->
</div>
<!-- Close Row-fluid -->
</div>
</div>
<!-- END PAGE CONTAINER-->
</div>
<!-- END PAGE CONTAINER-->
</div> <!-- END PAGE -->
<?php
include "footer.php";
} else {
header("Location:login.php");
}
?>
<script>
function showhidepupilbox()
{
console.log('Check');
jQuery('#addpupilform').toggle();
}
jQuery(document).ready(function() {
jQuery('#addpupilform').hide();
jQuery('#addpupil').click(function(){
console.log('sdf');
jQuery('#addpupilform').toggle();
});
App.setPage("table_managed"); // set current page
App.init(); // init the rest of plugins and elements
});
jQuery(document).ready(function() {
App.setPage("form_validation"); // set current page
App.init(); // init the rest of plugins and elements
});
jQuery(document).ready(function() {
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
I'm quite new to PHP and SQL so any corrections would be respected!
If any database structures are needed, please ask.
What can be improved / needs fixing:
You are using mysql_, which is depreciated since php 5.5 and shouldn't be used any more. Since you are new to php, now is the right time to learn PDO or mysqli_!
You are using md5, which shouldn't be used any more.
And:
session_start();
needs to be the first line in all files that make use of session.
I guess you are using a tutorial that you have found - which is the right way, but I recommend finding another one.
I haven't fixed the md5 issue, because your passwords need to be changed in DB and the script wouldn't work if I did - but change it to mcrypt
I wrote a comment in the code - variable $usercode isn't set, I don't know where it's comming from, you might want to include usercode in the first query/do both together.
Here is your file writen with PDO:
<?php
session_start();
include('include/.db_def.php');
try {
$connection = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE , USER_ONE, PASS_ONE);
$state = $connection->prepare("SELECT username, password FROM users WHERE username = :names AND password = :password");
$state->execute(array('names' => $_POST['username'], 'password' => md5($_POST['password'])));
list ($user,$password)=$state->fetch(PDO::FETCH_NUM);
$state->closeCursor();
$state2 = $connection->prepare("SELECT usercode FROM users WHERE usercode= :usercode");
$state2->execute(array('usercode' => $usercode)); //<<< $usercode isn't set, you need to fix this
list($usercode)=$state2->fetch(PDO::FETCH_NUM);
$state2->closeCursor();
unset($connection);
if (isset($usercode) AND $usercode != '')
{
$_SESSION['isamsdata'] = $usercode;
header("Location: index.php?logged in successfully");
exit();
}
else {
header("Location:login.php?msg=email or password wrong");
exit();
}
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
Your .db_def.php should look like this:
define('HOST_ONE','your host');
define('USER_ONE','db_user');
define('PASS_ONE','db_pass');
define('DB_ONE','db');
SIDENOTE:
I suppose usercode is in the users table? If so, change the query to:
$state = $connection->prepare("SELECT username, password, usercode FROM users WHERE username = :names AND password = :password");
and the part after list to:
list ($user,$password,$usercode)=$state->fetch(PDO::FETCH_NUM);
You can then get rid of the second query!
Here is the complete code with only one query:
<?php
session_start();
include('include/.db_def.php');
try {
$connection = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE , USER_ONE, PASS_ONE);
$state = $connection->prepare("SELECT username, password, usercode FROM users WHERE username = :names AND password = :password");
$state->execute(array('names' => $_POST['username'], 'password' => md5($_POST['password'])));
list ($user,$password,$usercode)=$state->fetch(PDO::FETCH_NUM);
$state->closeCursor();
unset($state,$connection);
if (isset($usercode) AND $usercode != '')
{
$_SESSION['isamsdata'] = $usercode;
header("Location: logged_in.php?logged in successfully");
exit();
}
else {
header("Location:login.php?msg=email or password wrong");
exit();
}
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
?>
Your next pages should start like this:
<?php
session_start();
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
// user seems to be logged in, do whatever you want here
}
else
{
header("Location:login.php?msg=you_are_not_logged_in");
exit();
}
File structure I would recommend:
Create a folder "views"
in views, put this .htaccess file:
<Files ~ "\.(htaccess|php)$">
order allow,deny
deny from all
</Files>
in your root folder, put the file I wrote above and name it index.php, and create the following file for every file you want to run, for the start, name it logged_in:
<?php
session_start();
if (isset($_SESSION['isamsdata']) AND $_SESSION['isamsdata'] != '') {
include('views/logged_in.php'); //here you put the file you want to run
}
else
{
header("Location:login.php?msg=not_logged_in");
exit();
}
Now, all the files you want to run will have to be in the 'views' folder, but you allways link to the file in your root folder. You need to create two files with the same name(makes it easier), one in root, one in views. In root, the file should contain the line
include('views/index.php');
but changed to the file you want to run, f.e.
include('views/dashboard.php');
Now create the file logged_in.php in "views" and just put
<?= "HELLO"; ?>
into it, just to see if it's running.
$sql2="SELECT usercode FROM $tbl_name WHERE usercode='$usercode'"
Variable $usercode is undefined
$sql2= $usercode1['usercode'];
Variable $usercode1 is undefined and code is very strange
$_SESSION['isamsdata']->UserCode) != '';
This code is strange. If you want compare it then you should use operator if
I recommended you turn full error reporting and turn on errors output. You can make this by PHP settings in php.ini or in your code.
For example in begin of script
error_reporting(E_ALL);
ini_set("display_errors", 1);
You can do like follwing code:
<?php
session_start();
include ("include/dbConfig.php");
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect($db_hostname, $db_username, $db_password)or die("cannot connect"); // no quotes needed around vars
mysql_select_db($db_database)or die("cannot select DB"); // no quotes needed around vars
$username = mysql_real_escape_string($_POST['username']);
$encrypted_password = mysql_real_escape_string(md5($_POST['password']));
$sql="SELECT usercode FROM $tbl_name WHERE username='$username' and password='$encrypted_password'";
$result=mysql_query($sql);
// If result matched $username and $password, table row must be *AT LEAST* 1 row
if(mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$usercode= $row['usercode'];
if($usercode!=''){
$_SESSION['isamsdata']->UserCode= $usercode;
header("Location: index.php?logged in successfully");
} else {
header("Location:login.php?msg=email or password wrong");
}
}
?>
I'm currently learning PHP and am creating a small CMS feature that includes a login area. I have used the code below which includes an include header file that contains the doctype/head info and the opening tag. It also includes the header content. I also have a connection file for connecting to the db.
My header include code is:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title><?php echo $pagetitle ?></title>
<link rel="stylesheet" href="../stylesheets/foundation.css">
<link rel="stylesheet" href="../stylesheets/app.css">
<style>#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800); #import url (http://fonts.googleapis.com/css?family=Kreon:100,200,300,400);</style>
<script src="../javascripts/modernizr.foundation.js"></script>
</head>
<body>
<div class="subHeader">
<div class="row">
<div class="four columns logo">
<img src="../images/logo.png" alt="logo" />
</div>
<div class="eight columns navigation right">
<ul class="navigationMain">
<li class="<?php if($navcurrent == "home"){echo "navigationActive";} ?>">Home</li>
<li class="<?php if($navcurrent == "services"){echo "navigationActive";} ?>">Services</li>
<li class="<?php if($navcurrent == "work"){echo "navigationActive";} ?>">Recent Work</li>
<li class="<?php if($navcurrent == "about"){echo "navigationActive";} ?>">About</li>
<li class="<?php if($navcurrent == "contact"){echo "navigationActive";} ?>">Contact</li>
</ul>
</div>
<div class="twelve columns titlesection">
<h2><?php echo $headTitle ?></h2>
<h4><?php echo $headsubTitle ?></h4>
</div>
</div><!--End Feature Row-->
</div><!--End Feature-->
<div class="underbar">
<div class="bordertriangle"></div>
<div class="row">
<div class="eight columns"> </div>
<div class="three columns right socialcontainer">
<ul class="socialicons">
<li><a><img id="linkedinIcon" src="../images/socialli.png" alt="linkedin icon" /></a></li>
<li><a><img id="twitterIcon" src="../images/socialtw.png" alt="twitter icon" /></a></li>
<li><a><img id="facebookIcon" src="../images/socialfb.png" alt="facebook icon" /></a></li>
</ul>
</div>
</div>
When I open the admin page, the username password form, header and footer appear as they should. If I test the errors, they return as they should. However, when I successfully log in using a valid username and password, no content appears except the what is included in the header file. Can anyone point me in the direction of what i might be doing wrong? Any help would be much appreciated. I am a relative noob to PHP...
<?php
$pagetitle = "Admin";
$navcurrent = "home";
$headTitle = "ADMIN AREA";
$headsubTitle = "SITE ADMINISTRATION AREA";
include_once('../includes/connection.php');
include_once('../includes/headeradmin.php');
if (isset($_SESSION['logged_in'])) {
echo('Successfully Logged In');
} else {
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)){
$error = 'An Error Has Occurred - All Fields Are Required';
}
else{
$query = $pdo->prepare('SELECT * FROM users WHERE user_name = ? AND user_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('location: index.php');
exit();
}
else{
$error = 'The username/password you entered was incorrect - Please try again';
}
}
}
?>
<div class="row">
<div class="four columns centered">
<?php if (isset($error)) { ?>
<h5 style="color: #e63333;"><?php echo $error; ?></h5>
<br />
<br />
<?php } ?>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</div>
You can't use the header('location: index.php'); line if you've already output content (i.e - html code) to the browser when you included the header in this line include_once('../includes/headeradmin.php');
read the documentation of header - Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
you need to redirect the user with the header() function before you output the head html of the admin page