Auto fill-in data (input field) from MySQL Database in PHP (PDO) - php

This post contains:
3 PHP pages
MySQL table picture
Picture of the form
As the title says, I need to extract some information from my database.
So far I have the following:
Index page <-- You need to login here with a personal code. (this is where I get the 'Session username' from that already works at the contact page)
Config page <-- Used for database access and all
Contact page <-- In here I would like to auto fill-in the users data.
Database table consists of:
username; email; realName (and some other stuff I don't need here)
So in the contact page I would like to see the following:
Card number = username (this already works)
Auto fill-in: realName and email according to the username.
Maybe it is possible to extract the info when logging in and storing these in the POST variable already? But how?
Database:
Table I need to use: 'members'
The info given by the user himself/herself = username
The info I need to auto fill-in = realName and email
Picture of the form.
The email should be in the SESSION statement, so I can send a confirmation email to the person, and the realName should be entered from the database.
These are the files currently running:
config.php:
<?php
ob_start();
session_start();
//set timezone
date_default_timezone_set('Europe/Brussels');
//database credentials
define('DBHOST','*****');
define('DBUSER','*****');
define('DBPASS','*****');
define('DBNAME','*****');
//application address
define('DIR','http://*****/');
define('SITEEMAIL','noreply#*****');
try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
contact form:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); }
?>
<html>
<head>
<title>*****</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/shiv.js"></script><![endif]-->
<link rel="stylesheet" href="siteassets/assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="siteassets/assets/css/ie8.css" /><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#next').keyup(calculate);
$('#nextprice').keyup(calculate);
$('#current').keyup(calculate);
$('#currentprice').keyup(calculate);
});
function calculate(e)
{
$('#total').val($('#next').val() * $('#nextprice').val() + $('#current').val() * $('#currentprice').val());
}
</script>
</head>
<body class="landing">
<div id="page-wrapper">
<!-- Header -->
<header id="header" class="alt">
<nav id="nav">
<ul>
<li>
Menu
<ul>
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
</ul>
</li>
<li>contact</li>
<li><a href='logout.php'>Logout</a></li>
</ul>
</nav>
</header>
<!-- Banner -->
<section id="banner">
<h2>*****</h2>
<p>Slogan.</p>
<ul class="actions">
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
<li>contact</li>
</ul>
</section>
<!-- Main -->
<section id="main" class="container 75%">
<div class="box">
<?
if($_SERVER['REQUEST_METHOD']=="POST")
{
if(strlen($_POST['name2']) == 0)
{ $error_msg ="- Please, provide us with your name.<br>"; }
if(!empty($error_msg))
{
//Een van de velden werd niet goed ingevuld
echo "<b>Your message can't be send due to the following reason:</b> <br><br>";
echo $error_msg;
echo "<br>Click on <a href='javascript:history.back(1)'>Go back</a> and provide us with your name.<br><br>";
}
else
{
$recipient = "*****";
$subject = "******";
$header = "From: " . $_POST['uwemail'] . "\n";
$mail_body = "Contact script werd op " . date("d-m-Y") . " om " . date("H:i") . " uur uitgevoerd.\n";
$mail_body .= "*****:\n\n";
$mail_body .= "Naam: " . $_POST['name2'] . "\n";
$mail_body .= "Met als kaartnummer: " . $_POST['card2'] . "\n";
$mail_body .= "******: " . $_POST['current2'] . "\n";
$mail_body .= "******: " . $_POST['next2'] . "\n";
$mail_body .= "Voor een totaal van: " . $_POST['total2'] . " EUR.";
$mail_body .= "\n\n -- ****** --";
mail($recipient, $subject, $mail_body, $header);
print "<b>IMPORTANT!</b>";
print "<br><br>*****.";
print "<br><br>***** ";
print $_POST['total2'];
print " *****";
print "<br><br>******.";
print "<br><br>******";
}
}
else
{
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" readonly/>
</div>
<div class="6u 12u(mobilep)">
Please enter your name. (mandatory)
<input type="text" name="name2" id="name" value="" placeholder="Your name" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Current Project - Smile
<input type="text" name="current2" id="current" value="" placeholder="How many tickets would you like?" />
</div>
<div class="6u 12u(mobilep)">
Next Project - Sand
<input type="text" name="next2" id="next" value="" placeholder="How many tickets would you like?" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice" value="10" placeholder="" />
</div>
</div>
<div class="6u 12u(mobile)">
<input name="uwemail" placeholder="Email" type="hidden" value="******"/>
</div>
<div class="6u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" readonly/>
</div>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
<?php
}
?>
</div>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© *****. All rights reserved.</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<script src="siteassets/assets/js/jquery.min.js"></script>
<script src="siteassets/assets/js/jquery.dropotron.min.js"></script>
<script src="siteassets/assets/js/jquery.scrollgress.min.js"></script>
<script src="siteassets/assets/js/skel.min.js"></script>
<script src="siteassets/assets/js/util.js"></script>
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/respond.min.js"></script><![endif]-->
<script src="siteassets/assets/js/main.js"></script>
</body>
</html>
Index page (where they have to login)
<?php
//include config
require_once('includes/config.php');
//process login form if submitted
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: home.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}//end if submit
?>
<html>
<head>
<title>******</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/iv.js"></script><! [endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /> </noscript>
</head>
<body class="is-loading">
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<section id="main">
<header>
<h1>*****</h1>
<h1><a style="color:#FFFFFF" href=''>Coming soon.</a></h1>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Login</h2>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please contact us for a new card.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Enter your card number" value=" <?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="hidden" name="password" id="password" class="form-control input-lg" value="*****" tabindex="3" >
</div>
<br>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Login" class="btn btn-primary btn-block btn-lg" tabindex="5"></div>
</div>
<hr>
<div class="row">
<div class="col-xs-9 col-sm-9 col-md-9">
<a style="color:#FFFFFF" href='*********'>Lost your card? Contact us.</a>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ******</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<!--[if lte IE 8]><script src="assets/js/respond.min.js"> </script><![endif]-->
<script>
if ('addEventListener' in window) {
window.addEventListener('load', function() { document.body.className = document.body.className.replace(/\bis-loading\b/, ''); });
document.body.className += (navigator.userAgent.match(/(MSIE|rv:11\.0)/) ? ' is-ie' : '');
}
</script>
</body>
</html>

