how to restrict access to certain pages on my website - php

my website is http://setch.me
I have a page that I use to add new entries to the artists table, how do I set a simple username/password to this page with normal php(no framework)?
I've looked it up and I found similar questions but none of them is using php only

It's simply you just need to create a form
<form action="" method="post">
<input type="text" name="user"/>
<input type="password" name="pass"/>
</form>
And submit data and compare it with your private username and password
example
<?php
if(isset($_POST["submit"])) {
// Here you put you own login data you can use mysql to get it
$username = "admin";
$password = "admin";
$username_post = htmlspecialchars($_POST["user"]);
$password_post = htmlspecialchars($_POST["pass"]);
if(($username_post == $username) && ($password_post == $password)) {
session_start();
$_SESSION["admin"] = $username;
}
}
?>
and put this code in page that you want to add new entries
<?php
session_start();
if(empty($_SESSION["admin"])) {die();}
?>

Php-login comes with three versions. The first one (One-file version) maybe is what you are looking for.

Related

Logins error using sessions in php

I am using this script for my login system in php, while am handling the session values it is not working
Case is when am not validating the session values in the test page which are passed from index page the login is valid and goes to the test page after successful login but when am using the session values to validate in the test page the login is not successful, after entering the credentials the page does not goes to test.php it stays only on index.php
Can i know what is the mistake i have done ? Thanks in advance
Login Page
<?php
require 'connection.php';
error_reporting(0);
$employee_id = $connection->real_escape_string($_POST['EMPLOYEE_ID']);
$password = $connection->real_escape_string($_POST['PASSWORD']);
$sql = "SELECT EMPLOYEE_ID,EMP_NAME,DESG FROM EMPLOYEELOGIN WHERE EMPLOYEE_ID='" . $employee_id . "' AND PASSWORD='" . $password . "'";
$result = $connection->query($sql);
session_start();
if ($result->num_rows == 1) {
$row = $result->fetch_row();
// print_r($row);
$_SESSION['EMPLOYEE_ID'] = $row[0];
$_SESSION['EMPNAME'] = $row[1];
$_SESSION['DESG'] = $row[2];
header('Location: test.php');
}
?>
// The form used
<form role="form" method="post" action='index.php' class="m-t-20">
<input class="form-control" type="text" name="EMPLOYEE_ID" required="" placeholder="Username">
<input class="form-control" type="password" name="PASSWORD" required="" placeholder="Password">
<input type="submit" class="btn btn-primary" name="submit" value="Login">
</form>
Test Page
<?php
session_start();
// error_reporting(0);
if (isset($_SESSION['EMPLOYEE_ID'])) {
if ($_SESSION['EMP_NAME'] != 1) {
header("Location: index.php");
} else {
require 'connection.php';
}
} else {
header("Location: index.php");
}
?>
connection.php
<?php
$connection = new mysqli("localhost","root","123","testdatabase");
if($connection->connect_error){
die("Connection Failed<br>".$connection->connect_error);
}
?>
Updated Answer based on new connection.php code::
You do not appear to have a mysqli class included in the code anywhere so your attempt to instantiate will fail, you should be getting a white page or an error of some sort depending on your php.ini configurations. In any of the code I assume you do not have that class. If thats the case you need to convert your code over to use mysqli_ functions directly or create/install a mysqli class. Direct functions you would use like this:
$conn = mysqli_connect // etc...
-------------- Previous Answer --------------
PASSWORD is a reserved word in mysql
PASSWORD=
Should be (note the backticks)
`PASSWORD`=
Or better yet, change the name of the column to something like user_password, pass or anything you want.
I believe that will solve the problem.
There is a full list of reserved words for mysql available here:
Mysql Keywords/Reserved Words List

Login with PHP doesn´t show any html code

I´ve a problem a login, the page doesn´t show anything. This is the code:
PHP:
<?php
require 'connect_db.php';
/* start the session */
session_start();
conectar();
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM teachers WHERE email='$email' and password='$password'";
$result = mysql_query($sql);
// counting table row
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['loggedin'] = true;
$_SESSION['email'] = $email;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (10 * 60) ;
echo "<body><p>Welcome! </p></body>";
}
else
{
echo "Mail or password not correct.";
echo "<a href='teacher.html'>Try again</a>";
}
//$conexion->close();
?>
The HTML calling this code is:
<form action= "php/login_profesores.php" method="POST" onsubmit="return validacion()">
<label>Mail</label>
<input type="text" class="" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" id="inputDNI"></input></br>
<input name="Enviar" type="submit" class="submit" value="Send" /></input></br>
</form>
validación() is the javascript code what works, but the problem is that php doesn´t show any page when the user logins in the system. The DB is well-configured and teacher´s table exists.
connect_db
<?php
function conectar()
{
define('DB_SERVER','http://**/');
define('DB_NAME','**');
define('DB_USER','**');
define('DB_PASS','**');
$conexion=new mysqli();
$conexion->connect('DB_SERVER','DB_USER','DB_PASS', 'DB_NAME');
$error=$conexion->connect_error; //Tambien vale connect_error
echo $error;
}
?>
You must have name attribute in your input fields if you want to pass the value using POST, GET or any other method.
<input type="text" class="" name="email" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" name="password" id="inputDNI"></input></br>
In the form you are specifing input types but you are not specifying names for that.
You are using MySQL_ procedural in your PHP page but you're using MySQLi_ Object Orientated in your connection page.
Update everything to MySQLi (object orientated). MySQL_ is now deprecated and no longer supported and should not be used.
You should also check with your SQL that it allows access from the IP address your page is trying to access it from. If they are on the same server then you should replace your SQL database connection address with localhost .
Thanks, it works! I had to write the name of server without http:// and I had another problem mixing mysql and mysqli because it is not correct.

