This code I wrote is not working for an unknown reason. PHP does not report any errors or warnings.
<html>
<head>
<title>PHP Blog</title>
</head>
<body>
<?php
require 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if(isset($_POST['username']) and isset($_POST['password']))
{
$pass = "test";
$user = "test";
if($_POST['username'] == "test" and $_POST['password'] == "test")
{
echo <<<_END
<form action="post.php" method="post"><pre>
Title: <input type="text" name="title">
Post: <textarea rows="5" cols="64" name="post">
</textarea>
<input type="submit" value="Submit">
</pre></form>
_END;
if(isset($_POST['title']) and isset($_POST['post']))
{
$title = $_POST['title'];
$post = $_POST['post'];
$query = "INSERT INTO blog(title,post) VALUES('$title', '$post')";
mysql_query($query);
echo 'Succesfully posted..';
echo 'Click here';
}
}
else
{
echo "Wrong Password!";
}
}
?>
Everything works until I set variables $_POST['title'] and $_POST['post'] by clicking the button. When I do that I just get a blank page.
If the code that you have provided is post.php, this is the problem:
When you press the Submit button, the post.php only receives $_POST['title'] and $_POST['post'] from the form.
Making the $_POST['username'] and $_POST['password'] null/empty. Therefore returning FALSE for the if statement, and producing a blank page.
There are many ways to fix this, depending on your implementation.
You can pass the username and password value from the form. You can use input type hidden or text if you like.
<input type="hidden" name="username"><input type="hidden" name="password">
Use $_POST['title'] and $_POST['post'] inside the isset() instead of $_POST['username'] and $_POST['password']
And many more..
Because your form should be:
echo <<<_END
<form action="post.php" method="post"><pre>
Username: <input type="text" name="username">
Password: <input type="password" name="password">
Title: <input type="text" name="title">
Post: <textarea rows="5" cols="64" name="post">
</textarea>
<input type="submit" value="Submit">
</pre></form>
_END;
you lose your $_POST['username'] and $_POST['password'] and no test is echoed because you don't have an else for:
if(isset($_POST['username']) and isset($_POST['password']))
or you can save your login info in a session and use them without making the user eneter again his user and password.
You have to echo the login form right after the body tag.
IF not, you will always get a blank page, because your username and password will always be blank.
Related
I'm having a problem in inserting data to my database. I don't have any clues what's the error.
Here's my index:
<form id="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"/><br/>
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<button id="sub">Save</button>
</form>
<span id="result"></span>
And here's my insert.php:
include_once('db.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
if(mysql_query("INSERT INTO table_users VALUES('$name', '$username', '$password')")){
echo "Successfully Inserted";
} else {
echo "Insertion Failed";
}
And my db.php:
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('neverstoplearning');
You need to make the HTML form in a valid way like you use form but not a submit button as type submit.
HTML Form
<form id="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"/><br/>
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" id="sub" value="Save" name='submit_form'/>
</form>
Now when you click on he submit button its go for the page insert.php and from there you need to store your the username, name and password.
insert.php
For this part you need to follow some rules, Stay away from SQL Injection, follow what i share as a Note at the bottom. And must use a isset submit for doing all these thing.
if(isset($_POST['submit_form']){
include_once('db.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
// use mysqli_* and the $conn string.
if(mysqli_query($conn, "INSERT INTO table_users VALUES('$name', '$username', '$password')")){
echo "Successfully Inserted";
} else {
echo "Insertion Failed";
}
}
Note:
For the protection of SQL Injection must use mysqli_escape_string,
mysql_real_escape_string, addslashes , md5, hash.
and mysql_* now Deprecated, so start use of mysqli_* or PDO.
I am having some trouble trying to delete a member from the database I'm using, I don't think it is getting the Username correctly. Here is the form I am using for HTML
deleteForm.php
<?php
//begin our session
session_start();
?>
<html>
<head>
<title>Welcome</title>
</head>
<form action="deleteUser.php">
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
</form>
</body>
</html>
And this is the code to handle the deletion itself:
deleteUser.php
<?php
//begin our session
session_start();
//Check if username, password have been sent
if((!filter_input(INPUT_POST, 'Username')))
{
echo 'Please enter a valid username';
}
else
{
//Enter the valid data into the database
$memberUsername = filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_STRING);
echo $memberUsername;
$SQLhostname = "****";
$SQLusername = "****";
$SQLpassword = "****";
$databaseName = "****";
try
{
echo "in the try block";
// Create connection
$conn = mysqli_connect($SQLhostname, $SQLusername, $SQLpassword)
or die("Unable to connect MySQL");
$db_selected = mysqli_select_db($conn, $databaseName)
or die("Could not select database");
$deleteMember = "DELETE FROM customers
WHERE name =
'$memberUsername'";
$result = $conn->query($deleteMember);
if(! $result ){
die('Could not delete member: ' . $conn->error);}
else{
echo "Member deleted <br/>";
}
mysqli_close($conn);
}
catch (Exception $ex)
{
//To be added
}
}
?>
The problem is it always enters the if statement and asks for a valid username which I'm assuming is not being set.
Add method attribute to your form.
<form action="deleteUser.php" method="post">
<!--^^^^^^^^^^-->
<p>
<center><label for="Username">Enter username to delete</center></label>
<center><input type="text" id="Username" name="Username" value="" maxlength="20" /></center>
<center><input type="submit" value="Delete Member"></center>
</p>
Just as a quick FYI:
Whenever a method is omitted in a form, it defaults to GET and you're using INPUT_POST therefore you should either be using INPUT_GET or add a post method, i.e: method="post".
Consult the manual:
http://php.net/manual/en/function.filter-input.php
Plus, and for your added safety, your code is open SQL injection. Do use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
in the form tag add "method" attribute:
<form ... method="POST">
In the PHP script you van find the value of inputs in the variable $_GET:
$_GET[Username'']
Kevin
When I run the code no syntax or any error actually ocur but the problem is that the sql query don't seem to be reading the username and password:
here is what I get when I run the code and try to login:
That information is incorrect, try again Click Here
Here is the PHP
<?php
if(isset($_POST["username"]) && isset($_POST["password"])){
$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'");
$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>
You check on $_POST['username'] and $_POST['password'], but use $_SESSION["manager"] and $_SESSION["password"] in your query. Don't you need your $_POST values there?
In your code example, you never assign these post values to these session values.
You are checking if username and password are in the POST request, but then you perform a preg_replace on the session request. I don't think that's right.
if(isset($_POST["username"]) && isset($_POST["password"])){
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_POST["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]);
..
It might be that your mysql_query is not getting executed correctly. Can you print your $sql variable on screen and see if your $manager and $password variables are being output correctly? If so, can you copy that sql query and run in manually in phpmyadmin/ your database client to see if you get desired output?
Another possibility is that you can change the way you write your mysql_query
mysql_query('SELECT id FROM admin WHERE username="' .$manager. '" and password= "' .$password. '";') or die(mysql_error());
So essentially I have this PHP code which is a login system for a webpage not using MySQL but using pre-determined values within the PHP code. I am running php 5.5.3.
The page I have designed is a called access.php. If you enter the pre-defined username and password correctly it takes you through to a user.php page, but if either are incorrect it comes up with an alert box: “Incorrect password or username”
However the problem I am having is that when that alert box comes up it fills the same page (access.php) with grey and the alert box is located within the middle losing all of the initial web page design, and then when you accept the alert box by pressing 'ok' it takes you back to the access.php page design again. I want this alert box to come up over the page I have already designed without losing any of the initial design.
Here is the code for PHP:
<?php
session_start();
if (isset($_POST['username'])) {
// Set variables to represent data from database
$dbUsname = "adminDJ";
$dbPassword = "admin";
$uid = "1111";
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
print 'incorrect username or password.';
}
}
?>
Here is the HTML markup:
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
Is there any way I can have it so PHP either alerts a box within the same page or uses JavaScript to alert a box?
If the above php code is on th esame page access.php then rather than a print set a variable to then use to display a message:
<?php
session_start();
$error = false;
......
} else {
$error = true;
}
then after the form:
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
<?php if($error){ ?>
<div class="error"> There was an issue with the form")</div>
<?php } ?>
or if you want an alert
<?php if($error){ ?>
<script> alert ("There was an issue with the form")</script>
<?php } ?>
Your code does not seem like it should behave how you are describing it but here is an idea using setTimeout():
access.php
<?php
session_start();
if (isset($_POST['username'])) {
// Set variables to represent data from database
$dbUsname = "adminDJ";
$dbPassword = "admin";
$uid = "1111";
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
// use a setTimeout to display the alert after 100ms
print 'setTimeout(function(){alert(\'whatever you want\');}, 100)';
}
}
?>
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
Just cut out of the php put in the JS and then open the php agsin. Put this where you want the box to appear in the code
?><script> alert("incorrect details"); window.history.back();</script><?php
This should work. :)
I am trying to make a simple PHP MySQL login page. I keep reading over the code and can't see what I'm doing wrong. I'm testing with an e-mail and password that I've just looked at in the database as a test so I know it exists. When I click submit on the previous form, it just redirects me back to the same page and doesn't log in (I know this because my header changes with the $_SESSION variables when it works; I know this because my registration page works but not the login once you register). Be aware too that upon registration they enter their first and last name which is why I've included it on the $_SESSION variables on session_start. Here's the code (first the form and the then the checklogin.php page):
<!--THIS IS THE FORM FROM THE PAGE SIGN_IN.PHP-->
<form method="post" target="checklogin.php">
<label for="email">EMAIL/USERNAME:</label>
<input type="text" name="email" id="email">
<label for="password">PASSWORD:</label>
<input type="password" name="password" id="password">
<br />
<input type="submit" value="Let's Play!">
</form>
And this is the checklogin.php script that the form posts to:
<?php
$mysqli = mysqli_connect("mysql_name","login_id","password", "db_name");
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
// username and password sent from form
//NEVER Remove the mysql_real_escape_string. Else there could be an Sql-Injection!
$email=$mysqli->real_escape_string($_POST['email']);
$password=$mysqli->real_escape_string($_POST['password']);
$sql="SELECT * FROM tbl_name WHERE email='$email' and password='$password'";
$result = $mysqli->query($sql);
if(is_object($result) && $result->num_rows == 1){
// Register variables and redirect to file "profile.php"
session_start();
$_SESSION['firstname']=$_POST['firstname'];
$_SESSION['lastname']=$_POST['lastname'];
$_SESSION['email']=$_POST['email'];
$_SESSION['password']=$_POST['password'];
redirect('profile.php');
} else {
echo "Wrong Username or Password";
}
?>
I've also tried this with header('location:profile.php') but with the same results.
<form method="post" action="checklogin.php">
The action attribute is for specifying the URL where you form will be posted. While the target attribute is for specifying where the URL should be loaded.
If the action property is missing, it defaults to the current URL, this is why you are navigating to the same page when you submit the form.
Change Your Form As:
<form method="post" action="checklogin.php">
<label for="email">EMAIL/USERNAME:</label>
<input type="text" name="email" id="email">
<label for="password">PASSWORD:</label>
<input type="password" name="password" id="password">
<br />
<input type="submit" value="Let's Play!">
</form>
Checklogin.php as
<?php
$mysqli = mysqli_connect("mysql_name","login_id","password", "db_name");
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
// username and password sent from form
//NEVER Remove the mysql_real_escape_string. Else there could be an Sql-Injection!
$email=$mysqli->real_escape_string($_POST['email']);
$password=$mysqli->real_escape_string($_POST['password']);
$sql="SELECT * FROM tbl_name WHERE email='$email' and password='$password'";
$result = $mysqli->query($sql);
if(is_object($result) && $result->num_rows == 1){
// Register variables and redirect to file "profile.php"
session_start();
$_SESSION['firstname']=$_POST['firstname'];
$_SESSION['lastname']=$_POST['lastname'];
$_SESSION['email']=$_POST['email'];
$_SESSION['password']=$_POST['password'];
//redirect('profile.php');
header('location:profile.php');
} else {
echo "Wrong Username or Password";
}
?>