EDITED: Since you're having user class (ex.: $user->is_logged_in()), then in $_POST[] method ignore $_POST['name2'] as it can still be changed through DEV tools and instead change that to $_SESSION['username'] (assuming that's the correct value). This is much more reliable than using HTML field. The PHP part (of query) also differs because you're using PDO, but I can't help with this one because I'm using mysqli_, not PDO (sorry about that), but query itself should be similar.
"SELECT * FROM `table` WHERE `number` = '".$_POST['number']."'"
But don't forget to escape your string, otherwise, your query is vulnerable.

I fixed the problem.
In the user.php file I had everything prepared already, but I just didn't understand why it didn't work.
Turned out to be a simple error XD
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['realName'] = $row['realName'];
$_SESSION['email'] = $row['email'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
return true;
}
}
}
?>
I forgot to add the realName and email to this line: (idiot me :D)
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');

Related

Adding function to differentiate between user and admin login page

Im currently working on this project for my assignment.i need to differentiate between user and admin on the login page. What changes should i made for the login page can differentiate between the user and admin ? these codes working just fine.
index.php
<?php
require_once 'php_action/db_connect.php';
session_start();
if(isset($_SESSION['userId'])) {
header('location: http://localhost/managementsystem/dashboard.php');
}
$errors = array();
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) || empty($password)) {
if($username == "") {
$errors[] = "Username is required";
}
if($password == "") {
$errors[] = "Password is required";
}
} else {
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $connect->query($sql);
if($result->num_rows == 1) {
$password = md5($password);
// exists
$mainSql = "SELECT * FROM users WHERE username = '$username' AND password='$password'";
$mainResult = $connect->query($mainSql);
if($mainResult->num_rows == 1) {
$value = $mainResult->fetch_assoc();
$user_id = $value['user_id'];
//set session
$_SESSION['userId'] = $user_id;
header('location: http://localhost/managementsystem/dashboard.php');
} else {
$errors[] = "Incorrect Username or Password combination";
}
}else {
$errors[] = "Username does not exists";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Log-in Page</title>
<!-- bootstrap -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">
<!-- bootstrap theme -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap-theme.min.css">
<!-- font awesome -->
<link rel="stylesheet" type="text/css" href="assets/font-awesome/css/font-awesome.min.css">
<!-- custom css -->
<link rel="stylesheet" href="custom/css/custom.css">
<!-- jquery -->
<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
<!-- jquery ui -->
<link rel="stylesheet" href="assets/jquery-ui/jquery-ui.min.css">
<script src="assets/jquery-ui/jquery-ui.min.js"></script>
<!-- bootstrap js -->
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row vertical">
<div class="col-md-5 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-info">
<div class= "panel-heading text-center">
<h3 class= "panel-title">MH ALLIM Management System</h3>
</div>
<div class="panel-body">
<div class="messages">
<?php if($errors) {
foreach ($errors as $key => $value) {
echo '<div class="alert alert-warning" role="alert">
<i class="glyphicon glyphicon-exclamation-sign"></i>
'.$value.'</div>';
}
} ?>
</div>
<form class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" id="loginForm">
<div class="form-group">
<label for="inputUser3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default"> <i class="glyphicon glyphicon-log-in"></i>
Sign in</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Session.php
<?php
session_start();
require_once 'db_connect.php';
//echo $_SESSION['userId'];
if(!$_SESSION['userId']) {
header('location: http://localhost/managementsystem/index.php');
}
?>
should i modify the session so the normal user cannot access to the admin page ?
Thanks :)
You should have something that makes user and admin different. So, you can simply add a new column to your table with the name "role" (for example). If the user is a User, then the role will be "user". Same thing with any Admin, the role will be "admin".
And you can write the following code to your admin's page to prevent any login from unauthorized users. Use the same code with the user's page to prevent any login from any admin to the user's page "change this part to: $_SESSION['role'] != 'user')"
<?php
session_start();
require_once 'db_connect.php';
if( (empty($_SESSION['userId'])) || ($_SESSION['role'] != 'admin') ) {
echo "<script>window.open('index.php','_self');</script>";
}
else {
$userId = $_SESSION['userId'];
}
?>
Use if and else to separate it:
if(type="admin")
{
do somethg
}
else
{
do somethg
}

How to keep the user logged on the entire web

I have a problem logging users. When logs, session work, but when you click to another page, the session will disappear and does not work and when I put session_start to the main page and to login.php, I got error that session is already running. Some ideas? Thanks
Main Page.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="css.css">
<link rel="icon" href="favicon.ico">
<title>----</title>
</head>
<body>
<!-- HEADER _____________________________________________________________________________ -- >
<div id="whiteblock">
<div id="grayblock">
<div id="logo">
</div>
<h1>----</h1>
<h2>----</h2>
Registration
<?php
include "Login.php";
echo $_SESSION["LogiNick"];
?>
<div id="inputposunuti">
<form name="Log" id="Log" method="post">
<label for="Nick" class="inputtext">Nick:</label>
<input type="text" name="LogiNick" id="LogiNick" class="input"> <?php echo $EmptyNick; echo $Else; ?>
<label for="Pass" class="inputtext">Password:</label>
<input type="password" name="LogiPass" id="LogiPass" class="input"> <?php echo $EmptyPass; echo $Else; ?>
<input type="submit" name="LogIn" value="⇒">
</form>
</div>
</div>
<!-- HEADER _____________________________________________________________________________ -->
<!-- MENU _______________________________________________________________________________ -->
<div id="pruh">
<div id="search">
<form name="search" method="post">
<input type="text" name="hledat" id="sirka">
<input type="submit" name="subhledat" value="Search!" id="button">
</form>
</div>
<div id="menutext">
<p>Home</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
</div>
</div>
<!-- MENU _______________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<div id="teams"></div>
</div>
<p id="creator">Created by</p>
Login.php
<?php
session_start();
include_once "db.php";
global $db;
$Else = $EmptyNick = $EmptyPass = $EmptyNick = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$LogiNick = $_POST["LogiNick"];
$LogiPass = $_POST["LogiPass"];
if (empty($_POST["LogiNick"])) {
$EmptyNick = " - Nick";
}
if (empty($_POST["LogiPass"])) {
$EmptyPass = " - Password";
}
}
if(!empty($_POST["LogiNick"]) AND !empty($_POST["LogiPass"])){
$LogiPass = $_POST["LogiPass"];
$SHA = sha1($LogiPass);
$sql = "SELECT * FROM WEB_REGISTER WHERE Nick = :nick AND Heslo = :heslo";
$query = $db->prepare($sql);
$query->execute(array('nick' => $LogiNick, 'heslo' => $SHA));
$count = $query->rowCount();
if ($count > 0) {
$_SESSION["LogiNick"];
}
}
?>
You just set a session if you put a value into it.
$_SESSION["name"]=$value;

