php authorization to two different databases that have different privileges - php

I need to authorize users to access two different databases:
DB01 and DB02.
Let's say that people who can access DB01 can also access DB02 but who can just access DB02 can't access DB01.
I've used form-guide code. This is the FORM code:
<!-- Form Code Start -->
<div id='fg_membersite'>
<form id='login' action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
<fieldset >
<legend><br/>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<div class='container'>
<label for='username' >UserName*:</label><br/>
<input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username') ?>' maxlength="50" />
<span id='login_username_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='password' >Password*:</label><br/>
<input type='password' name='password' id='password' maxlength="50" />
<span id='login_password_errorloc' class='error'></span>
</div>
<div class='short_explanation'>* required fields</div>
<br/>
<br/>
<div class='container'>
<input type='submit' style="font-family:'Courier'; font-size: 30px;" name='Submit' value='Submit' cursor='hand'/>
</div>
</fieldset>
</form>
<!-- client-side Form Validations:
Uses the excellent form validation script from JavaScript-coder.com-->
<script type='text/javascript'>
// <![CDATA[
var frmvalidator = new Validator("login");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("username","req","Please provide your username");
frmvalidator.addValidation("password","req","Please provide the password");
// ]]>
</script>
</div>
<!--
Form Code End (see html-form-guide.com for more info.)
-->
and this is the Login function inside fgmembersite.php:
function Login()
{
if(empty($_POST['username']))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($username,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $username;
return true;
}
function CheckLogin()
{
if(!isset($_SESSION)){ session_start(); }
$sessionvar = $this->GetLoginSessionVar();
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
I've used two different fgmembersite.php renaming everything so to be
fgmembersite for DB01 and fgmemebersite_db02 for DB02.
What happened at the moment is that if I authorize a user for DB02 the user is also authorized for DB01. I guess the problem is due to the $_SESSION.
I didn't rename it because I think it's not possible to have S_SESSION_DB02.
So when the user access the script and try to get access to DB01 the check on $_SESSION is already true because it was already authorized when he accessed DB02. So please can anybody help me on this to give the two different privileges but using the code available on form guide website?
http://form.guide/php-form/php-login-form.html
I

Related

Echo protected content after login

What I try to achieve
I need to create a administration-panel for a website. Therefore, I need a possibility to protect the content of the panel via a password. The functionality doesn't have to be very advanced. I neither need a password-reset functionality nor the possibility to add more than one user. I also don't need a "keep me logged in"-functionality.
It is also a pretty small site, so I don't think the security standards need to be as high as with big companies.
I can't use cookies for this project. It is for a completely "cookie-free" website.
Code
The basic code looks like this:
<?php
//Documentation: https://www.php.net/manual/de/function.password-hash.php
$username = '$2y$10$bWW0KD6P7WUaTU99PpcjtON1xKSBhCCxxiiyoaMuY0aVehZSfgVI6'; //result of password_hash("admin", PASSWORD_BCRYPT);
$password = '$2y$10$NxtrHFdZGZMG7y2G6l2o6eZpksOQfQvrQrCBTj7knEmL8VynQlcz2'; //result of password_hash("1234", PASSWORD_BCRYPT);
//Loading login form
$content = "<h1>Login</h1>
<form method='POST' class='input'>
<label>
<input type='text' name='username' placeholder='Username' class='validInput' required/>
</label>
<label>
<input type='password' name='password' placeholder='Password' class='validInput' required/>
</label>
<input type='submit' name='login' value='Login'/>
</form>";
//Check if form was submitted
if(isset($_POST['login'])) {
//Documentation: https://www.php.net/manual/de/function.password-verify.php
$verifyUsername = password_verify($_POST['username'], $username);
$verifyPassword = password_verify($_POST['password'], $password);
//Check if user entered correct username and password
if($verifyUsername && $verifyPassword) {
//Load protected content
$content = "<h1>Welcome</h1><p>Content here!</p>";
}
//Reload login form
else {
$content = "<h1>Login</h1>
<p>Wrong username or password!</p>
<form method='POST' class='input'>
<label>
<input type='text' name='username' placeholder='Username' class='validInput' required/>
</label>
<label>
<input type='password' name='password' placeholder='Password' class='validInput' required/>
</label>
<input type='submit' name='login' value='Login'/>
</form>";
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>John Doe</title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>
</head>
<body id='body'>
<?php echo $content; ?>
</body>
</html>
Questions
Is this a secure possibility for basic login? Is it secure to just echo the protected content once the user logged in? If not, what can I improve to make it secure? What else should I think of?
Is HTTP authentication a good and secure alternative for this task?
Edit in reply to the comment from Ro Achterberg:
It is protecting a content management system. A potential attacker would be able to change, delete or replace content.
It needs to keep out everyone apart from the website owner

only jpg jpeg and .... photos should be uploaded

I've been trying to solve this problem for several hours, but it didn't work.
The problem is:
I only want to upload photos such as jpg png, but when I upload photos with this type, I get the error message that should only be displayed if the type of uploaded data is wrong.
I wrote all the code, and I also wrote some parts of the code where the problem might be, sSo that everything is clear for you.
<?php
//msg for the first name,
$msg='';
//msg2 for the last name
$msg2='';
//msg3 for the email
$msg3='';
//msg4 for the date
$msg4='';
//msg5 for the password
$msg5='';
//msg6 for the re Password
$msg6='';
//msg7 for the image
$msg7='';
//msg8 for the checkbox
$msg8='';
$msg9='';
$msg10='';
$firstname='';$lastname='';$email='';$date='';$password='';$c_password='';$image='';
include("includes\header.php");
include("includes\config.php");
/**isset: checks if a variable is set, which means that it has to be declared and is not NULL */
if(isset($_POST['submit']))
{
//mysqli not mysql`enter code here
$firstname=mysqli_real_escape_string($con, $_POST['fname']);
$lastname=mysqli_real_escape_string($con, $_POST['lname']);
$email=mysqli_real_escape_string($con, $_POST['mail']);
$date=$_POST['dob'];
$password=$_POST['pass'];
$c_password=$_POST['cpass'];
$image=$_FILES['image']['tmp_name'];
$checkbox=isset($_POST['check']);
// this two line was for testin, if all this is ok
//echo $firstname. "<br>".$lastname."<br>"."<br>".$email."<br>". "<br>".$date."<br>". "<br>".$password."<br>"
//."<br>".$c_password."<br>"."<br>".$image."<br>"."<br>".$checkbox."<br>";
//strlen is to returns the length of the string(firstname)
if(strlen($firstname) <3)
{
// This message must be displayed if the number of letters of the given name is less than 3
$msg="<div class='error'>First name must contain atleast 3 characters</div>";
}
else if(strlen($lastname) <3)
{
// This message must be displayed if the number of letters of the given lastname is less than 3
$msg2="<div class='error'>Last name must contain atleast 3 characters</div>";
}
//filter_var: filters the email with FVE.
else if(!filter_var($email,FILTER_VALIDATE_EMAIL))
{
// This message must be displayed if the number of letters of the given lastname is less than 3
$msg3="<div class='error'>Enter Vaild Email</div>";
}
else if (empty($date))
{
$msg4="<div class='error'> Please Enter Your Date of Birth</div>";
}
else if (empty($password))
{
$msg5="<div class='error'> Please Enter Your Password </div>";
}
else if (strlen($password) <5)
{
$msg5="<div class='error'>Password must contain atleast 5 Character</div>" ;
}
else if ($password!==$c_password)
{
$msg6="<div class='error'> Password is not same </div>";
}
else if ($image=='')
{
$msg7="<div class='error'> Please Upload Your Profile Image </div>";
}
else if($checkbox=='')
{
$msg8="<div class='error'> Please Agree Our Termas an Conditions </div>";
}
else
{
$img_ext=explode(".",$image);
$image_ext=$img_ext['1'];
if($image_ext=='jpg' || $image_ext=='png' || $image_ext=='PNG' || $image_ext=='JPG' || $image_ext=='jpeg' || $image_ext=='JPEG' )
{
// to conection to the database and gives the values
mysqli_query($con, "INSERT INTO users(first_name,last_name,mail,password,dob,img)
VALUES ('$firstname', '$lastname','$email','$date','$password','$image')");
$msg9="<div class='success'> You are Successfully Registered </div>";
$firstname='';$lastname='';$email='';$date='';$password='';$c_password='';$image='';
}
else
{
$msg7="<div class='error'> Please Upload an Image File</div>";
}
}
// this slash is from the if sumbmit
}
?>
//this part of code is from body
</head>
<style>
</style>
<body>
<!-- container: to set the content's margins dealing with the responsive behaviors of the layout.-->
<div class='container'>
<div class='login-form col-md-4 offset-md-4'>
<!--jumbotron: ndicates a big box for calling extra attention to.-->
<div class='jumbotron' style='margin-top:40px; padding-top:20px; background-color:00FF00; font-size: 20px; width:450px'>
<h3 align='center'>SignUp</h3><br>
<?php echo $msg9;?><br>
<!-- form: to creat form for user input
method=”POST” Specifying a value of POST means the browser will send the data to the web server to be processed.
enctype: specifies how the form-data should be encoded when submitting it to the server:
-->
<form method='post' enctype="multipart/form-data">
<div class="form-group">
<label> First Name: </label>
<!-- 1name: the name of th input
2. placeholder: specifies a short hint that describes the expected value of a input field / textarea.
3. All textual <input>, <textarea>, and <select> elements with class .form-control have a width of 100%.
-->
<input type='text' name='fname' placeholder="First Name" class='form-control' value='<?php echo $firstname;?>'>
<!--IF the type of information provided is not the required one, this message will be displayed-->
<?php echo $msg;?>
<!--the end of the div of First Name-->
</div>
<!--start div of the Last Name-->
<div class="form-group">
<label> Last Name: </label>
<input type='text' name='lname' placeholder="Last Name" class='form-control' value='<?php echo $lastname;?>'>
<!--IF the type of information provided is not the required one, this message will be displayed-->
<?php echo $msg2;?>
<!--the end of the div of the Last Name-->
</div>
<!--start div of the Email-->
<div class="form-group">
<label> Email: </label>
<input type='email' name='mail' placeholder="Your Email" class='form-control' value='<?php echo $email;?>'>
<!--IF the type of information provided is not the required one, this message will be displayed-->
<?php echo $msg3;?>
<!--the end of the div of the Email-->
</div>
<!--start div of the birth day-->
<div class="form-group">
<label> Date of Birth: </label>
<input type='date' name='dob' value='<?php echo $date;?>'>
<?php echo $msg4; ?>
<!--the end of the div of birth day-->
</div>
<!--start div of the Password-->
<div class="form-group">
<label> Password: </label>
<input type='password' name='pass' placeholder="Password" class='form-control' value='<?php echo $password;?>'>
<?php echo $msg5;?>
<!--the end of the div of the Password-->
</div>
<!--start div of the Re-enter Password-->
<div class="form-group">
<label> Re-enter Password: </label>
<input type='password' name='cpass' placeholder="Re-enter Password" class='form-control' value='<?php echo $c_password;?>'>
<?php echo $msg6;?>
<!--the end of the div of the Re-enter Password-->
</div>
<!--start div of the image profile -->
<div class="form-group">
<label> Profile Image: </label>
<input type='file' name='image' value='<?php echo $image;?>'/><br>
<?php echo $msg7;?>
<?php echo $msg10;?>
<!--the end of the div of the image profile -->
</div>
<!--start div of the checkbox -->
<div class="form-group">
<input type='checkbox' name='check' />
I Agree the terms and conditions
<?php echo $msg8;?>
<!--the end of the div of the checkbox -->
</div>
<!-- submit button-->
<br><input type='submit' value='submit' name='submit' class='btn btn-success' style="background-color:blue;"><br>
<!--the end of the form for the sign up icon-->
</form>
<!--the end of the jumbtorn class-->
</div>
</div>
</div>
</body>
</html>
I have rewritten the part of the code here where the problem could be.
// this part is from php
else
{
$img_ext=explode(".",$image);
$image_ext=$img_ext['1'];
if($image_ext=='jpg' || $image_ext=='png' || $image_ext=='PNG' || $image_ext=='JPG' || $image_ext=='jpeg' || $image_ext=='JPEG' )
{
// to conection to the database and gives the values
mysqli_query($con, "INSERT INTO users(first_name,last_name,mail,password,dob,img)
VALUES ('$firstname', '$lastname','$email','$date','$password','$image')");
$msg9="<div class='success'> You are Successfully Registered </div>";
$firstname='';$lastname='';$email='';$date='';$password='';$c_password='';$image='';
}
else
{
$msg7="<div class='error'> Please Upload an Image File</div>";
}
}
This part is from body.
I have rewritten the part of the code here where the problem could be.
<!--start div of the image profile -->
<div class="form-group">
<label> Profile Image: </label>
<input type='file' name='image' value='<?php echo
$image;?>'/><br>
<?php echo $msg7;?>
<?php echo $msg10;?>
<!--the end of the div of the image profile -->
</div>
You can add to your input accept parameter:
<input type="file" name="myImage" accept="image/jpeg" />
When user choosing image he will see only JPG files in own file manager. I don't remember is that worked in every browser. In Chrome must work. In Safari maybe not.
Also you can check your file extention before send to server side. Just write custom validator like this (JS code):
var file = "test.mp4";
var valid = (file.substring(file.lastIndexOf("."), file.length)).toLowerCase();
if (valid != '.jpg') {
console.log("Please Select Valid Image");
} else {
console.log("Is valid image");
}

Can't access session on other pages by redirecting using header function?

Hi I am having trouble accessing session on other pages. I have done everything but can't solve it either. I start each page with session_start(). I have a form that gets username name and password and sends it to another page that saves this information in session array and redirects to the previous page but it seems like the session is not changed. It would be hard to help and understand without the code so here it is:
In my sigin.php,
<?php
session_start();
$_SESSION['errorMessage']='0';
include("header.html");
if($_SESSION['loggedin']){
print("<div class='pageContent'>
<h2>Sign in</h2>
<form method='POST' action='sign.php'>
<input type='text' maxlength='20' name='username' placeholder='Username'/ required><br/>
<input type='text' maxlength='30' name='password' placeholder='Password'/ required><br/>
<input type='submit' name='submit' value='Sign in' style='padding:0.5em;margin-left:45%;font-family:cursive,helvetica,Arial; color:darkred;cursor:pointer;'/>
</form>");
if($_SESSION['errorMessage']){
print("<div style='font-family:inherit' color:red' margin:1em;'>"
. $_SESSION['errorMessage'] . "</div>");
}
print("<div style='font-family:inherit;padding-
bottom:1.5em;margin:1em;'>
Don't have an account? <a href='' style='text-
decoration:none;'>Click here</a>
to sign up.
</div>
</div>");
}
else{
print("<div class='pageContent'>
<h2>You are logged in.</h2>
</div>
");
}
include("footer.html");
?>
and the page that handles the form input:
<?php
session_start();
if($_SESSION['username']==$_POST['username']&&$_SESSION['password']==$_POST['password'])
{
$_SESSION['loggedin']='true';
$_SESSION['errorMessage']='';
}
else{
$_SESSION['errprMessage']='The username and password combination is invalid!';
$_SESSION['loggedin']='false';
}
header("Location:signin.php");
exit();
?>
Please help me as I can't find any help on internet about this. Thanks...

Refresh page after alert box using AJAX in php

I'm doing a form validation in my php script, take one column as an example, if the username is not filled, an alert window will pop up and say "please enter your username", after user click "ok", the whole page refresh but the information on the form will be reset too.
So I would like to keep what the user has input after refreshing the page, how can I embed the code in php using AJAX?
//username validation
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
the website is in php file, html code is embedded under the php stuff, and this is the form in the html
<div id="account">
<form method="POST">
<p><span class="error">* required field.</span></p>
Username:
<input type="text" name="Username">
<span class="error">* </span><br>
<!--other fields..-->
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="signup_button">
</form>
</div>
<?php
if(isset($_POST['signup_button'])){
$Username = $_POST['Username'];
}
?>
or...
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
/* save the value in the browser */
echo 'window.'+VarYouWantToKeep = $_POST['VarYouWantToKeep'];
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
( or use localStorage, instead of window. https://developer.mozilla.org/en/docs/Web/API/Window/localStorage )
Then, when the page loads, check if('window.'+VarYouWantToKeep)
and if it's there, set it as the value="" of the corresponding form field
try this (This is taking into account you set $username to $_POST["Username"];)
<input type="text" name="Username" value="<?php if(isset($_POST["signup_button"]) && $_POST["signup_button"]=="Submit") {echo $username; ?>"
To store variable data, you will need to use $_SESSION variables in PHP. Make sure that session_start() is at the top of the PHP page.
Here's a basic example:
//this PHP page contains the HTML form
<form>
<input type="text" value="<?php echo $_SESSION['email']; ?>" />
</form>
//ajax
$.ajax({
url:'validate.php',
type:'POST',
data:{name:inputName}
}).done(function(data){
alert(data);
});
//php page
session_start();
if(!isset($_POST['name'])){
//set session variable
$_SESSION['email'] = $_POST['email'];
//this will be sent back to PHP page with HTML
echo 'Please enter username';
}
I coded here, a super cool login page with bootstrap as you expect. Link bootstarp cdn in your html file. This will show the error under the button instead of showing a windows classic alert box. I included ajax request and php response also with some validation.
login.html
<div class="container">
<div class="col-lg-offset-8 col-md-offset-6 col-lg-4 col-md-4 login-bg">
<form class="form-horizontal" role="form" action="#" method="">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="username" type="text" class="form-control" name="username" value="" placeholder="User Name" required tabindex="1" autocomplete="off">
</div>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<input id="password" type="password" class="form-control" name="password" value="" placeholder="Password" required tabindex="2" autocomplete="off">
</div>
<br>
<div class="form-group">
<div class="col-lg-6">
<button class="btn btn-primary-outline btn-block" type="submit" id="login">Login</button>
</div>
<div class="col-lg-6">
<button class="btn btn-success-outline btn-block" type="reset">Clear</button>
</div>
</div>
<br>
<div id="login-feedback" class="btn-block"></div>
</form>
</div>
</div>
myStyle.js
<script type="text/javascript">
$(document).ready(function()
{
$('#login').click(function()
{
var uname=$('#username').val();
var pword=$('#password').val();
if(uname!='' && pword!='')
{
$('#login-feedback').text('validating....');
$.post("login-check.php",{username:uname,password:pword},function(data)
{
if(data=="success")
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','green').fadeTo(1000,1,function()
{
document.location='index.php';
});
});
}
else
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','red').fadeTo(900,1);
//reset form
$('#login').trigger("reset");
});
}
});
return false;
}
else
{
$('#login-feedback').text("Please enter all fields").css('color','purple');
}
});
});
</script>
login-check.php
<?php
//include connextion file;
if(!isset($_SESSION))
session_start();
$username=trim($_POST['username']);
$password=$_POST['password'];
$username=mysqli_real_escape_string($con,$username);
$password=mysqli_real_escape_string($con,md5($password));
if(($username) && ($password))
{
$query = mysqli_query($con,"select * from login where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows>= 1)
{
$fetch_result = mysqli_fetch_array($query);
session_regenerate_id(true);
$_SESSION['username']=$fetch_result['username'];
$_SESSION['status']=$fetch_result['status'];
// Close session variable assigns
session_write_close();
echo "success";
}
else
{
echo 'Login failed';
}
mysqli_close($con);
}
?>

dynamically changing target of a form

I am trying to display my login inside an iframe which loads in the middle of the start page with gray backgroud, however i have a problem dealing with the target of the iframe, things should work as follows:
1- if user logged in successfully home page should load in the parent window
2- if error, error message should be displayed in the iframe itself.
my code:
<div id="cover5" onclick="javascript:cover5();">
<iframe name="warning" src="SignIn.php" id="warning" onclick="javascript:cover5();">
</iframe>
</div>
SignIn.php
<html>
<head>
<script type='text/javascript'>
function valid(){
if(document.getElementById('username').value.toString().length>=1 || document.getElementById('password').value.toString().length>=1){
return true;
}
else{
alert("The Combination of username and password are Incorrect !");
return false;
}
}
</script>
<script type='text/javascript'>
function ChangeTarget() {
document.getElementById("login").prop("target", "_parent")
}
</script>
<script type='text/javascript'>
function ChangeText(text) {
document.getElementById("label1").innerHTML= text;
}
</script>
<title></title>
</head>
<body>
<form name="login" id='login' target='_self' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>SignIn</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >Email:</label>
<input type='text' name='email' id='username' maxlength="50" /> <br />
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" /> <br />
<br /> <label id="label1" style="color: red"></label> <br />
<input type='submit' name='Submit' value='Login'/> <br />
<a href='resetPassword1.php'> Forgot/Reset Password? Click Here</a>
</fieldset>
</form>
however, the target is not changed by method ChangeTarget() which is called inisde php code, so the problem now is that everything load inside the iframe or everything inside the parent window. anyone knows how to solve the problem?
server side script:
mysql_select_db("mydb",$check);
$email = $_POST['email']; //username that will be submit from a form
$password = $_POST['password']; //password that will be submit from a form
// if(mysql_num_rows($temp_privileges_id)== 1) //if the id found that means that the user is already assigned to a conference
// {
echo '<script type="text/javascript">',
'ChangeTarget();',
'</script>';
header('Location: main.php'); // transefer to home page with variable username
}
There is no method prop. Either set the value of the target attribute directly
document.getElementById("login").target = "_parent";
or use setAttribute
document.getElementById("login").setAttribute("target", "_parent");
.prop() is a jQuery function. If you're going to do it in jQuery, do this:
$("#login").prop("target", "_parent");
If you're not going to do it in jQuery, do it like this in straight JavaScript:
document.getElementById("login").target = "_parent";

Categories