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>
Related
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
I have three files working on an login app to learn PHP.
This is the connection with DB
<?php
# Connecting database below
$connection = mysqli_connect('localhost','root','','loginapp');
if ($connection) {
# code...
echo "connected";
}
else{
echo "Errorr";
die("Database");
}?>
and here is the html code for the web view
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Welcome to My Form</h1>
<form class="" action="login_create.php" method="post">
<input type="text" name="name" placeholder="Enter your name here"><br>
<input type="password" name="password" placeholder="Enter Password" value=""><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
and here is the file where things are going wrong, its not checking the conditions of entries and not putting the data into database what's wrong going there? help please
sometimes it gives
error that "unknown 'sbumit' in the $_POST" and sometimes it don't
doesn't even show any error
but doesn't even do anything
<?php
include "db.php";
if (isset($_POST['submit'])) {
$username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
if (strlen($username) > 10 && strlen($username) < 3) {
echo "Must enter username & pass between 3 & 10";
echo "So that we can forward your request";
}
else {
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')";
$result = mysqli_query($connection,$query);
if(!$result)
{
die('Sorry Query faild'.mysqli_error());
}
}
}
else
{
echo "You haven't wrote anything, write it first";
}
}?>
Habib,
Some guidance for PHP :
$button = isset($_POST["submit"])?$_POST["submit"]:"";
What this line does is apply a value to the $button variable, the first check is that IF isset($var) THEN (indicated with the ? ) apply the value of $var to the $button variable.
The colon : then sets that if the boolean query (true/false) of the IF returns false, then apply the second value instead, in this case an empty string of "".
This is code minimalisation and you should be aware of it but there is little need to use it, especially while learning.
Feedback on your code:
mysqli_error($connection); Your error feedback for MySQLi should include the connection details, as shown here.
replace the $username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
because you want to check not if they're set but if they're not empty, currently they will be set as they're set to the values of $_POST even if they are null (potentially), so replace with:
if(!empty($username) && !empty($password)){
Also note that ! is the negative operator. so above is IF NOT EMPTY.
if (strlen($username) > 10 && strlen($username) < 3) { this is impossible to reach because you're setting if string is longer then 10 AND string is shorter than 3, this is clearly impossible. replace the && with || which is OR rather than AND .
Personally I think that isset($_POST['submit']) is not the best way, instead checking that if($_POST['submit'] == 'submit') confirms the submission of this form from this submit button (the value is the value set in your HTML form).
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')"; This works fine, BUT you really, really need to do some research into SQL injection attacks and SQL security. read How can I prevent SQL injection in PHP? as a start. This is very important to learn at the start of your PHP MySQL learning.
Also research into PDO database connectivity.
Also be aware that your script will not output anything when you have a successful saving of username/password to the database.
As a closer:
Fnally, set up error logging on your page, to give you useful feedback on errors and problems: error_reporting(E_ALL);
ini_set('display_errors', 1); at the very top of your page. Also see How do I get PHP errors to display?
Change your code as follow.
<?php
include "db.php";
$button = isset($_POST["submit"])?$_POST["submit"]:"";
$username = isset($_POST["name"])?$_POST["name"]:"";
$password = isset($_POST["password "])?$_POST["password "]:"";
/*Commetents*/
$button =isset($_POST["submit"])?$_POST["submit"]:"";
is similar to following code:
if(isset($_POST["submit"]))
{
$button = $_POST["submit"];
}
else
{
$button = $_POST["submit"];
}
You know in Php 5.4 , it will present error,if you do not set any value to variable . that is why we used it. If it doesn't get any value it will set it value "".
if($button == "submit") means when someone will press the button submit then $_POST['submit'] value will be submit which you define in the submit button value.
if($button == "submit")
{
if($username=="" or $password=="")
{
$error ="Username & Password can't be blank";
}
elseif(strlen($username)<3 or strlen($username) > 10 )
{
$error ="Must enter username & pass between 3 & 10";
}
else
{
$query = "INSERT INTO users (username,password) VALUES('$username','$password')";
mysqli_query($connection,$query) or die(mysqli_error());
}
}
echo $error;
Hope it will help you .
I'm currently building a php based login for a website which happens to work in my localhost created with Wamp, but it does not work if I copy my files over to a remote server and set up the same database there. The connection with the database should be okay, because I can register a new user on the site and the site also shows everything that is to be taken off from the database.
The problem with the login part of the site is that it just simply doesn't do anything at all. I try to login, and if it's with the proper account details, it says login is succesful and it also echoes the session variables for testing purposes (for example: it shows the given user's ID that is saved in the database). But when I navigate to an other page, the user is just not logged in at all. I'll try to list all the code here that should be important to see what's the problem:
The login form:
<form action="submit.php" method="POST" id="loginForm">
<fieldset>
<table id="form_Table">
<tr>
<td><label for="login_Username">Username</label></td>
<td><input type="text" name="login_Username" id="login_Username" class="" /></td>
</tr>
<tr>
<td><label for="login_Password">Password</label></td>
<td><input type="password" name="login_Password" id="login_Password" class="" /></td>
</tr>
</table>
<p class="submit"><input type="submit" name="login_Submit" value="Log in" /></p>
</fieldset>
</form>
The php code which handles the login procedure in the submit.php:
if (isset($_POST['login_Submit'])) {
if (!empty($_POST['login_Username']) && !empty($_POST['login_Password'])) {
$username = mysql_real_escape_string($_POST['login_Username']);
$password = md5(mysql_real_escape_string($_POST['login_Password']));
$sql = "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'";
$checklogin = mysql_query($sql);
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());
}
if(mysql_num_rows($checklogin) == "1") {
$row = mysql_fetch_array($checklogin);
$group = $row['group'];
$userid = $row['id'];
$cart = array();
$_SESSION['Username'] = $username;
$_SESSION['Group'] = $group;
$_SESSION['UserID'] = $userid;
$_SESSION['LoggedIn'] = 1;
$_SESSION['cart'] = $cart;
echo '<h1>Logged in successfully!</h1>';
//echo '<meta http-equiv="refresh" content="1;index.php">';
echo $_SESSION['Username'];
echo $_SESSION['LoggedIn'];
echo $_SESSION['UserID'];
echo $_SESSION['Group'];
} else {
echo '<h1>Wrong username or password!</h1>';
}
}
}
index.php:
<?php
#session_start();
include 'header.php';
?>
connection.php:
<?php
#session_start();
//connect variables are here
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL connection error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL database error: " . mysql_error());
mysql_query('SET NAMES utf8');
?>
header.php:
<?php include 'connection.php';
#session_start();?>
My best guess was that for some reason the site does not keep the session variables after I leave the given page, that's why I added the #session_start() to multiple pages, but it does not work this way either.
As I have ran out of ideas of what could I do now, any help would be greatly appreciated. Thank you.
When you get a "headers already sent" error, it should specify the file and line responsible for the premature output.
I suspect you might have a trailing whitespace after a PHP closing tag in one of your files. Because this is such a problem, it's a good idea to completely omit the closing PHP tag. The PHP parser doesn't care, so why should you? :)
A simple fix might be to simply use output buffering, but it shouldn't be necessary in this instance.
Have you checked to see if a cookie is being set? Are you calling session_destroy() anywhere? session_start() should only ever be called once. It would probably make sense to shove it into a bootstrap file, and include that from each of your pages.
I looked at previos Undefined error questions to see if I could find help for my question, but I can't seem to fix it for my problem.
So when I try to log in a user I get an error that says Undefined index:
No sure why Im getting this message on my login.php page
I have a database and a table called users with data inserted
this is what I use to connect to the database
conn.php
<?php
session_start();
$dbhost = "127.0.0.1"; // my database
$dbname = "fxdme";
$dbuser = "root";
$dbpass = "";
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname) or die("MySQL Error: " . mysqli_error("Cant Connect"));
?>
the login script
login.php
<?php include 'template/header.php';?>
<form action="login.php" method="POST">
User Name: <input type="text" name="username" />
Password: <input type="password" name="password"/>
<input class="submit" name="submit" type="submit" value="Log In"/>
</form>
<?php
$result=$mysqli->query('SELECT * FROM users WHERE username = "' .
$_POST['username'] . '" AND password = "' . $_POST['password'] . '"');
//set session user
$row = $result->fetch_assoc();
$_SESSION['user_id'] = $row['id'];
if ($_SESSION['user_id']) {
echo "You are logged in, $session_username. <a href='logout.php'>Log out</a>"; }
else {
echo " cant log in";
}
?>
// Index page
My index page
index.php
//in the template header is where Im calling my conn file
<?php include 'template/header.php'; ?>
<?php
if (isset($_GET['invalid'])) {
echo "<tr><td colspan='2' align='right'>Invalid login.</td></tr>";
}
?>
Im trying to get the error fixed so I'm not worried about sql injections at the moment. I just want to be able to login and and worry about the other stuff later.
You will find that $_POST["username"] will return invalid index if username is not in the post variables.
I usually create a set of variables to hold the my post variables so I can do validation and normalisation of the data first
So before your query statement
$username=(isset($_POST) && isset($_POST["username"]) ? $_POST["username"] : "";
$password=(isset($_POST) && isset($_POST["password"]) ? $_POST["password"] : "";
then use $username and $password in your query. You could event turn the previous statements into a function call passing in the variable name to check.
function getPostVar($name) {
return (isset($_POST) && isset($_POST[$name]) ? $_POST[$name] : "";
}
$username=getPostVar("username");
$password=getPostVar("password");
Obviously your code is ripe for sql injection with at username of ' union select * from users --
There is not anything in your code to make a query string in URL to fetch by $_GET. How can you have an index when you don't have anything ?
For what you said, you must use a header('location:index.php?invalid=1'); if the user can not log in to your system.
Might not be the same issue for you but I had this same error when converting to mysqli and my fetch statement looked the same as yours.
try changing.
$row = $result->fetch_assoc();
to
$row = $result->fetch_array(MYSQLI_ASSOC));
index.php
<?php
if( $_SESSION['auth'] != 1 ) {
require( 'login.php' );
}
else {
echo "hello";
}
?>
login.php
<?php
$name = $_POST['name'];
$pass = $_POST['pass'];
if( isset($name) || isset($pass) )
{
if( empty($name) ) {
die ("ERROR: Please enter username!");
}
if( empty($pass) ) {
die ("ERROR: Please enter password!");
}
if( $name == "<some name>" && $pass == "<some password>" )
{
// Authentication successful - Set session
session_start();
$_SESSION['auth'] = 1;
setcookie("username", $_POST['name'], time()+(84600*30));
echo "Access granted!";
}
else {
echo "ERROR: Incorrect username or password!";
}
}
// If no submission, display login form
else {
?>
<html>
<head></head>
<body>
<center>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Username: <input type="text" name="name" value="<?php echo $_COOKIE['username']; ?>">
<p />
Password: <input type="password" name="pass">
<p />
<input type="submit" name="submit" value="Log In">
</center>
</body>
</html>
<?php
}
?>
So, as I'm still learning PHP, there's a few things I'm trying to figure out now:
How do I get it so I can reload index.php and it displays 'hello'?
How can I get login.php to auto-load index.php on a successful authentication so I can get it to that "hello"?
Later, would using a cookie to store the user's submitted login data (so they don't have to refill the form to restore their session) have any potential problems?
Help appreciated.
1, You're missing session_start() in index.php. Add it and you should be able to see 'Hello world'
2, Replace your line with "Access granted!" with a redirect:
header('Location: index.php');
exit;
3, You can definitely store credentials in a cookie, but you should always hash and salt the password. Here is a good article about password hashing.
Better way of doing things:
Check for the session variable in the index.php and redirect if it is not set. Something like this
session_start();
if (!isset($_SESSION['auth']) || $_SESSION['auth'] != 1) {
header('Location: login.php');
exit();
}
echo 'Hello';
In the login.php, after successful authentication, redirect to index.php and do the echo there.
session_start();
if( $name == "<some name>" && $pass == "<some password>" )
{
// Authentication successful - Set session
$_SESSION['auth'] = 1;
setcookie("username", $_POST['name'], time()+(84600*30));
header('Location: index.php');
exit();
}
else {
echo "ERROR: Incorrect username or password!";
}
session_start() should come before any content is echoed to the browser.
You should:
always try to call session_start() as early as possible - "To use cookie-based sessions, session_start() must be called before outputing anything to the browser."
check whether $_POST['name'] isset before doing $name = $_POST['name'];. You can do:
$name = isset($_POST['name']) ? $_POST['name'] : '';
store the username directly in $_SESSION so that cookie holds only PHPSESSID and no data that could be replaced / abused by the end users:
$_SESSION['user'] = 'John';
try to redirect the user to index.php to see the immediate result of changing the session:
header('Location: index.php');
exit;
So this is how it could look like:
<?php
session_start();
if (empty($_SESSION['user'])) {
$name = isset($_POST['name']) ? $_POST['name'] : '';
$pass = isset($_POST['pass']) ? $_POST['pass'] : '';
if ($name != '' || $pass != '')
{
if ($name === '')
die("ERROR: Please enter the username!");
if ($pass === '')
die("ERROR: Please enter the password!");
if ($name == "test" && $pass == "test") {
// authentication successful, save username in session:
$_SESSION['user'] = 'John';
// redirect to index.php to welcome the logged in user:
header('Location: index.php');
exit;
}
else {
die("ERROR: Incorrect username or password!");
}
}
// no submitted data, display form:
?>
<html>
<head></head>
<body>
<center>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Username: <input type="text" name="name" value=""><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Log In">
</form>
</center>
</body>
</html>
<?php
}
else {
// info about current user is stored in session, welcome this user:
echo "hello " . $_SESSION['user'];
}
?>
Use this to redirect to index.php (I hope it answers your #1 and #2)
if( $name == "<some name>" && $pass == "<some password>" )
{
// Authentication successful - Set session
session_start();
$_SESSION['auth'] = 1;
setcookie("username", $_POST['name'], time()+(84600*30));
//echo "Access granted!";
header("Location: index.php");
die('');
}
You are using cookies to store the username directly. That is not a great option. What if a user modifies the cookies, to read some other username? Instead use $_SESSION['..']
Like this:
$_SESSION['user']=$_POST['name'];
and then later on,
if (isset($_SESSION['user']))
echo "Hello, " . $_SESSION['user'];
How do I get it so I can reload index.php and it displays 'hello'?
Remove the else, so it will always display the "hello":
if($_SESSION['auth'] != 1) {
require('login.php');
}
// Either way always print.
echo "hello";
How can I get login.php to auto-load index.php on a successful authentication so I can get it to that "hello"?
Replace echo "Access granted!"; with header('Location:index.php');
Later, would using a cookie to store the user's submitted login data (so they don't have to refill the form to restore their session) have any potential problems?
As long as are using this as a way to autofill the username only. and require the users to enter their password every time. otherwise a user can set his username cookie to "admin" or some other user.
no one is mentioning that you should check that the session is actually a valid one... if you just check it's set you can most likley fake it and get through.
also to hash credentials into the cookie i would encrypt it first server side and then hash it. just in case somewhere in the future someone breaks the hash type. sha3-256 is your best choice here as it's not known to be broken and should resist alot of computing power increase in the future.
What i usually do is to encrypt password and user with the user password itself as key, that way, if you also store their credentials in this fasion in your own database, there is no way even for the site maintainer to decrypt it and steal the passwords. and any db dumping skiddie will have only some meta data. (you should also encrypt the usernames...)
It seems a little conveluted to be a 'simple login and password for the users' but really as simple as possible should still consider security for your users, even if it's not a public site...
So remember:
check sessions and cookies for valid contents if they are there
check user and pw input fields for sane data before forwarding to your auth process.
encrypt user and pw information in your server side, and in the client side if you send it there (cookies?).
use AES256 atleast (mysql support this native since 5.6 its really easy to use...) for encrypting data.
use sha3-256 for hashing.
look at guides for crypto and hashing as it's easy to mess up.
ask a friend in the know to test your setup to best of their ability for a crate of beer ^^ and have fun with him and learn a bunch of stuff about your code :D
lastly, i will have forgotten (or don't know atall) alot of stuff, so there will be missing bullets! :D