PHP - using variables across different files - php

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.

Related

How to use an existing Drupal 7 User Database With 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 .

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! :)

How to make the website remember login, in order to prefill a input field? (PHP, MySQL)

EDIT: Problem fixed. I appreciate the replies I got, both for their help and the rapid response they was. The two answers I got was both rather identical, but I chose one of them to mark it as solved.
I have, for some time tried to get this to work but I can't and thus I am coming here, hoping for help.
I am currently trying to create a login, register and comment function on my website. Registering is working, logging in with those credentials also work, and I have got a filter to prevent empty-field entries.
Once I log in I have it echo out the possibility to go to the comment page, and my plan there is to allow the users to write a comment, see the comments below, and the author name will be grabbed from their login username. See where I am going? That is exactly what's not working, though. I can't get it to grab the username from the login field, and I am quite sure it has something to do with that the website doesn't remember the login, and I'm unsure how to set cookies and such if thats where the fix would be.
So, TL;DR - How do I get the website to remember a login, then insert it into a field?
Above the code is the website design itself, connection with the database, and session_start();.
Login.php code
<?php
if(!isset($_POST['submit_login'])) {
// Checks whether anyone have clicked the submit button, as long as they don't, show the form
echo '
<div class="loginform">
<h2>Please login to continue</h2>
<br />
<form action="login.php" method="POST">
Username : <input type="text" name="username_login"><br />
Password : <input type="password" name="password_login"><br />
<br />
<input type="submit" name="submit_login" value="Submit">
</form>
</div>
';
}
if(isset($_POST['submit_login'])) {
// Checks whether they have clicked on the submit button or not, if they have, check if the fields are filled or empty, as well as check it with the database.
$username_login = $_POST['username_login'];
$password_login = $_POST['password_login'];
$loginCmd = "SELECT * FROM tblUsers WHERE username='$username_login' AND password='$password_login'";
$result = mysql_query($loginCmd);
if(empty($username_login)) {
echo "<center>Wrong username.</center>";
}
else if (empty($password_login)) {
echo "<center>Wrong password.</center>";
}
else if (mysql_num_rows($result) == 0) {
echo "<center>User does not exist.</center>";
}
else {
mysql_query($loginCmd);
echo '<center>Logged in. Welcome '.$username_login.' !</center> <br />';
echo '<center>View/post comments here</center>';
}
Comments.php code
<div class="commentform">
<h2>View and post comments and thoughts here!</h2>
<p>All fields required</p><br /><br />
<form action="comments.php" method="POST">
Author : <input readonly type="text" name="author" value=''> <br /><br />
Comment : <textarea name="comment" class="insertcomment"></textarea><br />
<br />
<input type="submit" name="submit" value="Submit">
</form>
</div>
<br />
<hr>
<br />
<?php
if(isset($_POST['submit'])) {
// Checks if they have clicked on the submit button, if they have, send it to the database
$comment = $_POST['comment'];
$author = $_POST['author'];
$insertComment = "INSERT INTO tblComments(comments, author) VALUES ('$comment', '$author')";
if(empty($comment)) {
echo "<center>No text found in comment field.</center>";
}
else if(mysql_query($insertComment) ) {
echo "<center>Comment posted</center>";
}
}
Once you validate the login then you can store the username in a session array which is persistent between pages :
<?php
// this goes on top of the php page where ever you want to use session variable
session_start();
//once user login is valid then you can store username like this
$_SESSION["username"]=$username; //$username is what you used while validating the login
?>
On some other page you can get this value back as long as you have session_start on top:
<?php
//2 nd page
session_start();
echo $_SESSION["username"];//This will print username which you stored while logging
?>
For more information on sessions visit w3schools or php.net
You have two options to store the username between pages: Cookies, which are stored on the user's computer, or sessions, which are stored on your server. Consider sessions for any security-based authentication as cookies can be easily manipulated by your users.
Cookies:
$expiry_time = time() + 604800; // Expire in 7 days (time is in seconds)
setcookie("username", "administrator", $expiry_time); // set the cookie
echo $_COOKIE["username"]; // read the cookie
Sessions:
session_start();
$_SESSION["username"] = "administrator"; // set the session variable
echo $_SESSION["username"]; // read the session variable

setCookie in PHP script

I am working with a simple PHP script that I want to set a cookie on. I do not want this page to refresh. Currently, the page is where I go to upload pictures, and the page refreshes when the upload is done causing the upload to never go through.
<?php $password = "basicadminpassword";
setcookie('password', $password, time()+60*60*24*365, '/', '.myurl.com'); ?>
<?php
// If password is valid let the user get access
if (isset($_POST["password"]) && ($_POST["password"]=="$password")) {
?>
PROTECTED DATA
<?php } else { ?>
<div align="center">
You must have a password to upload pictures.<br /><br />
<form method="post">
<input name="password" placeholder="ADMIN PASSWORD..." type="password" size="25" maxlength="15"><input style="display:none;" value="go" type="submit">
</div>
</form>
<?php } ?>
After the user types in basicadminpassword we wont be asked for it again which will stop the refreshes from happening. If you know of a better way that would be great to hear also!
I don't know what you're doing but you shouldn't save your password plain in a cookie. For security reasons that not a really good idea. Compare the password and save in a session weather the user is logged in or not.
session_start();
$_SESSION['loggedOn'] = true;

Error with Admin login page in PHP and mySql

When i run this code everything seems to be fine... But when I login with the right username and password i get the following: That information is incorrect, try again Click Here I should be taken to the index.php file.
I also have echo the sql query and it gave me this Resource id #4
Can anyone spot the problem here.
Here is the PHP
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
include"db_connection.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' and password='$password' LIMIT 1");
$existCount = mysql_num_rows($sql);
if ($existCount ==1){
while($row = mysql_fetch_array($sql)){
$id=$row["id"];
}
$_SESSION["id"]=$id;
$_SESSION["manager"]=$manager;
$_SESSION["password"]=$password;
header("location:index.php");
exit();
}else{
echo'That information is incorrect, try again Click Here';
exit();
}
}
?>
Here is the HTML:
<html>
<head>
<title> Admin Login Page</title>
<head>
<body>
<div align="center" id="mainWrapper">
<div id="pageContent"><br/>
<div align="left" style="margin-left:24px;">
<h2> Please log in To manage the store</h2>
<form id="form1" name="form1" method="post" action="admin_login.php">
User Name: <br/>
<input name="username" type="text" id="username" size="40"/>
<br/></br>
Password: <br/>
<input name="password" type="password" id="password" size="40">
<br/>
<br/>
<br/>
<br/>
<br/>
<label>
<input type="submit" name="button" id="button" value="LogIn">
</label>
</form>
</body>
</html>
Look at your first two lines. You're using $_SESSION whereas the form submitted data will be in $_POST.
You have an extra curly brace, }.
As good practice, never build a query from unescaped strings (especially if they are stored in $_SESSION since they can be easily hijacked), never store a user's password in raw format in the database, and never save a raw password to the session. All these issues make your application very vulnerable and with great security risks which not only are subject for revealing users' sensitive data, but also can compromise your system. This being said, you should use mysql_real_escape_string() to escape user input when querying the database, you should encrypt your password with MD5/SHA/whatever (maybe add a salt too) and you should store only the user ID in the session because the other don't matter anyway.
Also, there is no reason to loop over the query results, since you are sure to have only one record returned.
Furthermore, I assume that the code you have posted is incomplete. Otherwise, your session variables won't work because you have not started a session with session_start(). Also, if you want to work with the username and password provided in the form, you must use $_POST["username"] and $_POST["password"], since this is how you grab the posted data, not by using sessions.

Categories