Echo not displaying, or adding ID, but shows up in database

I set up a PHP database that worked perfectly on my local server. Then, when I went to put it online through my hosting site, Site5, I was getting these kinds of errors: "Cannot modify header information – headers already sent by...". So I changed the PHP file on Site5 to have output buffering turned on. Now, I am not getting an error, however, whenever I input data, it doesn't echo it back - however, it does show up in the database in phpMyAdmin (but without an ID).
Any ideas as to why it isn't echoing back and why it's new data isn't getting an ID?
Here it is live (and broken):
http://hjaramillo.com/tell_me/index.php
<!DOCTYPE html>
<html class="no-js" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A Message For You</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="css/media.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
</head>
<?php
ob_start();
//error_reporting(0);
require 'db/connect.php';
require 'functions/security.php';
error_reporting(E_ALL);
$records = array();
if(!empty($_POST)){
if(isset($_POST['first_name'],$_POST['location'],$_POST['message'])) {
$first_name = trim($_POST['first_name']);
$location = trim($_POST['location']);
$message = trim($_POST['message']);
if(!empty($first_name) && !empty($location) && !empty($message)) {
$insert = $db -> prepare("INSERT INTO message (first_name, location, message, date) VALUES (?,?,?,NOW())");
$insert->bind_param('sss',$first_name,$location,$message);
if($insert -> execute()){
header ('Location: index.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM message ORDER BY id DESC LIMIT 1")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results -> free();
}
}
?>
<?php
if (!count($records)){
echo 'No messages';
} else{
?>
<?php
foreach($records as $r){
?>
<body>
<?php
}}
?>
<div class="form-show">
<div class="post-icon">
<img src="images/post_icon.png"/>
</div>
</div>
<div class="form-background">
<div class="form-container">
<div class="form-title">
<p>Tell someone that:</p>
</div>
<form action="index.php" method="post">
<div class="fields msg">
<!--<label for="message">Message</label>-->
<textarea name="message" id="message" autocomplete="off"></textarea>
</div>
<div class="fields">
<ul>
<li> <label for="first_name">Name</label> </li>
<li> <input type="text" class="s-input" name="first_name" id="first_name" autocomplete="off"> </li>
</ul>
</div>
<div class="fields last">
<ul>
<li><label for="location">Location</label></li>
<li><input type="text" class="s-input" name="location" id="location" autocomplete="off"></li>
</ul>
</div>
<input type="submit" value="Post" id="submit-button">
</form>
<div>
</div>
</div>
</div>
<div class="msg-container">
<div class="msg-intro">
<p> On <?php echo escape($r->date); ?>,</p>
<p><span style="text-transform:capitalize;"><?php echo escape($r->first_name); ?> </span> from
<span style="text-transform:capitalize;"><?php echo escape($r->location); ?></span> wanted to tell you:</p>
</div>
<div class="msg-content">
<p><?php echo escape($r->message); ?></p>
</div>
</div>
</body>
<script type="text/javascript" src="js/application.js"></script>
</html>
Someone earlier asked if my ID was set to AUTO INCREMENT - it wasn't. That was the problem, thanks!

Syntax Error, unexpected $end -- PHP error, what's wrong?

My entire error code is Parse error: syntax error, unexpected $end in /home/a3704125/public_html/home.php on line 356
Here is my entire PHP file.. Tell me what the problem may be? ._. Thanks!
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('GamesFXLogin');
// Starting the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['GamesFXRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the GamesFXRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: home.php?logout=true");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM gamesfx_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('GamesFXRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php?page=home&error=true");
exit;
}
else if($_POST['submit']=='Register')
{
// If the Register form has been submitted
$err = array();
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['username'] == '')
{
$err[] = 'User Name is required.';
}
if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
$err[]='Your username must be between 3 and 32 characters!';
}
if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
$err[]='Your username contains invalid characters!';
}
//whether the email is blank
if($_POST['email'] == '')
{
$err[]='E-mail is required.';
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$sql1 = "SELECT * FROM gamesfx_members WHERE email = '$email'";
$result1 = mysql_query($link,$sql1) or die(mysql_error());
if (mysql_num_rows($result1) > 0)
{
$err[]='This Email is already used.';
}
}
else
{
//this error will set if the email format is not correct
$err[]='Your email is not valid.';
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$err[]='Password is required.';
}
if(!count($err))
{
// If there are no errors
// Make sure the email address is available:
if(!count($err))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$activation = md5(uniqid(rand()));
$encrypted=md5($password);
$sql2 = "INSERT INTO gamesfx_members (usr, email, pass, Activate) VALUES ('$username', '$email', '$encrypted', '$activation')";
$result2 = mysql_query($link,$sql2) or die(mysql_error());
if($result2)
{
$to = $email;
$subject = "Confirmation from GamesFX to $username";
$header = "GamesFX: Confirmation from GamesFX";
$message = "Please click the link below to verify and activate your account. rn";
$message .= "http://www.mysite.com/activate.php?key=$activation";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
}
exit();
}
}
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
$script = '
<script type="text/javascript">
$(function(){
$("div#panel").show();
$("#toggle a").toggle();
});
</script>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A Cool Login System With PHP MySQL &amp jQuery | Tutorialzine demo</title>
<link rel="stylesheet" type="text/css" href="demo.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/slide.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!-- PNG FIX for IE6 -->
<!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
<!--[if lte IE 6]>
<script type="text/javascript" src="js/pngfix/supersleight-min.js"></script>
<![endif]-->
<script src="js/slide.js" type="text/javascript"></script>
<?php echo $script; ?>
</head>
<body>
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<div class="left">
<h1>The Sliding jQuery Panel</h1>
<h2>A register/login solution</h2>
<p class="grey">You are free to use this login and registration system in you sites!</p>
<h2>A Big Thanks</h2>
<p class="grey">This tutorial was built on top of Web-Kreation's amazing sliding panel.</p>
</div>
<?php
if(!$_SESSION['id']):
?>
<div class="left">
<!-- Login Form -->
<form class="clearfix" action="" method="post">
<h1>Member Login</h1>
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Remember me</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
<div class="left right">
<!-- Register Form -->
<form action="" method="post">
<h1>Not a member yet? Sign Up!</h1>
<?php
if($_SESSION['msg']['reg-err'])
{
echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
unset($_SESSION['msg']['reg-err']);
}
if($_SESSION['msg']['reg-success'])
{
echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
unset($_SESSION['msg']['reg-success']);
}
?>
<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="30" />
<label>A password will be e-mailed to you.</label>
<input type="submit" name="submit" value="Register" class="bt_register" />
</form>
</div>
<?php
else:
?>
<div class="left">
<h1>Members panel</h1>
<p>You can put member-only data here</p>
View your profile information and edit it
<p>- or -</p>
Log off
</div>
<div class="left right">
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div> <!--panel -->
I am trying to use the slide panel that's a login panel.. Don't know if you ever heard of it. But anyhow, I am wondering how to fix this error. As-for I can't see what the problem may be.. I'm banging my head over it, thanks for the help!
EDIT: I added what's after the below this text..
<div class="pageContent">
<div id="main">
<div class="container">
<h1>A Cool Login System</h1>
<h2>Easy registration management with PHP & jQuery</h2>
</div>
<div class="container">
<p>This is a simple example site demonstrating the Cool Login System tutorial on <strong>Tutorialzine</strong>. You can start by clicking the <strong>Log In | Register</strong> button above. After registration, an email will be sent to you with your new password.</p>
<p>View a test page, only accessible by <strong>registered users</strong>.</p>
<p>The sliding jQuery panel, used in this example, was developed by Web-Kreation.</p>
<p>You are free to build upon this code and use it in your own sites.</p>
<div class="clear"></div>
</div>
<div class="container tutorial-info">
This is a tutorialzine demo. View the original tutorial, or download the source files. </div>
</div>
</div>
</body>
</html>
Closing brackets in here :
else if($_POST['submit']=='Register')
{
Put two closing brackets here:
$script = '';
}} #line 175
if($_SESSION['msg'])
Moral: always put opening and closing brackets together when going for any condition statement.

