I am a novice to PHP. Now I am building a simple login-logout system. While trying to log in the system, I got the Internal Server Error with jquery.min.js:4. Here is my code:
Index:
<!-- Login Form -->
<form method="post" id="loginForm">
<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="#loginHeading" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="loginHeading">Login Form</h4>
</div>
<div class="modal-body">
<div id="loginMessage"></div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="pass">Password: </label>
<input type="password" id="pass" name="pass" class="form-control" required>
</div>
<div class="row">
<div class="checkbox" >
<div class="pull-left" style="padding-left:20px">
Forget password?
</div>
<label class="pull-right" style="padding-right:20px"><input type="checkbox" name="remember" value=""> Remember me</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success pull-left" data-dismiss="modal" data-toggle="modal" data-target="#signUp">Register</button>
<button type="submit" class="btn myBtn">Login</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Script:
$("#loginForm").submit(function(event) {
event.preventDefault();
var dataPost= $(this).serializeArray();
$.ajax({
url: '4-logIn.php',
type: 'POST',
data: dataPost,
success:function(data){
if (data == "success") {
window.location("mainPageLogin.php");
}
else {
$("#loginMessage").html(data);
}
},
error: function(data){
$('#loginMessage').html('<div class="alert alert-danger"><h5>Error in connection with loginForm</h5></div>');
}
});
});
4-login.php:
``
<?php
session_start();
include '0-connection.php';
$error='';
$email=filter_var($_POST["email"],FILTER_SANITIZE_EMAIL);
$pass=filter_var($_POST["pass"],FILTER_SANITIZE_STRING);
// Query
$email=mysqli_real_escape_string($link,$email);
$pass=mysqli_real_escape_string($link,$pass);
$pass=hash('sha256',$pass);
$sql="SELECT * FROM users WHERE email='$email' AND password='$pass' AND activation='activated'";
$result=mysqli_query($link, $sql);
if (!$result) {
echo "<div class='alert alert-danger'>Error running the query to take user login</div>";
exit;
}
$count= mysqli_num_rows($result);
if ($count !== 1) {
$error="<div class='alert alert-danger'><strong>ERROR:</strong> Wrong username or password. Please try again or Do you want to <a href='#' data-dismiss='modal' data-target='#signUp' data-toggle='modal'>Sign up</a></div>";
echo $error;
}
else {
// Set session
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id']=$row['user_id'];
$_SESSION['username']=$row['username'];
$_SESSION['email']=$row['email'];
// Check remember me Box
if (empty($_POST['remember'])) {
echo "success";
}
else {
}
}
?>
This is my error:
demonstration
web response
Please be more specific in your answer because I am very new in programming. Thanks for reading.
Error in 4-logIn.php, if (!result) { must be changed as if (!$result) {
Related
I don't know what I've done but I think I have some error in my ajax query. I am expecting to have been able to see the missing details not entered in the signup form. I get 500 server error and undefined $("#signupform") errors.
I have tried searching here and tried inserting various comments into my code to try and see if it helps. I have only been coding for 10 weeks so it's all new to me. I took an online course that promised the earth but has zero support whatsoever.
I think the error may be coming from the connection.php file I have not allowing the code to progress to check out my input fields in the table?
I have these pages hosted on a subdomain here is the link http://welcomer.offyoucode.co.uk/WEBSITES/9.Notes%20App/ in case its easier to figure it out from there.
<!--connect to the database-->
<?php
$link = mysqli_connect("#", "#", "#", "#");
if(mysqli_connect_error()){
die("ERROR: Unable to connect:" . mysqli_connect_error());
echo "<script>window.alert('Hi!')</script>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Online Notes</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="styling.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Arvo&display=swap" rel="stylesheet">
<style>
</style>
</head>
<body>
<!--navbar-->
<nav role="navigation" class="navbar navbar-custom navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand">Online Notes</a>
<button type="button" class="navbar-toggle" data-target="#navbarCollapse" data-toggle="collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="navbarCollapse">
<ul class="nav navbar-nav">
<li class="active">Home<span class="caret"></span></li>
<li>Help</li>
<!--<li>Sign-Up</li>-->
<li>Contact Us</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Login</li>
</ul>
</div>
</div>
</nav>
<!--jumbotron with signup button-->
<div class="jumbotron" id="myContainer">
<h1>Online Notes App</h1>
<p>Your notes with you, wherever you go.</p>
<p>Easy to use, protects all your notes!</p>
<button type="button" class="btn btn-lg green signup" data-target="#signupModal" data-toggle="modal">Sign up - Its free</button>
</div>
<!--login form-->
<form method="post" id="loginform">
<div class="modal" id="loginModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 id="myModalLabel">Login:</h4>
</div>
<div class="modal-body">
<!--login message from php file-->
<div id="loginmessage"></div>
<div class="form-group">
<label for="loginemail" class="sr-only">Email:</label>
<input class="form-control" type="email" name="loginemail" id="loginemail" placeholder="Email" maxlength="50">
</div>
<div class="form-group">
<label for="loginpassword" class="sr-only">Password</label>
<input class="form-control" type="password" name="loginpassword" id="loginpassword" placeholder="Password" maxlength="40">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="rememberme" id="rememberme">
Remember me
</label>
<a class="pull-right" style="cursor: pointer" data-dismiss="modal" data-target="#forgotpasswordModal" data-toggle="modal">
Forgot Password?
</a>
</div>
</div>
<div class="modal-footer">
<input class="btn green" name="login" type="submit" value="Login">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-default pull-left" data-dismiss="modal" data-target="signupModal" data-toggle="modal">Register</button>
</div>
</div>
</div>
</div>
</form>
<!--signup form-->
<form method="post" id="signupform">
<div class="modal" id="signupModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 id="myModalLabel">Sign up today and start using our Online Notes App! </h4>
</div>
<!--signup message from php file-->
<div id="signupmessage"></div>
<div class="modal-body">
<div class="form-group">
<label for="username" class="sr-only">Username:</label>
<input class="form-control" type="text" name="username" id="username" placeholder="Username" maxlength="35">
</div>
<div class="form-group">
<label for="email" class="sr-only">Email:</label>
<input class="form-control" type="email" name="email" id="email" placeholder="Email" maxlength="50">
</div>
<div class="form-group">
<label for="password" class="sr-only">Password:</label>
<input class="form-control" type="password" name="password" id="password" placeholder="Choose a password" maxlength="40">
</div>
<div class="form-group">
<label for="password2" class="sr-only">ConfirmPassword:</label>
<input class="form-control" type="password" name="password2" id="password2" placeholder="Confirm password" maxlength="40">
</div>
</div>
<div class="modal-footer">
<input class="btn green" name="signup" type="submit" value="Sign up">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</form>
<!--forgot password form-->
<form method="post" id="forgotpasswordForm">
<div class="modal" id="forgotpasswordModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 id="myModalLabel">Forgot Password? Enter your Email address:</h4>
</div>
<div class="modal-body">
<!--forgot password message from php file-->
<div id="forgotpasswordMessage"></div>
<div class="form-group">
<label for="forgotpasswordEmail" class="sr-only">Email:</label>
<input class="form-control" type="email" name="forgotpasswordEmail" id="forgotpasswordEmail" placeholder="Email" maxlength="50">
</div>
</div>
<div class="modal-footer">
<input class="btn green" name="login" type="submit" value="Login">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-default pull-left" data-dismiss="modal" data-target="signupModal" data-toggle="modal">Register</button>
</div>
</div>
</div>
</div>
</form>
<?php
include "footer.php";
?>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
//Ajax Call for the sign up form
//once the form is submitted
$("#signupform").submit(function(event){
//prevent default php processing
event.preventDefault();
//collect user inputs
var datatopost =
$(this).serializeArray();
console.log(datatopost);
//send them to signup.php using ajax
$.ajax({
url: "signup.php",
type: "POST",
data: datatopost,
success: function(data){
if(data){
$("#signupmessage").html(data);
}
},
error: function(){
$("#signupmessage").html("<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>");
},
});
// $.post({}).done().fail();
});
//ajax call successful: show error or success message
//ajax call fails: show ajax call error
//ajax call for the login form
//once the form is submitted
//prevent default php processing
//collect user inputs
//send them to login.php using ajax
//if php files return "success": redirect user to notes page
//otherwise show error message
//ajax call fails: show ajax call error
//ajax call for the forgot password form
//once the form is submitted
//prevent default php processing
//collect user inputs
//send them to login.php using ajax
//ajax call successful: show error or success message
//ajax call fails: show ajax call error
<?php
//<!--start session-->
session_start();
include("connection.php");
//<!--check user inputs-->
// <!--define error messages-->
$missingUsername='<p><strong>Please enter a username</strong></p>';
$missingEmail='<p><strong>Please enter an email address</strong></p>';
$invalidEmail='<p><strong>Please enter a valid email address</strong></p>';
$missingPassword='<p><strong>Please enter a password</strong></p>';
$invalidPassword='<p><strong>Your password should be at least 8 characters long and contain at least 1 capital letter and 1 number!</strong></p>';
$differentPassword='<p><strong>Passwords do not match! </strong></p>';
$missingPassword2='<p><strong>Please confirm your password</strong></p>';
$errors = "";
$username = "";
$email = "";
$password = "";
$myFile = "db.json";
$arr_data = array(); //create empty array
// <!--get username, email, password, password2-->
//get username
if(empty($_POST["username"])){
$errors .= $missingUsername;
}else{
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
}
//get email
if(empty($_POST(["email"]))){
$errors .= $missingEmail;
}else{
$email = filter_var($_POST["email"],
FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors .= $invalidEmail;
}
}
// get passwords
if(empty($_POST["password"])){
$errors .= $missingPassword;
}elseif(!(strlen($_POST["password"])>= 8 and preg_match('/[A-Z]/', $_POST["password"])and
preg_match('/[0-9]/', $_POST["password"])
)
){
$errors .= $invalidPassword;
}else{
$password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);
if(empty($_POST["password2"])){
$errors .= $missingPassword2;
}else{
$password2 = filter_var($_POST["password2"], FILTER_SANITIZE_STRING);
if($password !== $password2){
$errors .= $differentPassword;
}
}
}
// <!--if there are any errors print errors-->
if($errors){
$resultMessage = '' . $errors . '';
echo $resultMessage;
exit;
}
//<!--no errors-->
// <!--prepare variables for the query-->
$username = mysqli_real_escape_string($link, $username);
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$password = md5($password);
//128 bits -> 32 characters
// <!--if username exists in the table print error-->
$sql = "SELECT * FROM users WHERE username = '$username'";
mysqli_query($link, $sql);
if($!result){
echo '<div class="alert alert-danger">Error running the query!</div>';
// echo '<div class="alert alert-danger">' . mysqli_error($link) . '</div>';
exit;
}
$results = mysqli_num_rows($results);
if($results){
echo '<div class="alert alert-danger">That username is already in use. Do you want to log in?</div>'; exit;
}
// <!--else-->
// <!--if email exists in the users table print error-->
$sql = "SELECT * FROM users WHERE email = '$email'";
mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
$results = mysqli_num_rows($results);
if($results){
echo '<div class="alert alert-danger">That email is already in use. Do you want to log in?</div>'; exit;
}
// <!--else-->
// <!--create a unique activation code-->
$activationKey = bin2hex(openssl_random_pseudo_bytes(16));
//byte: unit of data = 8 bits
//bit: 0 or 1
//16 bytes = 16*8 = 128 bits
//2*2*2*2*2*2....*2
//16*16.......*16
//32 characters
// <!--insert user details and activation code in the users table-->
$sql = "INSERT INTO users ('username', 'email', 'password', 'activation') VALUES ('$username', '$email', '$password', '$activationKey')";
mysqli_query($link, $sql);
if(!$result){
echo '<div class="alert alert-danger">There was an error inserting the user details into the database</div>';exit;
}
// <!--send the user an email with a link to activate.php with their email and activation code-->
$message = "Please click on this link to activate your account:\n\n";
$message = "http://https://welcomer.offyoucode.co.uk/WEBSITES/9.Notes%20App/activate.php?email=" . urlencode($email) . "&key=$activationKey"; if(mail($email, 'Confirm your Registration', $message, 'From:'.'onlinenotes#gmail.com')){
echo '<div class="alert alert-success">Thank you for registering. A confirmation email address has been sent to $email. Please click on the activation link to activate your account.</div>';
}
?>
Solved! On line 34 in signup.php extra brackets around email input. Solved using ERROR_REPORTING(E_ALL); ini_set('display_errors', 1) to narrow down my fault.
Im having problem when implementing edit function where I can edit the role of the user
Here is the button that will open the modal
<button type="button" id="edit" name="edit" class="btn btn-outline-warning" data-id="'.$row["id"].'">EDIT</button>
Here is the modal code
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="">
<div class="form-group">
<label for="userName" class="col-form-label">Username:</label>
<input type="text" class="form-control border-danger" id="userName" readonly style="background-color: #2A3038">
</div>
<div class="form-group">
<label for="user_type" class="col-form-label">User Type:</label>
<select class="form-control border-success" id="user_type">
<option value="user">User</option>
<option value="contributor">Contributor</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<input type="hidden" id="user_id" name="user_id">
<button type="submit" id="update" name="update" class="btn btn-success">Update</button>
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Ajax
$(document).on('click', '#edit', function(){
var user_id = $(this).attr("data-id");
$.ajax({
url:"/auth/action",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#editModal').modal('show');
$('#userName').val(data.userName);
$('#user_type').val(data.user_type);
$('#user_id').val(user_id);
}
})
});
PHP where the action happens
if($_POST["action"] == 'update')
{
$query = 'UPDATE `users` SET username = :username, user_type = :user_type WHERE id = :id';
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $_POST['user_id'],
':username' => $_POST['userName'],
':user_type' => $_POST['user_type']
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo '<div class="alert alert-fill-warning" role="alert">User type changed!<div>';
}
}
and also I have a function for fetch which I named it load_user_data()
Here is the for the datatype json
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connect->prepare(
"SELECT * FROM users WHERE id = '".$_POST["user_id"]."' LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["userName"] = $row["username"];
$output["user_type"] = $row["user_type"];
}
echo json_encode($output);
}
The problem Im having is that the PHP action code is not working or is there anything wrong with my code? but I dont have probelm with displaying the data in the modal except if i submit the change there is no function happening
Your ajax data property is missing a lot of parametars:
....ajax....
data: {user_id: user_id, userName: username here,user_type:set type here, action: 'update'}
You need to add edit id to your update button
Also you need to add userdata to your ajax response, currently you are using data.userName etc. but you didnt put that in the response
You can find more info on how to properly return json response here:
Returning JSON from a PHP Script
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="">
<div class="appenddata">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="update" name="update" class="btn btn-success">Update</button>
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).on('click', '#edit', function(){
$('#editModal').modal('show');
var user_id = $(this).attr("data-id");
$.ajax({
url:"/auth/action",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
$(".appenddata)".html(data);
}
})
});
</script>
<?php
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connect->prepare(
"SELECT * FROM users WHERE id = '".$_POST["user_id"]."' LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
$user_array=array("user","contributor");
?>
<input type="hidden" id="user_id" name="user_id" value="<?= $_POST["user_id"]; ?>">
<div class="form-group">
<label for="userName" class="col-form-label">Username:</label>
<input type="text" class="form-control border-danger" id="userName" value="<?= $result[0]['username']; ?>" readonly style="background-color: #2A3038">
</div>
<div class="form-group">
<label for="user_type" class="col-form-label">User Type:</label>
<select class="form-control border-success" id="user_type">
<?php
if($user_array!=NULL)
{
foreach($user_array as $data)
{
if($data==$result[0]['username'])
{
$selected='selected="selected"';
}
else
{
$selected='';
}
?>
<option value="<?= $data; ?>"><?= ucwords($data); ?></option>
<?php
}
}
?>
</select>
</div>
<?php
}
So my purpose is to get the ID from a database and making the id ready to be used for modal. I know that I can use input type=hidden but I don't know for sure it is safe because in inspect element, user can edit it. I'm thinking also of session but I don't have any idea how can I do it. So what are the ways I can do to make the id not editable after submitting? Or how can i put it in array and match the id? Here is my code I used
class.names.php
public function getAllNames()
{
$obj = new Db();
$stmt = $obj->connect()->query("SELECT * FROM persons");
while ($person = $stmt->fetch())
{
echo "<tr>";
echo "<td>".$person['first_name']."</td>";
echo "<td>".$person['last_name']."</td>";
echo "<td><a id=\"".$person['person_id']."\"type=\"button\" data-target-toggle=\"modal\" data-target=\"#edit-name-modal\" class=\"btn btn-danger edit_data\" href=\"#\">Update</a></td>";
echo "</tr>";
}
}
names.js
$(document).on('click', '.edit_data', function(){
var person_id = $(this).attr("id");
$.ajax({
url:"/data/updatename.php",
method:"POST",
data:{person_id:person_id},
dataType:"json",
success:function(data){
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#person_id').val(data.person_id);
$('#edit-name-modal').modal('show');
}
});
});
updatename.php
<?php
include_once 'db.php';
if(isset($_POST["person_id"]))
{
$person_id = $_POST["person_id"];
$object = new Dbc();
$stmt = $object->connect()->prepare("SELECT * FROM persons WHERE person_id=?");
$stmt->execute([$person_id]);
$profile_info = $stmt->fetch();
echo json_encode($profile_info);
}
?>
namelist.php
<div class="modal fade" id="edit-name-modal" name="edit-name" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="POST" enctype="multipart/form-data" action="namelist.php">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update Name's List</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>First Name</label>
<input type="text" id="first_name" name="first_name" class="form-control">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" id="last_name" name="last_name" class="form-control">
</div>
<input type="hidden" id="person_id" name="person_id">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" name="update" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>
I want to write log in code for my index.html ' s form and i wrote a giris-yap.php file which is at below. i cant access my php file browser get alert only like localhost is waiting .
i tried to put action method in my form's submit button but it was not usefull.
giris-yap.php
<?php
require "connect.inc.php";
require "core.inc.php";
if(isset($_POST['exampleInputEmail1']) && isset($_POST['exampleInputPassword1']) ){
$mail=$_POST['exampleInputEmail1'];
$pass=$_POST['exampleInputPassword1'];
$password=md5($pass);
if($query_run=mysql_query("SELECT * FROM `users` WHERE `e-mail`= '".mysql_real_escape_string($mail)."' AND `sifre`='".mysql_real_escape_string($password)." ' ")){
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows==0){
echo 'Invalid';
}
else if($query_num_rows!=0){
$ad=mysql_result($query_run,0,'Ad');
$_SESSION['ad']=$ad;
$usersurname=mysql_result($query_run,0,'SoyAd');
$_SESSION['usersurname']=$usersurname;
$username=mysql_result($query_run,0,'e-mail');
$_SESSION['username']=$username;
header('Location: index.html');
}
}
else{
echo mysql_error();
}
}
else{echo 'error';}
/**
* Created by PhpStorm.
* User: bilsay
* Date: 21.05.2015
* Time: 10:35
*/
?>
index.html :
<div class="modal fade" id="login-modal-box" role="dialog" aria-labelledby="gridSystemModalLabel" aria-hidden="true">
<form action="#giris-kontrol" method="POST">
<div class="modal-dialog user-login-box-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Kullanıcı Giriş Paneli</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Eposta Adresiniz</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Şifre</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Beni hatırla
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" value="Giriş">Giriş</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
cant access my php file
You need to update your action as described in the other answer: https://stackoverflow.com/a/30377560/482256.
Then, note that this code here:
require connect.inc.php;
require core.inc.php;
Is the equivalent of doing this:
require 'connectincphp';
require 'coreincphp';
When you don't use quotes, PHP looks for constants, and when it doesn't find those it will assume the string, so connect becomes "connect". The period concatenates, so it combines "connect" with "inc" and you get "connectinc", etc.
The require should be causing a 500 error...and possibly an empty page depending on what your error output settings are.
Your code translated to PDO and BCrypt, because I just can't "fix" code and leave it insecure:
if(isset($_POST['exampleInputEmail1']) && isset($_POST['exampleInputPassword1']) ){
$pdo = new \PDO('mysql:dbname=dbName;host=localhost','username','password');
$mail = $_POST['exampleInputEmail1'];
$pass = $_POST['exampleInputPassword1'];
$userSql = $pdo->prepare("SELECT * FROM `users` WHERE `e-mail`=:email");
$userSql->execute(array('email'=>$mail));
$userData = $userSql->fetch(\PDO::FETCH_ASSOC);
if( $userData !== false && BCrypt::isValidPassword($pass, $userData['sifre']) ) {
$_SESSION['ad'] = $userData;
$_SESSION['usersurname'] = $userData['SoyAd'];
$_SESSION['username'] = $userData['username'];
header('Location: index.html');
}
else {
die("You have entered an invalid username or password");
}
}
else{
die("Username and Password must be submitted");
}
And your modified HTML. I fixed the action, turned your button into a real submit button, and added the name= attributes to your inputs:
<div class="modal fade" id="login-modal-box" role="dialog" aria-labelledby="gridSystemModalLabel" aria-hidden="true">
<form action="giris-yap.php" method="POST">
<div class="modal-dialog user-login-box-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Kullanıcı Giriş Paneli</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Eposta Adresiniz</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Şifre</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="exampleInputPassword1" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Beni hatırla
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" value="1" class="btn btn-primary" id="submit"> Giriş Yap</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
And the BCrypt class you will need. However, use password_hash and password_verify if you have PHP >= 5.5.
class BCrypt {
public static function hash( $password, $cost=12 ) {
$base64 = base64_encode(openssl_random_pseudo_bytes(17));
$salt = str_replace('+','.',substr($base64,0,22));
$cost = str_pad($cost,2,'0',STR_PAD_LEFT);
$algo = version_compare(phpversion(),'5.3.7') >= 0 ? '2y' : '2a';
$prefix = "\${$algo}\${$cost}\${$salt}";
return crypt($password, $prefix);
}
public static function isValidPassword( $password, $storedHash ) {
$newHash = crypt( $password, $storedHash );
return self::areHashesEqual($newHash,$storedHash);
}
private static function areHashesEqual( $hash1, $hash2 ) {
$length1 = strlen($hash1);
$length2 = strlen($hash2);
$diff = $length1 ^ $length2;
for($i = 0; $i < $length1 && $i < $length2; $i++) {
$diff |= ord($hash1[$i]) ^ ord($hash2[$i]);
}
return $diff === 0;
}
}
change action..
<form action="giris-yap.php" method="POST">
then change a link in your modal-footer
<button type="submit" value="Giriş Yap" class="btn btn-primary" id="submit" />
Having some problems with the error handling of a bootstrap modal. In the modal I have two inputs (both are required). I want to be able to display a simple "required" message if the form is submitted without one of the fields populated.
I tried doing this with PHP and it works in a page by itself, but when I put it in a modal the modal closes on submit and then if you re-open the modal you see the error messages. I really want the modal to stay open or re-open if the input fields are not valid when the user submits.
Any help would be appreciated! Thanks!
HTML (Start of the modal):
<div class="modal fade" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add a vCenter</h4>
</div>
<div class="modal-body">
PHP (To graph the input and report any errors):
if ( !empty($_POST)) {
// keep track validation errors
$vcenternameError = null;
$vcenterownerError = null;
// keep track post values
$vcentername = $_POST['vcentername'];
$vcenterowner = $_POST['vcenterowner'];
// validate input
$valid = true;
if (empty($vcentername)) {
$vcenternameError = 'Please enter vCenter Name';
$valid = false;
}
if (empty($vcenterowner)) {
$vcenterownerError = 'Please select vCenter Owner';
$valid = false;
}
// insert data
if ($valid) {
$sql = "INSERT INTO ";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
header("Location: index.php");
}
}
?>
HTML (the rest of the modal):
<div class="panel-body">
<form class="form-horizontal" action="index.php" method="post">
<div class="<?php echo !empty($vcenternameError)?'error':'';?> form-group">
<div class="alert alert-warning">
Please input the FQDN of the vCenter and select an owner.
</div>
<label class="control-label">vCenter Name</label>
<div class="controls">
<input name="vcentername" type="text" placeholder="vCenter Name" value="<?php echo !empty($vcentername)?$vcentername:'';?>" class="form-control">
<?php if (!empty($vcenternameError)): ?>
<div class="alert alert-warning alert-dismissable">
<?php echo $vcenternameError;?>
</div>
<?php endif; ?>
</div>
</div>
<div class="<?php echo !empty($vcenterownerError)?'error':'';?> form-group">
<label class="control-label">vCenter Owner</label>
<div class="controls">
<div class="btn-group" data-toggle="button" role="group" aria-label="...">
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team1"> Team1
</label>
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team2"> Team2
</label>
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team3"> Team3
</label>
</div>
<?php if (!empty($vcenterownerError)): ?>
<div class="alert alert-warning alert-dismissable">
<?php echo $vcenterownerError;?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button type="submit" class="btn btn-success">Add</button>
<a class="btn btn-default" href="index.php">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
You can use jQuery to open the modal again if the modal contains errors when the page loads:
var modal = $('#createModal');
if(modal.find('div.alert-warning').length)
modal.modal();
But for the best user experience, you should call your PHP script with an ajax request: http://api.jquery.com/jquery.ajax/