How do I check the password?

recently revealed a problem in my login handler. The thing is, that even though the entered password is correct and matches the one in the database, script still sends me to the mistake page.
session_start();
include ("db.php");
if (isset($_POST['login'])) {
$login = $_POST['login'];
$login = stripslashes($login);
$login = htmlspecialchars($login);
$login = trim($login);
if ($login == '') {
unset($login);
}
}
if (isset($_POST['password'])) {
$password=$_POST['password'];
$password = stripslashes($password);
$password = htmlspecialchars($password);
$password = trim($password);
$password = hash("md5",$password);
if ($password =='') {
unset($password);
}
}
if (empty($login) or empty($password))
{
exit (header('location:index.php'));
}
$result = mysql_query("SELECT * FROM users_data WHERE login='$login'");
$row = mysql_fetch_array($result);
if (empty($row['password']))
{
exit (header('location:mistake.php'));
}
else {
if ($row['password']==$password) {
$_SESSION['login']=$row['login'];
$_SESSION['users_id']=$row['users_id'];
header('location:first.php');
}
else {
header('location:mistake.php');
}
}
The HTML form:
<form action="login.php" method="post" class="login">
<label><span>Login:</span>
<input name="login" type="text" size="20" maxlength="100">
</label>
<label><span>Password:</span>
<input name="password" type="password" size="20" maxlength="100">
</label>
<p>
<input type="submit" name="submit" class ="submit" value="Login">
</p>
UPD: Thank you for your answers, finally I've got where the problem was - I just specified not enough length of password values in the database.
First of all why would you store the password in the database without hashing them(e.g. md5).
If you would do that, then there would be no need to process the password and you could just compare the stored md5(password) with the md5 hash of the password posted by the user.
Also w.r.t it is most likely that you are being redirected to the mistake.php page instead of the success.php page because of the encoding.
It would help if you provide us with the password you are using to test the code (assuming you are testing it. ;) ).
Cheers!
EDIT: Please look at better encryption techniques, as suggested by #jayblancard in the comments below.
try to use isset() instead of empty
if (isset($row['password']))
I will just advice you to try to debug your code, mistake DOT php is called in multiple places so use a die("die message") to see which one is being fired.
Since you don't have tests to your code debug output of valid and invalid input and check output.
Once you are satisfied with the inputs and outputs, check if conditions if they are behaving as expected like previously using die condition maybe.
NB: your code is messy look at this to lean basics
Also look at OO programming

redirecting the user to the same page after login