PHP Session doesn't work in my edited script

Just edited php sliding jquery panel form and it doesn't work, actually registration works but login doesn't. I erased some code that doesn't matter in my problem...
Please ignore these error messages in this strange language.
<?php
error_reporting(0);
define('INCLUDE_CHECK',true);
require_once($_SERVER['DOCUMENT_ROOT'] . '/config.php');
session_start();
session_name('avaLogin');
session_set_cookie_params(2*7*24*60*60);
if($_SESSION['id'] && !isset($_COOKIE['avaRemember']) && !$_SESSION['rememberMe'])
{
$_SESSION = array();
session_destroy();
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
echo('<script type="text/javascript">window.location = "' . $SITE_URL .'"</script>');
exit;
}
if($_POST['submit']=='Zaloguj')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'Wszystkie pola muszą być wypełnione!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
echo '';
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM ava_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('avaRemember',$_POST['rememberMe']);
}
else $err[]='Zły login i/lub hasło!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
echo('<script type="text/javascript">window.location = "' . $SITE_URL .'"</script>');
exit;
}
else if($_POST['submit']=='Zarejestruj')
{
// If the Register form has been submitted
$err = array();
if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
$err[]='Twój login musi mieć pomiędzy 3 i 32 znaki!';
}
if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
$err[]='Twoje hasło zawiera niedozwolone znaki!';
}
if(!checkEmail($_POST['email']))
{
$err[]='Twój e-mail jest nieprawidłowy!';
}
if(!count($err))
{
// If there are no errors
$pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
// Generate a random password
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$_POST['username'] = mysql_real_escape_string($_POST['username']);
// Escape the input data
mysql_query(" INSERT INTO ava_members(usr,pass,email,regIP,dt)
VALUES(
'".$_POST['username']."',
'".md5($pass)."',
'".$_POST['email']."',
'".$_SERVER['REMOTE_ADDR']."',
NOW()
)");
if(mysql_affected_rows($avalink)==1)
{
send_mail( 'support#avatar.itterek.net',
$_POST['email'],
$SITE_NAME . ' - Twoje hasło',
'Twoje hasło to: '.$pass);
$_SESSION['msg']['reg-success']='Wysłaliśmy do Ciebie e-mail z nowym hasłem!';
}
else $err[]='Ten login jest już w użyciu!';
}
if(count($err))
{
$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}
echo('<script type="text/javascript">window.location = "' . $SITE_URL .'"</script>');
exit;
}
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
$script = '
<script type="text/javascript">
$(function(){
$("div#panel").show();
$("#toggle a").toggle();
});
</script>';
}
?>
<link rel="stylesheet" type="text/css" href="<?php echo $LOGIN_URL; ?>/style.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo $LOGIN_URL; ?>/login_panel/css/slide.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!-- PNG FIX for IE6 -->
<!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
<!--[if lte IE 6]>
<script type="text/javascript" src="login_panel/js/pngfix/supersleight-min.js"></script>
<![endif]-->
<script src="<?php echo $LOGIN_URL; ?>/login_panel/js/slide.js" type="text/javascript"></script>
<?php echo $script; ?>
</head>
<body>
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<div class="left">
<h2>REGULAMIN</h2>
<p class="grey">Rejestracja i/lub logowanie oznaczają akceptację regulaminu.
Jeśli jeszcze się z nim nie zapoznałeś to zapraszamy.</p>
<h2>DOŁĄCZ DO NAS</h2>
<p class="grey">Rejestrując się uzyskasz dostęp do szerokiej gamy polskich komiksów avatar the last airbender!</p>
</div>
<?php
if(!$_SESSION['id']):
?>
<div class="left">
<!-- Login Form -->
<form class="clearfix" action="" method="post">
<h1>Logowanie</h1>
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<label class="grey" for="username">Login:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Hasło:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Pamiętaj mnie</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Zaloguj" class="bt_login" />
</form>
</div>
<div class="left right">
<!-- Register Form -->
<form action="" method="post">
<h1>Jeszcze nie masz konta?!</h1>
<?php
if($_SESSION['msg']['reg-err'])
{
echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
unset($_SESSION['msg']['reg-err']);
}
if($_SESSION['msg']['reg-success'])
{
echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
unset($_SESSION['msg']['reg-success']);
}
?>
<label class="grey" for="username">Login:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label>Hasło zostanie Ci wysłane.</label>
<input type="submit" name="submit" value="Zarejestruj" class="bt_register" />
</form>
</div>
<?php
else:
?>
<div class="left">
<h1>Panel użytkownika</h1>
<p>Twoja subskrypcja wygasa <?php echo '???'; ?></p>
Wyloguj się
</div>
<div class="left right">
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Witaj <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Gościu';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Rozwiń panel':'Login | Reje';?></a>
<a id="close" style="display: none;" class="close" href="#">Zwiń panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div>
</body>
</html>
The problem is that here:
<li>Witaj <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Gościu';?>!</li>
user does not appear... i tried many ways to fix it and guess what?
everything works but after redirect to other page usr doesnt exists...
CHMOD 755. What's wrong with it?
As documented for session_name(), you MUST set the session name BEFORE you call session_start(). You are also changing the session cookie parameters AFTER session_start().
You cannot do this. session settings must be changed BEFORE you start the session.
I suspect that you working on the session before you've started it may be the problem.

Categories