I've got problem when using sessions to recall data stored in mySQL database. This is my code:
The login page is simple, the input your username and password kind (i know the password is still plaintext, i plan to change it later).
<?php
$host="localhost";
$user="root";
$pass="";
$db_name="proyek";
$tbl_name="murid";
mysql_connect("$host", "$user", "$pass")or die("Cannot connect to SQL.");
mysql_select_db('$db_name');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="header">
LOGO
<h1 align="center">TITLE</h1>
</div>
<br/>
<div id="login">
<form id="loginform" name="loginform" method="post" action="checklogin.php">
<table border="0" align="center">
<tr>
<td>NIS</td>
<td></td>
<td><input type="text" name="nislogin" id="nislogin"/></td>
</tr>
<tr>
<td>Password</td>
<td></td>
<td><input type="password" name="pwdlogin" id="pwdlogin"/></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="loginbutton" id="loginbutton" value="Login"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
and this is the code for login check page:
<?php
session_start();
$host="localhost";
$user="root";
$pass="";
$db_name="proyek";
$tbl_name="murid";
mysql_connect("$host", "$user", "$pass")or die("Cannot connect to SQL.");
mysql_select_db('$db_name');
$nis=($_POST['nislogin']);
$pwd=($_POST['pwdlogin']);
$sql="SELECT * FROM murid WHERE nis='$nis' and password='$pwd'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
$_SESSION['nislogin']=$nis;
$nama=$result['nama'];
$_SESSION['nama']=$nama;
header("location:index.php");
return true;
exit;
}
else
{
echo("Wrong NIS or password.");
return false;
}
?>
i have entered some dummy data in database for testing purposes; id, password, name. how can i recall something from database while user only login with username/id?
i'd like to display something like 'hello, name' in the next page. Help is appreciated.
edit: I've edited my code based on feedbacks and it produces blank; like 'Hello,' with no name.
First of all, since you are running a query on your login check page, use that value for your session rather than the post data. Also, whenever you are redirecting, always exit your script.
EDIT:
Since you are in the development stage, you need to display an error if your query fails so you know why. I also realized you need to return an associative array to access the row. Try this.
$sql="SELECT * FROM murid WHERE nis='$nis' and password='$pwd'";
$result=mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$count=mysql_num_rows($result);
if($count==1)
{
$data=mysql_fetch_assoc($result); // since you are only accessing one row,
// otherwise you would put this in a loop to build your array.
session_start();
$_SESSION['nislogin']=$data['nis'];
header("location:index.php");
return true;
exit;
}
I also see this session on your login page, but I don't see that you ever created it and I don't see the purpose.
if(isset($_SESSION['nama']))
{
unset($_SESSION['nama']);
}
Basically all you need from here, is to start the session on index.php and output it.
index.php
session_start();
if(isset($_SESSION['nislogin']))
{
$name = $_SESSION['nislogin'];
} else {
$name = "stranger";
}
<body>
Welcome, <?=$name?>
</body>
Related
i have a form file with name form1.php
<?PHP
//form.php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>form</title>
</head>
<body>
<?PHP if (isset ($_SESSION["notfound"])) { ?>
<h2 style="text-align:center">Wrong user name or password</h2>
<?PHP unset($_SESSION["notfound"]);}
if (isset ($_SESSION["empty"])) {?>
<h2 style="text-align:center">Empty</h2>
<?PHP unset($_SESSION["empty"]); }?>
<form name="signin" action="http://localhost/M1.php" method="post">
<table>
<tr>
<td>
<label>
Username<input type="text" name="name" size="32"/>
</label>
</td>
<td>
<label>
Password <input type="password" name="pass" size="32"/>
</label>
</td>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>
</form>
and controll file M1.php
<?php
$name=$_POST["name"];
$pass=$_POST["pass"];
if((!empty($name)) && (!empty($pass)))
{
session_start();
if($conection=mysql_connect("localhost","","")===false)
die("not connect to data base");
if(mysql_select_db('login',$conection) ===false)
die("data base not found");
$sql =sprintf("SELECT `password` FROM `signin` WHERE `username`= '%s' ",mysql_real_escape_string($name));
$dbpass=mysql_query($sql);
if ($dbpass==$pass)
{
$_SESSION["authenticated"]=true;
header("Location: http://localhost/home.php");
exit;
}
else //if ($dbpass===false)
{
$_SESSION["notfound"]=true;
header("Location: http://localhost/form1.php");
exit;
}
}
else
{
$_SESSION["empty"]=true;
header("Location: http://localhost/form1.php");
exit;
}
?>
*i am useing xampp for runing them
i have data base loging which contain a table signin
when i fill the form with same user name and password which i save in signin table and click submit it return me on form1.php with session 'notfoun'
and when i submit empty form it return me without seting empty session *
You are not fetching data from database and you make a condition based on execute query = $pass which will be always false, so change to
$dbpass=mysql_query($sql);
$result = mysql_fetch_array($dbpass);
$passw = $result['password'];
if ($passw==$pass)
{
//logged
As side note i would say a couple of thing. First I notice you sanitized your input which is a good pratice, but you really should switch to prepared statments with either PDO or mysqli so you will avoid any risk of mysql injection, also because mysql_* functions are deprecated. Second saving a password in plain text in database is a very bad pratice, you should really encrypt it and save an hash of the password in database, there is anice post about that here. Further more I think that session_start(); should be placed at the top of your file to work correctly.
It's firstly good time to make use of PDO or mysqli rather then using mysql which is deprecated in latest PHP version.
While passing db connection values, I feel you missed out the username & password, which should help you connect the database.
Later, mysql_query("SELECT_QUERY"); returns result object, whose values should be read by mysql_fetch_assoc() which returns the db row into associative array form.
Finally your code should look like,
$sql =sprintf("SELECT `password` FROM `signin` WHERE `username`= '%s' ",mysql_real_escape_string($name));
$result = mysql_query($sql);
$dbpass = mysql_fetch_assoc($result);
$dbpass = $dbpass['password'];
if ($dbpass==$pass)
{
$_SESSION["authenticated"]=true;
header("Location: http://localhost/home.php");
exit;
}
else //if ($dbpass===false)
{
$_SESSION["notfound"]=true;
header("Location: http://localhost/form1.php");
exit;
}
What's the error you're getting?
Anyway, how do you connect through your database? I see you have put the username and password as an empty string. You should try to put in a user/pass of an existing user:
mysql_connect syntax:
mysql_connect(host,username,password,newlink,clientflag)
example:
mysql_connect("localhost","root","")
or
mysql_connect("localhost","root","password")
Hi I'm brand new to PHP and I'm just doing a simple form to learn. It just contains an email address, I want to Validate the information and send it to the database. My problem is connecting it to a database. I've done a few tutorials but just leave myself confused.
Right now this is my homepage
reg.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration Form</title>
</head>
<body>
<?php include("validation.php"); ?>
<form method="post" action="connect.php" name="form">
<ul id="errors">
<li><?php echo $err_email; ?></li>
</ul>
<div id="wrapper">
<div>Email</div>
<div class="input"><input type="text" name="email" value="<?php echo $val_email; ?>" /></div>
</div>
</form>
</body>
</html>
This is my validation.php file
<?php
if($_POST)
{
$email = $_POST['email'];
// Email
if (preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email)) {
$val_email = $email;
}else{
$err_email = 'Please enter valid Email address.';
}
if((strlen($val_email)>0) ){
header("Location: reg");
}else{ }
}
?>
finally my connect file
<?php
$host="localhost";
$username="admin";
$password=""; // Mysql password
$db_name="davidtest"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("davidtest")or die("cannot select DB");
// Get values from form
$email=$_POST['email'];
// Insert data into mysql
$sql="INSERT INTO $users(email)VALUES('$email')";
$result=mysql_query($sql);
// close connection
mysql_close();
?>
INSERT INTO $users(email)VALUES('$email')
$users isn't a variable so will be empty when being placed into the table. I suspect you meant
$sql="INSERT INTO $tbl_name (email) VALUES ('$email')";
However you should never use unescaped user strings in queries since a malicious user could inject SQL into your query (read up on SQL Injection).
Also please be aware that the mysql_* series of functions is now deprecated, no longer maintained and will be removed in a future release of PHP. Consider mysqli or PDO.
I'm relatively new to PHP and have exhausted the internet trying to find an answer to this problem. I've looked at countless examples but people seem to very different login systems to mine and I have trouble deciphering it.
Here is my code so far:
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Video for Education Log In</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="logo">
videoedu.edu </div>
<div id="menu">
<ul>
<li>Create Account</li>
<li>About Us</li>
</ul>
</div>
</div>
<br><br><br><br>
<div id="page">
<div id="content">
<h2>Video for Education helps you connect and share with the videos in your life.</h2>
<h3>Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome</h3>
<div class= "form">
<form name="login" method="post" action="checklogin.php">
Username: <input type="text" name="myusername" id="myusername" class="textb"/><br />
Password : <input type="password" name="mypassword" id="mypassword" class="textb"/><br />
<br>
<input type="submit" name="login" value="Login" id="login" class="texta" />
</form>
</div>
</div>
</div>
</div>
</body>
</html>
checklogin.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "test";
$tbl_name = "members";
mysql_connect("$host", "$username", "$password")or die("Cannot connect.");
mysql_select_db("$db_name")or die("Cannot select DB.");
$myusername=$_POST["myusername"];
$mypassword=$_POST["mypassword"];
if ($myusername&&$mypassword)
{
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else
{
echo "Wrong Username or Password";
}
}
else
echo "You have left one or more fields blank.";
?>
login_success.php
<?
session_start();
if( !isset( $_SESSION['myusername'] ) ){
header("location:account.html");
}
echo "Welcome, ".$_SESSION['myusername']." - You are now logged in.<br>";
echo "<a href=logout.php>Logout</a>"
?>
<html>
<body>
</body>
</html>
logout.php
<?php
session_start();
session_destroy();
echo "You have been logged out, <a href='index.php'>click here</a> to return."
?>
I have tried inserting this into index.html and changing the file name to index.php.
$submit = $_POST["login"];
if($submit)
{
}
...but it just constantly displays one of the errors ('Wrong username or password') down the bottom of the page at all times.
I want it so that if the user enters a wrong username or password, or leaves a required field blank, the error will pop up on the same page, instead of going to a new ugly, blank PHP page with the error message in the top left-hand corner.
In checklogin.php, instead of echoing an error, use this:
die(header("location:index.html?loginFailed=true&reason=password"));
or something similar, and in your index.html page, just have PHP generate the HTML message, something like this:
<input type="submit" name="login" value="Login" id="login" class="texta" /><br /><br />
<?php $reasons = array("password" => "Wrong Username or Password", "blank" => "You have left one or more fields blank."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>
</form>
Also, make sure to die() or exit() when you use header to redirect the page, otherwise the rest of your script continues to run.
What you can do is, redirect back to your page if data is invalid. Put errors into session and display them on page:
e.g.:
<?php if(isset($_SESSION['Login.Error']) { echo $_SESSION['Login.Error'];
unset($_SESSION['Login.Error']); } ?>
<form ....
and your error will be visible on page.
In your PHP
$_SESSION["Login.Error"] = 'Invalid credentials';//redirect back to your login page
In checklogin.php, if the user enters a wrong username or password, use the code like this:
echo "<script language=\"JavaScript\">\n";
echo "alert('Username or Password was incorrect!');\n";
echo "window.location='login.php'";
echo "</script>";
It will pop up the error message at the same page (login page), instead of going to a blank PHP page.
You would want to make your index.html page a PHP page, and have the form submit to itself, i.e. to index.php. In this way, you your index page can do the login check for the form values and display the output of the page appropriately, or use headers to redirect if everything validates.
It's hard to tell the effect that your attempt may have had without seeing it in the full context, but the gist of the situation is you need the form to submit to itself and handle it's login processing.
It looks like you want/need to integrate it with jQuery or some other Javascript/AJAX library
to make things more presentable. jQuery has an plugin for form validation that's is very easy to integrate to your project (obviously jQuery library is minimum requirement).
jQuery site and
jQuery validation plugin.
You may also consider using a PHP Framework like CodeIgniter which is also has a very helpful form validation library. CodeIgniter is scary at the beginning (like all MVC based programming library/framework) but it's worth it. you can watch some tutorials on netTuts+ they've created a series of tutorials called CodeIgniter From Scratch, is not from the latest version but is easy to adapt.
------ SOLVED ------
Hi everyone, I have now solved this issue and it was my inexperience and trying to be clever that caused this issue, as you can also see from the comments below the issue was in my .htaccess file. I had put RewriteRule ^admin adminlogin.php so this was changing any page containing admin back to adminlogin.php
------ORIGINAL QUESTION------
Im trying to get a simple login script working on a website. It is coded in php and it is as follows:
adminlogin:
<div class="login">
<form name="form1" method="post" action="checklogin.php">
<table width="379px" border="0px" cellpadding="3px" cellspacing="1px">
<tr>
<td colspan="3"><strong>Admin Login</strong></td>
</tr>
<tr>
<td width="78px">Username</td>
<td width="6px">:</td>
<td width="294px"><input name="myusername" type="text"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</div>
checklogin.php:
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="Logins"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die(mysql_error());
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM `$tbl_name` WHERE UN='$myusername' and PWD=md5('$mypassword')";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file “adminloginsuccess.php"
session_start();
$_SESSION['user'] = $myusername;
header('location:adminhome.php');
}
else {
header('location:adminloginretry.php');
}
?>
adminhome.php:
<?php $thisPage="Admin Home";
session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/meta.php'); ?>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="header">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/header.php'); ?>
<div id="links">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/links.php'); ?>
</div><!--close links-->
</div><!--close header-->
<div id="sidebar">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/sidebarimage.php'); ?>
</div><!--close sidebar-->
<div id="content">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/adminhomecontent.php'); ?>
</div><!--close content-->
<div id="extra" align="center">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/fblb.php'); ?>
</div><!--close extra-->
<div id="footer">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/footer.php'); ?>
</div><!--close footer-->
</div><!--close container-->
</div><!--close wrapper-->
</body>
</html>
adminhomecontent.php:
You Have Successfully Logged In.<br>
Log Out
Now for some reason when I go and log in, I am redirected and the address bar says www.gemma-hyde-fashion-sketches.co.cc/adminhome.php but still shows the login form, and if I view the source I see the source for adminlogin.php.
I am new to PHP, could anybody assist, I found this code online so have tried myself to understand it as fully as I can
------EDIT------
I have created a log in for stackoverflow users. If you head over to www.gemma-hyde-fashion-sketches.co.cc/adminlogin.php and use the username stackoverflow and the password stackoverflow you should see the same results i'm getting (there isnt actually anything in the admin area at this time anyway)
------EDIT FOR JUDDA------
Yes what I mean is that if I log in, the address bar shows: http://www.gemma-hyde-fashion-sketches.co.cc/adminhome.php which is what i expected to be redirected to. However if i right click and view source I see
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gemma Hyde Fashion Sketches | Admin Login</title>
<meta name="title" content="Gemma Hyde Fashion Sketches | Admin Login" />
<meta name="keywords" content="Admin Login, gemma hyde fashion sketches, fashion, fashion design, fashion sketches, fashion design sketches, clothes design sketches" />
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
which is the same as what the adminlogin.php page would show, this makes me think that this section at the top of adminhome.php:
session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
}
Is just redirecting because it cannot pick up that it is logged in.
Does that clear things up?
It sounds to me like PHP isn't running on the file if you are able to see the actual PHP for it (which I understand from the statement "and if I view the source I see the source for adminlogin.php"). Do other PHP pages work (i.e. <?php phpinfo();?>)?
If you suspect the session is not set check that in adminhome.php
Change this code
Session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
to this
Session_start();
exit(var_dump($_SESSION));
I have now solved this issue and it was my inexperience and trying to be clever that caused this issue, as you can also see from the comments below the issue was in my .htaccess file. I had put RewriteRule ^admin adminlogin.php so this was changing any page containing admin back to adminlogin.php
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function redirect(URL)
{
document.location="delete_row.php";
return false;
}
</script>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM users");
?>
<table border="1">
<th>Name</th>
<th>Age</th>
<th> </th>
<?php
while($row = mysql_fetch_array($result))
{?>
<tr>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['age'];?></td>
<td>Delete</td>
</tr>
<?php } ?>
</table>
<?php
mysql_close($con);
?>
</body>
</html>
This is the PHP part with file name delete_row.php
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>
The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13
How will the page then know what row to delete? You'll have to send some sort of identifier across to it. If you mean, after it's deleted, get the id to hide again, you can do that with a redirect by using:
header('Location: urlOfPageWithoutQueryString');
You can use a small form, with the "delete" button being a submit button. Set the method to "post." An example:
<form action="delete_row.php" method="post">
<input type="hidden" name="row" value="5">
<input type="submit" value="Delete">
</form>
In your PHP file, you can then use the POST values rather than GET values. This is more correct, as well -- GET actions should be idempotent (i.e. should have no effects except returning the requested information).
You should not use GET for this kind of action at all as GET is considered as being a safe method:
[…] the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".
Use a POST form instead where you can use a hidden form control for the ID:
<form action="delete_row.php" method="post">
<input type="hidden" name="id" value="5">
<input type="submit" value="Delete row">
</form>
Apart from the safe method reason, using POST instead of GET is also not that vulnerable against Cross-Site Request Forgery attacks. At that point you should also think about using so called CSRF tokens to further reducing the chances of successful CSRF attacks.
Will this work for you?
Delete
You could also do this:
<script language="javascript" type="text/javascript">
function redirect(URL)
{
if(confirm('Are you sure you wish to delete this item?'))
document.location=URL;
return false;
}
</script>
Delete