I have a header bar including a login form in every page of my website:
<header>
<form action="login.php" method="post">
<input id="username" name="username" placeholder="Benutzername" type="text">
<input id="password" name="password" placeholder="Passwort" type="password">
<input class="submit-button" type="submit" value="Login">
</form>
</header>
When clicking submit a php script in a separate login.php is executed. login.php is also an extra page where the user can try again after failing to login.
login.php looks like this:
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is right
header('Location: index.php');
up here is where the problem starts. As you can see, the user is redirected to index.php when the form is sent and the login succeeds. What I would like to do is redirect the user to whatever page they are currently on when submitting the form (e.g. when the user is currently on a page that shows my website guidelines and logs in, I want him to be redirected to the very same guidelines-page when the login succeeds.)
I tried something like this:
if($dn['password']==$password and mysql_num_rows($req)>0)
{
if(($_SERVER['REQUEST_URl'] == login.php)){
header('Location: index.php');
} else {
header('Location: '.$_SERVER['REQUEST_URl']);
}
This is the last part of login.php:
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
lots html following...
I hope this is clear. Thank you!
You should use HTTP_REFERER instead of REQUEST_URl :
if($dn['password']==$password and mysql_num_rows($req)>0) {
if(($_SERVER['HTTP_REFERER'] === "login.php")){
header('Location: index.php');
} else {
header('Location: '.$_SERVER['HTTP_REFERER']);
}
}
you will need to use:
$_SERVER['HTTP_REFERER'];
to return to the very last page before the login process!
You can access browser history using javaScript. Just include the script in the index page and send the users to the desired page.
Use window.history.go method
window.history reference
https://developer.mozilla.org/en-US/docs/Web/API/Window.history
Or without jS
http://ha.ckers.org/blog/20070228/steal-browser-history-without-javascript/

PHP/MySQL Database Issues

PHP/MySQL newbie question.
I have a database I've imported into my local phpmyadmin. However it seems I can't access it from my a php application. The connection string seems right and when I try to authenticate user credentials to access database information, no problems.
However authenticate everyone and knows when I put in fake credentials. Still it won't pull any other information from the database.
For instance, once a users login they should see something like, "Hello username", that kind of thing. At this point I see "Hello" without the username. Any ideas what i might be missing?
I noticed you are using the root user (though I'm not sure if this was added merely for posting purposes here.) Depending on what hosting environment you are using this may or may not be a problem - some shared hosts force you to assign a user for databases in MySQL.
From the looks of things your query should be executing and returning a number of rows at the least. Have your tried print_r on the results array? If so, can you post the output?
If you are successfully getting results from the database, I don't see anywhere in your posted code a conditional that echos out a success message. You may want to check isset() against the $_SESSION superglobal keys you assign ( recordID and firstName) and if true echo out a success message if you have not already done so.
Just a thought as well - I noticed you are using sprintf to format out your query - it may be a bit too robust for what you're trying to accomplish, but using PDO to get parameterized sql queries is a nice way to get that job done where available.
Introduction to PHP 5 PDO
ok sorry for all the back and forth guys. here's the issue. I've got a php app and mysql database connected (or at least i hope so...). there is a form in the header of my page for users to login. i CAN login but i can't seem to pull any information from the database. If i try to log in using bogus credentials i'm given an "incorrect login" message. However when i do login it can't seem to pull anything else from the database other than those credentials.
ok here's the code...
DATABASE CONNECTION:
<?php
session_start();
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_test = "localhost";
$database_test = "girlpower";
$username_test = "root";
$password_test = "password";
$test = mysql_pconnect($hostname_test, $username_test, $password_test) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_test, $test);
?>
HERE'S THE LOGIN CODE:
<?php
require_once("includes/db.php");
$userEmail = trim($_POST['userEmail']);
$password = trim($_POST['password']);
$userlogin = trim($_POST['userlogin']);
//print_r($_POST);
if ($userlogin != "" && $userEmail != "" && password != "" )
{
$sql = sprintf("Select * from girlpower where email = '%s' and pwd = '%s'", $userEmail, $password );
//echo $sql;
$res = mysql_query($sql);
if( mysql_num_rows( $res ) == 0 )
{
//TODO:
//redirect..
header("Location: " . $_SERVER['HTTP_REFERER'] . "?fail=1" );
}
else
{
$row = mysql_fetch_assoc( $res );
$_SESSION['recordId'] = $row['recordId'];
$_SESSION['firstName'] = $row['firstName'];
//echo "success...";
header("Location: " . $_SERVER['HTTP_REFERER'] );
//print_r($_SERVER);
}
//print($_SESSION);
}
else
{
header("Location: " . $_SERVER['HTTP_REFERER'] . "?fail=1" );
}
HERE'S WHERE HEADER CODE (THIS IS WHERE THE FORM LIVES):
<?php
$fail = false;
if( $_GET['fail'] != "")
{
$fail = true;
}
if( $_SESSION['recordId'] != "" )
{
//get the 1st name
$firstName = $_SESSION['firstName'];
}
?>
<div id="header">
< SHOULD BE LINK "index.php"></a>
<div id="ulogin">
<fieldset id="userlogin">
<?php if( $firstName == ""){ ?>
<form name="loginForm" action="dologin.php" method="post" >
<label for="logemail">Members Login: Email</label> <input type="text"
name="userEmail" id="logemail" size="15" />
<label for="logpwd">Password</label> <input type="password" name="password"
id="logpwd" size="15" />
<input type="submit" name="userlogin" id="login" value="Login" />
<?php if ($fail == true ) {?>
<span class="error">Incorrect Login</span>
<?php }?>
</form>
</fieldset>
<?php
}
else{
?>
<div id="welcome">Welcome <?= htmlentities( $firstName ) ?> | <SHOULD BE LINK ="seemsgs.php?receiver_id="<?= $_SESSION["recordId"]?> > See Messages</> |<SHOULD BE LINK ="member.php">Update Profile</> | <SHOULD BE LINK ="dologout.php">Logout</a> </div><?php }?>
</div>

Categories