This question already has answers here:
When do I have to declare session_start();?
(2 answers)
Closed 1 year ago.
I did the register part and everything went well. I have reached the part where the user must log in to the site. The problem is that if I enter the wrong data in the login page, I get a message that the data is wrong.
But if I add the correct data for login, it redirects me to index.php, but the header does not change. Normally instead of the login and registration button, something like this should appear: Hi, Andrew. And a logout button.
Index header with login and register buttons
<?php
if(isset($_SESSION['id'])){
echo "<a href='login.html' class='login-panel'><i class='fa fa-user'></i>Salut, $_SESSION[name]. </a>
<button type='button' class='btn btn-light'>Logout</button>";
}
else {
echo " <a href='login.html' class='login-panel'><i class='fa fa-user'></i>Login</a>
<a href='inregistrare.html' class='login-panel'><i class='fa fa-user-plus'></i>Înregistrare</a>";
}
?>
Login form from login.php
<form method="post" action="login.php">
<div class="form-group">
<label for="email">* Adresa de e-mail:</label>
<input type="text" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password">* Parola:</label>
<input type="password" id="password" name="password" class="form-control" required>>
</div>
<div class="form-group gi-check">
<div class="gi-more">
<label for="save-pass">
Salvează parola
<input type="checkbox" id="save-pass">
<span class="checkmark"></span>
</label>
Ai uitat parola?
</div>
</div>
<div class="form-group">
<button type="login" name="login" class="site-btn login-btn">Intră în cont!</button>
</div>
</form>
login.php
session_start();
include('config.php');
// Cod pentru logare
if(isset($_POST['login']))
{
$password=$_POST['password'];
$dec_password=$password;
$email=$_POST['email'];
$ret= mysqli_query($con,"SELECT * FROM utilizatori WHERE email='$email' and password='$dec_password'");
$num=mysqli_fetch_array($ret);
if($num>0)
{
$extra="index.php";
$_SESSION['login']=$_POST['email'];
$_SESSION['id']=$num['id'];
$_SESSION['name']=$num['nume'];
$host=$_SERVER['HTTP_HOST'];
$uri=rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
header("location:http://$host$uri/$extra");
exit();
}
else
{
echo "<script>alert('Nume sau parola invalide!');</script>";
$extra="index.php";
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']),'/\\');
exit();
}
}
?>```
Kindly check that have you manage exception if condition not satisfied. also if you enter wrong data and once you logout you have to update code for session_destroy() . other wise same session has be called next time as well. I hope it will help to you.
I am creating a user registration form and i want to show a loading/progress on my page as soon user click submit button. Here Is my code please suggest me something to achieve this. here below is process.php file
if(isset($username)){
$con = new dbConnection();
$con->connect();
$con->add_user($username,$email,$password,$contact);
$db_class = 'ui success message';
$db_message_header = 'header';
$db_header_message = 'Your user registration was successful.';
$db_msg= 'You may now log-in with the username you have chosen';
$form_load = 'loading'; //Class for adding loading class
sleep(4);
header('location:index2.php');
}
Here is index.php
<form class="ui form attached fluid segment <?php echo $form_load; ?>" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="form">
<div class="field">
<label>Username <span id="err">*</span></label>
<input placeholder="Username Name" type="text" name="username" class="ui input success" value="<?php if(isset($username)){echo $username;} ?>" required>
</div>
<input type="submit" name="submit">Submit</input>
</form>
when user write her email for Newsletters, i want to show them a suuccess message
newsletter.php
<?php
$templates="templates/";
require_once 'includes/init.inc.php';
//require_once 'includes/classes/email.php';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (($result=mail::add_newsletter($_REQUEST['email'])) >0) {
Util::Redirect("index.php");
} else {
echo 'you register befor';
}
}
?>
footer.php
<form action="newsletter.php" method="post" class="searchform" >
<input type="text" placeholder=" type your email" name="email" />
<button type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p >come on with us to know everything for us</p>
</form>
Use session to store success message, and you can print it after redirect.
So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.
How would I do this through PHP? Here's the corresponding code
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
exit($e->getMessage());
}
// Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
// Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
echo "Complete all fields";
}
// Password match
if ($password != $password1) {
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
And my HTML form
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
So if the input satisfies the if statement how would I display the color?
When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like
$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
//run your form logic
//if you have success, run your php query and then redirect
//to your "success" page using a 302 (using a header("Location:... sort of call)
//you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form
With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.
Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.
When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
</div>
<div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
</div>
<div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
I would recommend using a templating engine or something to separate the view from the actual code.
As for the help text, you can use something like this after the elements with errors:
<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
<input type="text" class="form-control" />
<span class="help-block"><?php echo $yourVariable; ?></span>
</div>
The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.
EDIT
Example page: http://content.kevincuzner.com/register.php
Example source: https://gist.github.com/kcuzner/11323907
I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.
The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:
echo "Complete all fields";
$fieldsValid = false;
border-color: <?php $fieldsValid ? 'blue' : 'red' ?>
But you need to do a full page reload for this to work. JavaScript is a better route:
document.forms[0].addEventListener("submit", function () {
var usernameInput = document.querySelector("[name=username]");
if (!usernameInput.value) {
usernameInput.style.borderColor = "red";
}
});
I have been stuck on this problem for two days now. I've found the code to post data without refresh but it seems that if it doesn't refresh, the values aren't actually saved to the $_SESSION superglobal.
my jquery code:
$('.login_error').hide();
$('#sublogin').click(function(){
$('.login_error').hide();
var jusername = $('#loginusername').val();
var jpassword = $('#loginpassword').val();
if(jusername == ""){
$('label#username_error').show();
//return false;
}
if(jpassword == ""){
$('label#password_error').show();
return false;
}
var dataString = 'loginusername='+jusername+'&loginpassword='+jpassword;
$.post('login.php', dataString, function(data) {
$('#header').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500)
});
// return false
});
My login.php code:
<?php
//set the variables
$username = isset($_POST['loginusername'])? $_POST['loginusername']:'';
$password = isset($_POST['loginpassword'])? $_POST['loginpassword']:'';
$step = isset($_POST['step']) ? $_POST['step'] : '1';
if($step=='2'){
//validation is done in javascript
//if there are no errors
if(empty($loginErrors)){
//sanitizes data for use in query.
$username = trim(mysql_real_escape_string($username));
$password = md5(trim(mysql_real_escape_string($password)));
$query = "SELECT user_level, username, password FROM user WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die('query did not go through');
if($result!=false){
$query_row = mysql_fetch_assoc($result);
$_SESSION['user_level']=$query_row['user_level'];
$_SESSION['username']=$query_row['username'];
$_SESSION['password']=$query_row['password'];
}
}
}
if($step=='1'){
?>
<form class="login_fields" id="login_fields" name="login" method="POST">
<input type="hidden" name="step" value="2"/>
<div class="dtable">
<div class="dtr">
<span class="dtd">
<label name="name_label" for="username_box"> Username </label>
</span>
<span class="dtd">
<input type="text" id="loginusername" name="loginusername" maxlength="25" value=""/>
</span>
<span class="tdt">
<label for="username" id="username_error" class="login_error">Username field can not be blank</label>
</span>
</div>
<div class="dtr">
<span class="dtd">
<label name="pass_label" for="username_box"> Password </label>
</span>
<span class="dtd">
<input type="password" id="loginpassword" name="loginpassword" maxlength="20" value=""/>
</span>
<span class="tdt">
<label for="password" id="password_error" class="login_error">Password field can not be blank</label>
</span>
</div>
<div class="dtr">
<span class="dtd">
<input type="submit" name="sublogin" id="sublogin" value="login"/>
</span>
</div>
</div>
<div class="output" id="output" name="output">
</div>
</form>
<?php
}
?>
Edit: Ah yes I forgot to mention.
login.php is included in my headers file and my headers file is included in my index.php file so the session_start should cascade.
Edit 2: So if I set the return to false near the last line of the jquery code the page doesn't reload which is exactly what I want but the session isn't saved at all. Anyone able to figure out whats wrong with what I'm doing?
You should declare session_start(); at the top of your PHP script, otherwise the SESSION data won't be remembered!!