How to use an existing Drupal 7 User Database With PHP - php

I am trying to get a php login working for a Drupal 7 database so that I can use an existing user database.
I am using the following html form:
<form id='login' action='http://www.example.com/login.php'
`method='post' accept-charset='UTF-8' class="login100-form validate-form
flex-sb flex-w">
<span class="">
<tr>
<td align="center">
<img border="0" src="../logoac.jpg" width="70%"></td>
</tr>
</span>
<div class="" data-
validate = "Username is required">
<input class="input" type="text" name="username"
placeholder="Username">
<span class="focus-input"></span>
</div>
<div class="wrap-input100 validate-input m-b-16" data-
validate = "Password is required">
<input class="input100" type="password" name="password"
placeholder="Password">
<span class="focus-input100"></span>
</div>
<div class="container-login100-form-btn m-t-17">
<button class="login100-form-btn">
Login
</button>
</form>
And login.php that the form triggers is:
<?
//set the working directory to your Drupal root
define("DRUPAL_ROOT", "/xxx/web/xxx");
//require the bootstrap include
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
/(loads everything, but doesn't render anything)
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$form_state = array();
$form_state['values']['name'] = $username;
$form_state['values']['pass'] = $password;
$form_state['values']['op'] = t('Log In');
drupal_form_submit('user_login', $form_state);
$form_state['rebuild'] = TRUE;
$_SESSION["UserID"] = $data["name"];
if($user->uid >0)
{
header('Location: http://www.example.com/otherpage.php');
}
else
{
header('Location: http://www.example.com/noaccount.php');
}
?>
This sort of works in that the user is logged in and redirected as above, but next time they visit how do I get them to automatically go to otherpage.php without having to login with the html form?
If they re-use the html form, they get caught up in some sort of Drupal automatic redirect to their Drupal user page for some reason rather than the redirects above working. I think this is because they are already logged in and there is an open session but I cant get this to work.
So:
1. How can I get the form above to over ride the existing session?
2. Or better still, how do I get otherpage.php to check if an existing session is open and let them in to the restricted area or redirect them back to the login form if they are not logged in?
Thanks

You need to check the function "drupal_form_submit" or re-write it to create your prescribed session . Drupal is very secure and create session / cookies which will re-direct a logged in user as you have mentioned . If you want a trick , then play here .

Related

How can I add two CSS types into an embedded HTML echo command and also perform a form validation technique?

Question one
How can I make my echo html paragraphs bold? here is what I tried below 'text-align:center,font-weight: bold'?
echo "<div style='text-align:center,font-weight: bold'><p>Hello ". $_SESSION['username entered']."please enter the correct username or password for this login page.</p></div>";
echo "<div style='text-align:center'><p>Hi, you left the form feilds blank, please your username/password.</p></div>";
Question two
When the user inputs a username such as "circle" into my form how can I get that random username the user entered and get it to display on the line of code echo "<div style='text-align:center,font-weight: bold'><p>Hello ". $_SESSION['username entered']."please enter the correct username or password for this login page.</p></div>"; If I use the variable username this will tell the user the actual correct username for the form which I don't want.
see how if I use "username" it will tell the user what the actual script user is? I want the original username they entered to be displayed for example, if I type in "hjhjhj" as the username where it says "test1" I want that random user to be displayed there please
PHP
<?php
session_start();
//Selectional statement
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = $_POST["username"];
$pass = $_POST["password"];
//login aspect
if($user != "" || $pass != ""){
if($user=="test1"&&$pass=="test1"){
$_SESSION['login'] = "OK";
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
header('Location: protected.php'); //Links with protected php file
}else{ //If this codition is met output the below
$_SESSION['login'] = "";
echo "<div style='text-align:center,font-weight: bold'><p>Hello ". $_SESSION['username entered']."please enter the correct username or password for this login page.</p></div>";
}
}else{
$_SESSION['login'] = "";
echo "<div style='text-align:center'><p>Hi, you left the form feilds blank, please your username/password.</p></div>";
}
}
?>
HTML
<!-- Form Input Part -->
<form class="text-center" method="post">
<div class="form-group w-50 mx-auto">
<!-- First Name input section -->
<label for="username">USERNAME:</label>
<input id="username" class="form-control" type="text" maxlength="15" name="username" placeholder="Input your username.">
</div>
<div class="form-group w-50 mx-auto">
<!-- Last Name input section -->
<label for="password">PASSWORD:</label>
<input type="password" class="form-control" type="text" maxlength="15" name="password" placeholder="Input your password.">
</div>
<!-- Form Button Submission -->
<button type="submit" class="btn btn-dark">
Login
<i class="fas fa-sign-in-alt"></i>
</button>
</form>
</div>
Thanks for the help in advance:)
Question 1:
As Phix suggested in the comments, simply change your inline style to
text-align:center;font-weight: bold
using the semicolon instead of the comma.
Question 2:
It depends on how much random do you want to have, but if it's not importand, change
$_SESSION['username entered'] to one of the following:
substr(md5(time()),0,7)
substr(md5(rand(0, 3000)),0,7)
substr(base64_encode(openssl_random_pseudo_bytes(40)),0,7)
"User".rand(0, 99999)
For example
echo "<div style='text-align:center,font-weight: bold'><p>Hello ". "User".rand(0, 99999).", please enter the correct username or password for this login page.</p></div>";

PHP - using variables across different files

PHP noob here. I'm trying to create a login file. Here's my code:
HTML:
<body>
<div class="login">
<h2 class="login-header">Log in</h2>
<form action="practice.php" method="POST" class="login-container">
<p>
<label>Username: </label>
<input type="text" id="user" name="user" placeholder="Enter Username" required/>
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass" placeholder="Enter Password" required/>
</p>
<p>
<input type="submit" id="btn" value="Login" />
</p>
</form>
</div>
PHP:
<?php
$usernameIn = $_POST['user'];
$passwordIn = $_POST['pass'];
$usernameIn = stripcslashes($usernameIn);
$passwordIn = stripcslashes($passwordIn);
$usernameIn = mysql_real_escape_string($usernameIn);
$passwordIn = mysql_real_escape_string($passwordIn);
$host = 'localhost';
$user = 'root';
$password = '';
$db ='practice';
$connection = mysqli_connect($host,$user,$password,$db);// you can select db separately as you did already
if($connection){
$ret = mysqli_query($connection,"SELECT `userName`, `password`, `clearacne` FROM
`users_table` WHERE `userName`='$usernameIn' AND `password`='$passwordIn'");
global $to_encode = array();
while($row = mysqli_fetch_assoc($ret)) {
$to_encode[] = $row;
}
//user doesn't exist redirect to error page
if(empty($to_encode)) header("Location: http://localhost/practiceLogin/loginErrorIndex.html");
//user exist continue
else{
$to_encode = json_encode($to_encode);
header("Location: http://localhost/practiceLogin/loginOkIndex.php");
}
}else{
echo "db connection error because of".mysqli_connect_error();
}
?>
Two questions:
1)Is there a way to process the info the user puts in and redirect him to a new file ONLY if the info exists in the database?
2)How can I pass the variable $to_encode from the practice.php to other .php files without including/requiring the practice.php file?
Basically what I'm trying to do is to not allow access if the user isn't registered, and if he is then allow access to another file and use a JSON object that represents different parameters associated with the user.
Thank you!
First question: You are already making redirects:
header("Location: http://localhost/practiceLogin/loginOkIndex.php");
Second question: Yes, there is a way. It is called session. You can read more here: http://php.net/manual/en/book.session.php
The basic explanation - once you check if username/password match you start a session, put some temp variables in it, a file has been written in your server's HDD and a cookie has been sent to your user's browser. Next time the user sends request to some of your pages, you check for the cookie, check if session is still active an not expired and you can get your temp variables from the session's file.
The heavy stuff is already written and automated. Just put some time on reading the link I gave you and also I am sure you will find many example resources over the Internet.

Make a form sticky with php session

I am trying to create php multipage forms, and I use PHP sessions for this purpose.
However, when there is an error in user input and I want the form to ask user to fill in the form again with correct inputs, the forms field will not hold the data that the user has already put in so the user has to start things all over again.
How to make forms sticky with php session?
Thanks
My code is as bellow
<?php
// Session starts here.
if (!isset($_SESSION)) session_start();
?>
<form action="registration.php" method="post">
<center><h8>Please create your user name and password</h8></center>
<div class="imgcontainer">
<img src="phone.gif" alt="Welcome" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required value="<?php if(isset($_POST['username'])) echo $_POST['username'];?>">
<label><b>Password</b></label>
<input type="Password" placeholder="Enter Password" name="password" required>
<label><b>Confirm Password</b></label>
<input type="Password" placeholder="Confirm Password" name="confirm" required>
<span id="error" width=100%>
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo "<error>".$_SESSION['error']."</error>";
unset($_SESSION['error']);
}
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
?>
</span>
<br>
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</div>
and the registration php contains
<?php
if (!isset($_SESSION)) session_start();
// Checking first page values for empty,If it finds any blank field then redirected to first page.
if (isset($_POST['username']))
{
if (($_POST['password']) === ($_POST['confirm']))
{
foreach ($_POST as $key => $value)
{
$_SESSION['post'][$key] = $value;
}
}
else
{
$_SESSION['error'] = "Password does not match with Confirm Password.";
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
header("location: createlogin.php"); //redirecting to first page
}
}
Something like this:
<input name="var" value="<?= isset($_SESSION['var']) ? $_SESSION['var'] : null ?>" />
Try the other way around. Linking the form-action to the current page, and if all fields are valid; redirect it to the next page (registration.php). This way you'd still have all the post-data, you can process everything that needs to be saved in the session- and you can redirect after all of the logic is done.
My two cent would be keep the same page to validate the content and for the form.
You can include other PHP files from a single page depending on if the form is valid.
This way, you keep the same $_POST between both pages and don't need to store the posted data in a session variable.
Otherwise, if you want to keep the same architecture, you need to use the $_SESSION variables instead of the $_POST ones in your input value, such as the answer by delboy.
Replace:
<?php if(isset($_POST['username'])) echo $_POST['username'];?>
With:
<?php if(isset($_SESSION['username'])) echo htmlspecialchars($_SESSION['username']); ?>
^ Note: htmlspecialchars is used to prevent a reflected XSS if the users enters " as username.
The problem is, your data posted to registration.php, so you can't get the posted value in your original file. You are trying to use $SESSION but that's not recommended, and not right. Your whole solution is wrong.
Forget about session and separated files, put everything to registration.php file together.
You can check if user posted or not with $_SERVER['REQUEST_METHOD'] variable.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print 'Something just posted';
}
PS: Don't forget secure the password before you store it! :)

Login submit OOP not working in bootstrap form

I have a bootstrap login form for an admin user that has a login submit button, but when I press it, nothing happens.
Here's the html form placed in a login form template loginForm.php
<form action="admin.php?action=login" method="post" style="width: 50%;">
<input type="hidden" name="login" value="true" />
<?php if ( isset( $results['errorMessage'] ) ) { ?>
<div class="errorMessage"><?php echo $results['errorMessage'] ?></div>
<?php } ?>
<div class="field-wrap">
<label for="username">
username<span class="req">*</span>
</label>
<input type="text" name="username" id="username" required/>
</div>
<div class="field-wrap">
<label for="password">
Password<span class="req">*</span>
</label>
<input type="password" name="password" id="password" required/>
</div>
<button type="submit" name="login" class="button button-block"/>Log In</button>
</form>
and here's the login() function in the admin.php which includes all the functions for the admin.
function login() {
$results = array();
$results['pageTitle'] = "Admin Login | Malang Foodies";
if ( isset( $_POST['login'] ) ) {
// User has posted the login form: attempt to log the user in
if ( $_POST['username'] == ADMIN_USERNAME && $_POST['password'] == ADMIN_PASSWORD ) {
// Login successful: Create a session and redirect to the admin homepage
$_SESSION['username'] = ADMIN_USERNAME;
header( "Location: admin.php" );
} else {
// Login failed: display an error message to the user
$results['errorMessage'] = "Incorrect username or password. Please try again.";
require( TEMPLATE_PATH . "/admin/loginForm.php" );
}
} else {
// User has not posted the login form yet: display the form
require( TEMPLATE_PATH . "/admin/loginForm.php" );
}
}
Well, to be clear, all the functions that include a submit button like addArticle(), editArticle() in the admin.php does not work anymore when I adapted the bootstrap template, because before adapting bootstrap all the functions work fine.
Any help is appreciated. Thanks in advance.
You have a spurious forward slash / character in the button markup, so effectively you've closed the button tag twice:
<button type="submit" name="login" class="button button-block"/>Log In</button>
because you have: <button.... /> (the spurious / character which closes some other tags, so it's probably throwing the browser completely). Delete that and it should work.
He does have an input "login". It's the first of the form and it's hidden.
Is ADMIN_USERNAME and ADMIN_PASSWORD defined somewhere?
Or are you sure you sure both password and username match the constants?
Hope this helps.
Are you sure that this is a PHP issue? Try putting a statement like die('here') somewhere in the checking of POST values. I suspect, because your form is a button, the form isn't actually submitting. You might want to check for javascript errors on the page.

Is a stale session stopping post variables being submitted

I have had this issue intermittently for some time, but I only just had it happen repeatedly enough to actually trouble shoot it. It happened repeatedly in FF but I have seen it in Chrome as well.
I have login form as below, it is very simple, email address and password and a submit button
<form method="post" action="login.php" id="valid" class="mainForm">
<fieldset>
<div class="">
<label for="req1">Email:</label>
<div class="loginInput"><input style="width: 100%;" type="text" name="email" class="validate" id="req1" /></div>
<div class="fix"></div>
</div>
<div class="">
<label for="req2">Password:</label>
<div class="loginInput"><input style="width: 100%;" type="password" name="password" class="validate" id="req2" /></div>
<div class="fix"></div>
</div>
<input name="action" type="hidden" value="log_in" />
<div class="">
<div class=""><input type="checkbox" id="check2" name="remember_me" value="1"/><label>Remember me</label></div>
<input type="submit" value="Log me in" class="submitForm" />
<div class="fix"></div>
</div>
</fieldset>
</form>
Submitting the above form wouldn't log me in, it just displayed the login form again as if nothing was submitted. So I amended the login.php file that is submitted to, and at the very top added print_r($_POST);
When I submitted the form again all it displayed was an empty array. It was like the form variables just weren't being sent. I tried several accounts, and got a blank array each time.
I then tried to enter an email address that I new wasn't in the database, and to my amazement the $_POST array populated with the fake email and password. I then tried a real account again and it was blank.
The last thing I did was to deleted the session cookie in FF for the site, and then try again. To my surprise I could then log in OK. I logged in and out a few times after that with no problem at all!
So my question is: What was that session cookie doing to prevent the post variables from being sent (if that was what was actually happening) and why did it populate the $_POST array if I entered a fake email address? The print_r($_POST) I did was the very first thing in the script, before any other processing or includes, yet it still was empty??
I guess I don't really know how browsers deal with session cookies, but this behaviour has me completely clueless.
Any advice on how to troubleshoot this, or general session advice.
EDIT - PHP Code for the login.php
<?php
print_r($_POST);
include '../inc/init.php';
$action = fRequest::get('action');
if ('log_out' == $action) {
fSession::destroy();
fAuthorization::destroyUserInfo();
fMessaging::create('success', '<center>You were successfully logged out</center>');
}
if (fAuthorization::checkAuthLevel('user') || fAuthorization::checkAuthLevel('buser')) {
fURL::redirect('index.php');
}
if ('log_in' == $action) {
# Set session variables etc...
}
The init.php include at the top sets the database connetion strings and starts the session etc... I am using FlourishLib Un-Framework set of classes which includes a session class.
Thanks
try this code please
$actions = array('log_in', 'log_out');
$action = fRequest::getValid('action', $actions);
if ($action == 'log_out') {
fSession::clear();
fAuthorization::destroyUserInfo();
fMessaging::create('success', URL_ROOT . 'index.php', 'You were successfully logged out');
fURL::redirect(URL_ROOT . 'index.php');
}
if ($action == 'log_in') {
if (fRequest::isPost()) {
try {
$valid_login = fRequest::get('username') == 'yourlogin';
$valid_pass = md5(fRequest::get('password')) == 'md5(youpassword)';
if (!$valid_login || !$valid_pass) {
throw new fValidationException('The login or password entered is invalid');
}
fAuthorization::setUserToken(fRequest::get('username'));
fURL::redirect(fAuthorization::getRequestedURL(TRUE, URL_ROOT . 'index.php'));
} catch (fExpectedException $e) {
fMessaging::create('error', fURL::get(), $e->getMessage());
}
}
include VIEWS_DIR . DS . basename(__FILE__);
}

Categories