Ok, I'm in the middle of making a multi function php file.
The file is named functions.php and has switch - case.
At first, I just have a simple register.php file which sends to functions.php.
Here's the error which I get :-
Notice: Undefined index: action in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\transfer\functions.php on line 5
functions.php?username=223&password=223&action=register
This is pretty unsecure..I just want to show the action..like functions.php?action=register
What changes do I make to my script ?
Here's the code :-
register.php
<form action="functions.php" name="post">
<table>
<tr>
<td>Username : </td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td><input type="submit" name="action" value="register"></td>
</tr>
</table>
</form>
functions.php
<?php
session_start();
$db = mysql_connect('127.0.0.1', 'root', 'akshay!##') or die (mysql_error($db));
mysql_select_db('transfer', $db);
switch($_POST['action'])
{
case 'register':
$username = (isset($_POST['username'])) ? $_POST['username'] : '';
$password=(isset($_POST['password'])) ? $_POST['password'] : '';
$username=mysql_real_escape_string($username, $db);
$password = md5($password);
$password = mysql_real_escape_string($password);
$query = "select * from users where user_name = '" . $username . "'";
$result = mysql_query($query, $db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
echo "Username already exists, redirecting";
header('Refresh: 3; URL=register.php');
die();
}
if(empty($username) || empty($password))
{
echo "Fields cannot be empty, redirecting";
header('Refresh: 3; URL=register.php');
}
else
{
$query2 = "insert into users(user_id, user_name, user_pass)
values
(NULL, '" . $username . "', '" . $password . "')";
$result2 = mysql_query($query2, $db) or die (mysql_error($db));
if($result2)
{
echo "Registration successful";
}
else
{
echo "Cannot register";
}
}
break;
}
?>
Based on the query string ("functions.php?username=223&password=223&action=register"), it looks like you're using GET to send the data, and not POST.
You should be looking for $_GET['action'] instead, and you should use
isset($_GET['action'])
to check if the action is set.
Edit
If you're set on using POST, which you really should be for this type of application, then you'll need to change your form:
<form action="functions.php" name="post" method="post">
Additionally, you'll want to use a hidden field for the action parameter instead of using the submit button:
<td>
<input type="hidden" name="action" value="register" />
<input type="submit" name="submit" value="Submit" />
</td>
The method="POST" attribute ensures that your data will be transmitted to functions.php using POST. This way the data won't show up in the URL.
Then, your functions.php can contain:
if (isset($_POST['action'])) {
switch($_POST['action']) {
case 'register':
$username = (isset($_POST['username'])) ? $_POST['username'] : '';
// And so on
}
}
else {
echo "No action specified.";
}
It means that $_POST['action'] isn't set.
In your example you pass it in the URL, so should be using $_GET['action'] instead.
Related
I have 3 pages, I am trying to create a simple member login system using session .
In my first page ( index.php) I have database connection, session setup and this following login from :
<form action="index.php" method="POST">
<table>
<tr>
<td><label>Username</label></td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitbtn" value="Login" /></td>
</tr>
</table>
</form>
In member's profile page (member.php), I have a table to fetch data from database of that specific member logged in :
<table>
<?php $members=getMember(); ?>
<?php while($member = $members->fetch_assoc()) : ?>
<tr><td><label>Name</label></td><td><?php echo $member['name'];?></td></tr>
<tr><td><label>Age</label></td><td><?php echo $member['age'];?></td></tr>
<?php endwhile; ?>
</table>
and at dbconnection.php page I have this function :
<?php
function getMember(){
$db_conn = getConnection();
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if(!$db_conn) return false;
$sql = "SELECT * FROM member WHERE username ='$username' AND password='$password'";
$result = $db_conn->query($sql);
$db_conn->close();
return $result;
}
The code of session setup are :
<?php
$username="";
$password="";
$success=true;
$_SESSION['username']=$username;
if(isset($_POST['username']) && isset($_POST['password']))
{
$username=$_POST['username'];
$password=$_POST['password'];
if(check_in_db($username,$password)){
$_SESSION['logged_in']=1;
$_SESSION['username']=$username;
header("Location: adminPanel.php");
}
else{
$success=false;
}
}
?>
But when I am logging in, data ( name and age ) is not fetching ( displaying) there in member.php page ( I can't add image, since my reputation is under 10 ).
Thank you for your time .
I would suggest you take a look at php type comparisons for how isset() works. To let you know how php session works and how users persist in different pages, you have to digg into php session. I would recommend you use PDO and its prepare method when you're dealing with user data. Here you would get a very simple example of it.
The following code is working. So please take a look at them how they are constructed:
dbconnection.php
<?php
function getConnection() {
$servername = "localhost";
$username = "root";
$password = "12345";
$dbname = "db_test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function check_in_db($username, $password) {
$db_conn = getConnection();
if (!$db_conn) {
return false;
}
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $db_conn->query($sql);
return $result->num_rows > 0;
}
function getMember($username, $password) {
$db_conn = getConnection();
if (!$db_conn) {
return false;
}
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $db_conn->query($sql);
return $result;
}
index.php
<?php
session_start();
require_once('./dbconnection.php');
$success = true;
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(check_in_db($username, $password)) {
$_SESSION['logged_in'] = 1;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("Location: adminPanel.php");
}
else{
$success=false;
}
}
?>
<form action="index.php" method="POST">
<table>
<tr>
<td><label>Username</label></td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitbtn" value="Login" /></td>
</tr>
</table>
</form>
and member.php
<?php
session_start();
require_once('./dbconnection.php');
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$members = getMember($username, $password);
?>
<table>
<?php while($member = $members->fetch_assoc()) : ?>
<tr><td><label>Name</label></td><td><?php echo $member['name'];?></td></tr>
<tr><td><label>Age</label></td><td><?php echo $member['age'];?></td></tr>
<?php endwhile; ?>
</table>
when write anything in form and click Enter button, there is no error, but when i write the username and password correct the error show up
i tried echo "$_POST['username']"; // print username if username doesn't match ?
Error:
Notice: Undefined index: username in ..
Notice: Undefined index: password in ..
this is my form
<form action="2.php" method="post">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Enter" />
</td>
</tr>
</table>
</form>
and this my second page
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die('Could not connect');
exit;
}
mysql_select_db('dbName') or die( "Unable to select database");
$query = "SELECT * FROM admin WHERE username = '$username'";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result); // number of rows
if ($num > 0){
$i = 0;
while ($i < $num){
$row = mysql_fetch_array($result);
if ( ($password) == $row['password'] && ($username) == $row['username'] ){
header('location:2.php');
$_SESSION['sessionname'] = $username;
$_SESSION['sessionpass'] = $password;
}
elseif ( ($password) != $row['password'] && ($username) == $row['username'] ) {
echo "Wrong Password <a href='1.php' >Click Here</a>";
}
$i++;
}
}else {
echo "Username <strong><u>$_POST[username]</u></strong> invalid ! <a href='1.php' >Click Here</a> ";
}
?>
There is no reason to assign the username and password variables in the way you did. Simply assign the post data to the variables as you normally would with a session.
I have a login page (local intranet so dont worry about the security issues).
This page consists of the following form code :
<form action="auth.php" method="get" class="blocklogin">
<tr>
<td class="blocklogin" ><div align="left">Username: <input class="blocklogin" type="text" name="username" id="username" /><br />
</div></td>
</tr>
<tr>
<td class="blocklogin" ><div align="left">Password: <input class="blocklogin" type="password" name="password" id="password" />
</div></td>
</tr>
<tr>
<td colspan="2" class="blockloginfoot" title="Login"><input name="Login" type="submit" value="Login" /></td>
</form>
Now im trying to pass the username and password via the http link by doing the following :
http://localhost/folder/user_login.php?username=user#test&password=test123
But this does not seem to work,its suppose to use the details in the link to login. Am I missing something?
Pls help
The form action auth.php
<?php
session_start();
require_once('database.php');
$username = $_GET['username'];
$password = $_GET['password'];
$sql = "SELECT * FROM access_getaccountswithinfo WHERE username='".$username."' AND password='".$password."'";
$run = mysql_query($sql);
$row = mysql_fetch_array($run);
if (mysql_num_rows($run) == 1) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['password'] = $row['password'];
$_SESSION['packagename'] = $row['packagename'];
$_SESSION['creation-date'] = $row['creation-date'];
$_SESSION['cap'] = $row['cap'];
$_SESSION['total'] = $row['total'];
$_SESSION['remainingtopup'] = $row['remainingtopup'];
header("location: usage.php");
} else {
header("location: user_login.php");
}
mysql_close($link);
?>
Database code - database.php :
<?php
$link = mysql_connect('localhost', 'dbase', 'pass123');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make dbase the current db
$db_selected = mysql_select_db('dbase', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
If you try via url:
http://yourserver.com/folder/user_login.php?username=user#test&password=test123
You should use $_GET['username'] and $_GET['password'] to retrieve the value.
Otherwise if you submitting it, use $_POST['username'] and $_POST['password']
May this help.
Your html form uses the method "post" to send the data to your php script. Post data is sent in the header and the setup you have now should work.
When doing it via url you can get the parameters using "$_GET", not "$_POST".
Also, remember to htmlspecialchars() what you send from the form.
instead of using URL passing values to user_login.php where the form is...you have to pass it to auth.php which is the php that actually captures the values as follow
http://localhost/folder/auth.php?username=user#test&password=test123
im currently stuck trying to create a log in form that submits to its self so that if theres any errors they'll be displayed above the login form rather than being sent to another page. Also if the login is successful then they're sent to the desired page. Here's my code below, I appreciate any help, Thanks!
<?php
if ((isset($_REQUEST['username'])) && (isset($_REQUEST['password']))) {
$adminusername = $_POST["username"];
$adminpassword = $_POST["password"];
if ($adminusername == '' || $adminpassword == '') {
echo "<b>You must complete all sections</b><br/>";
}
$query = mysql_query("SELECT * FROM admin WHERE username = '$adminusername' AND password = '$adminpassword'");
$numrows = mysql_num_rows($query);
if ($numrows != 0) {
while ($row = mysql_fetch_assoc($query)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($adminusername == $dbusername && ($adminpassword == $dbpassword)) {
$_SESSION['username'] = $adminusername;
header("Location: admin.php");
}
} else {
echo " ($error) Username and password do not match";
}
}
?>
<h3>Admin Login</h3>
<form name="login" action="<?= $SERVER['PHP_SELF'] ?>" method="POST">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/><br/>
<button type="submit">Log In</button>
</form>
I've indented your code so you can see the structure more clearly.
If the username and password are blank then an error will be output, but the database will still be queried.
You're not checking whether the database query actually works. You should check $query is not false, and if it is report an error.
You're checking the username and passwords match twice (once in the SQL and once again later), this is overkill, and besides you're not reporting if the second check fails.
header() will only work if you've not sent any output yet... if there's anything output before the code you've shown, even a blank line outside of PHP, then the header won't work.
On its own, this works for me (sql injection potential aside):
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$adminusername = $_POST["username"];
$adminpassword = $_POST["password"];
if ($adminusername == '' || $adminpassword == '') {
echo "<b>You must complete all sections</b><br/>";
} else {
$sql = "SELECT * FROM admin WHERE username = '$adminusername' AND password = '$adminpassword'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['username'] = $adminusername;
header('Location: /admin.php');
exit;
}
echo "<b>Username and password do not match</b><br/>";
}
}
?>
<h3>Admin Login</h3>
<form name="login" action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/><br/>
<button type="submit">Log In</button>
</form>
To submit a <form>, you need a submit button; you've got:
<button type="submit">Log In</button>
try:
<input type="submit" value="Log In" />
I don't think you're currently submitting the form, so nothing will happen when you click submit.
instead of
header("Location: admin.php");
try java script
echo "<script>window.location = 'admin.php';</script>
if you have already outpu to the page header wont work
My solution echos the form with the error below it within a div. I'm still learning but I hope it helps someone.
<div>
<?php
//make sure the form action='' is set to itseslf
echo "
<form action='self_page_name' method='post'>
<table>
<tr>
<td>UserName:</td>
</tr>
<tr>
<td><input type='text' name='username' required='required' /></td>
</tr>
<tr>
<td>Password: </td>
</tr>
<tr>
<td><input type='password' name='password' required='required' /></td>
</tr>
<tr>
<td><input type='submit' name='submit' value='Login' /></td>
</tr>
</table>
</form>
";
//////////your php validation script here////////////
?>
</div>
I'm trying to build a login form so an admin I specify in the database can insert images into my database.
I'm having a few errors:
1) I'm using <?php echo $_SERVER['PHP_SELF']; ?> to call itself (call Login.php) so it will load the PHP code below it (which is in the same file). Whenever I press submit, it doesn't go to the specified header in the php code, but rather goes back to the homepage.php.
Login.php: Admin Login Form html
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>Username: </td><td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password: </td> <td><input type="text" name="pw"></td>
</tr>
</table>
<br />
<input type="submit" value="Log in">
</center>
2) The second issue is... looking at the php code, I'm trying to find a function that will let me grab a specific key of an associate array. For example, I run the database query and store it as an associate array in $result, and return that. Then I want to grab a key ("username" and "password") from users table and compare them to the input from the above html form.
I've tried using array_keys, but that needs an array, not an object. So I casted it, and it still won't work.
I'm using print_r(array_keys($userResult, "username")); to see if it would print the key I wanted.
Login.php Php code
<?php
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['pw']) ? $_POST['pw'] : "";
$userResult = verify($username, $password);
$array = (array)$userResult; //cast to array
print_r(array_keys($userResult, "username"));
if(array_keys($userResult, "username") == "dan" && array_keys($userResult, "password") == "12345") {
header("Location: ?action=admin");
}
else {
echo "<center>Incorrect credentials</center>";
}
function verify($user, $pw) {
include './scripts/dbconnect.php';
$result = $mysqli->query("SELECT username, password FROM users WHERE username='" . $user . "' AND password='" . $pw . "'");
return $result;
}
include 'include/footer.php';
?>
Any thoughts would be appreciated!
You can leave action in blank like action="" and it will post in the same page.
I don't remember what $_SERVER['PHP_SELF'] returns inside/outside includes but that must be your problem.
Also, you are alreadly checking the username and password on your query, then you just need to know if it returns a result or dont. Check for the number of rows :)
For part one if you want to just refresh the page you can do this.
<form action='' method=''>
Otherwise it is probably easier to just hard-code the path from login.php to your processing file.
For part two I think you incorrectly created your array.
$array = array();
$array[$username] = $password; // $username is the key and $password is the value aka.. array ($username => $password )
I am not sure why but it seems like with
$array = (array)$userResult;
you are trying to set an array as a tuple run though a function and that method seems a lot less clear than just setting the keys and values.
Thanks nimlhug, got it to work as such... forgot my main reason for checking the database was to actually see if there was a matching result... don't know why I was checking again to see if there was a match when I could have just used num_rows == 1, lol.
<?php
include 'include/header.php';
?>
<center>
<h2>Admin Log in</h2>
<br/>
<form action="" method="post">
<table>
<tr>
<td>Username: </td><td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password: </td> <td><input type="text" name="pw"></td>
</tr>
</table>
<br />
<input type="submit" value="Log in">
</center>
<?php
$username = isset($_POST['username']) ? $_POST['username'] : "";
$password = isset($_POST['pw']) ? $_POST['pw'] : "";
if(verify($username, $password) == 1) {
header("Location: ?action=admin");
}
else {
echo "<center>Incorrect credentials</center>";
}
function verify($user, $pw) {
include './scripts/dbconnect.php';
$result = $mysqli->query("SELECT username, password FROM users WHERE username='" . $user . "' AND password='" . $pw . "'");
return $result->num_rows;
}
include 'include/footer.php';
?>