I'm having trouble with <?php echo $_SERVER['PHP_SELF']; ?>. For some reason this line in my HTML form removes my $_GET variables (that I manually put into place) from the URL.
To understand my problem here is my register.php code:
<?php
session_start();
// IF USER NOT REMEMBERED(DID NOT CLICK REMEBER ME BUTTON) OR NO SESSION IS FOUND THEN THROW HIM OUT TO LOGIN
//SECURITY SO THAT USERS CANT ACCESS WEB URL DIRECTLY
$host="localhost"; // Host name
$username="user"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="temp_table"; // Table name
// Connect to server and select databse.
$link_temp = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db($db_name, $link_temp);
$results=mysql_query("SELECT temporary_password, temporary_username FROM $tbl_name WHERE temporary_username = '".$_GET['temp_username']."'");
$row = mysql_fetch_array($results);
if($_GET['temp_password'] != $row['temporary_password'] || $_GET['temp_username'] != $row['temporary_username']){
mysql_close();
header("Location: index.php?invalid_user=1");
}
elseif (empty($_GET['temp_password']) || empty($_GET['temp_username']) || empty($_GET)) {
mysql_close();
header("Location: index.php?invalid_user=1");
}
if(isset($_POST['submit']))
{
//retrieve our data from POST
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 != $pass2){
echo '<div class="alert">Passwords do not match!</div>';
die();
}
$encrypted_mypassword = md5($pass1);
$dbhost = "localhost";
$dbname = "dbname";
$dbuser = "user";
$dbpass = "password"; //not really
$link_users = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname, $link_users);
//sanitize values before entering into database
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$firstname = ucfirst(strtolower($firstname));
$lastname = ucfirst(strtolower($lastname));
$query = "INSERT INTO users ( firstname, lastname, username, password)
VALUES ('$firstname' , '$lastname' , '$username' , '$encrypted_mypassword');";
mysql_query($query);
mysql_close();
echo '<div class="info">User Successfully Created!</div>';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Secure Customer Login</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/structure_register.css">
<link href='https://fonts.googleapis.com/css?family=Nothing+You+Could+Do' rel='stylesheet' type='text/css'>
<script>document.createElement('footer');</script>
</head>
<body>
<div class="img">
<img src="images/logo.png" />
</div>
<form class="box login" style="max-width:334px;" name="register" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset class="boxBody">
<label>First Name</label>
<input type="text" name="firstname" maxlength="50" tabindex="1" placeholder="First Name" required />
<label>Last Name</label>
<input type="text" name="lastname" maxlength="50" tabindex="2" placeholder="Last Name" required />
<label>Username</label>
<input type="email" name="username" maxlength="50" tabindex="3" placeholder="Email" required/>
<label>Password</label>
<input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER and lowercase and numbers' : ''); if(this.checkValidity()) form.pass2.pattern = this.value;" placeholder="Password" name="pass1" tabindex="4" />
<label>Repeat Password</label>
<input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Repeat Password" name="pass2" tabindex="5" />
</fieldset>
<footer>
<center><input type="submit" name="submit" value="Register" class="btnLogin" /></center>
</footer>
</form>
<footer id="main">
© 2014 Rye High Group. All rights reserved.</a>
</footer>
</body>
</html>
Basically the register.php page on my website gets an input from a link that contains two get variables: temp_username and temp_password. So the link that is used to access the site looks like this: my_domin.ca/register.php?temp_username=SomeUser1&temp_password=Somepassword1
The get variables are compared to entries in the database and if they return true the user is granted access to register.php, otherwise he will be forwarded to index.php. Accessing register.php is no problem, but as soon as the form is submitted the $_GET variables are removed from the URL thus forwarding the user to index.php
My question is: How can I modify <?php echo $_SERVER['PHP_SELF']; ?> to stop removing GET variables
P.S. I will transition to mysqli as soon as I get basic functionality working on my site (since I know mysql_* the best and want to reduce errors in the transition period)
$_SERVER['REQUEST_URI'] : The URI which was given in order to access this page.
Reference
Your form should be like:
<form action="<?php echo $_SERVER['REQUEST_URI'] ?>">
your inputs
</form>
Related
I have 2 html forms. first page is registration page and next is login page. I managed to send the input from registration page to mysql using a php file named connect.php. the 'proceed' button in registration page will navigate to the php file but now i want the 'proceed' button in registration page link to login page and not the connect.php file nd update mysql. i tried putting the connect.php's codes into the registration page's html code but it didnt seem to work. Where should i put the php code in my html code and am i suppose to use bootstrap?
this is my connect.php code:
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "ktm_member";
//Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (!empty($username))
{
if (!empty($password))
{
if (mysqli_connect_error())
{
die ('Connect error('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else
{
$sql = "INSERT INTO `member list`(`name`, `age`, `gender`, `email`, `username`, `password`) VALUES ('$_POST[name]', '$_POST[age]', '$_POST[gender]', '$_POST[email]', '$_POST[username]', '$_POST[password]')";
if ($conn->query($sql))
{
echo "New record added successfully.";
}
else
{
echo "Error".$sql."<br>".$conn->error;
}
$conn->close();
}
}
else
{
echo "Password should not be empty";
}
}
else
{
echo "Username should not be empty";
die();
}
?>
and this is my registration page html code:
<!doctype html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./W3.CSS Template_files/w3.css">
<link rel="stylesheet" href="./W3.CSS Template_files/css">
<link rel="stylesheet" href="style.css">
<style>
body,h1 {font-family: "Raleway", sans-serif}
body, html {height: 100%}
.bgimg {
background-image: url('forestbridge.jpg');
min-height: 100%;
background-position: center;
background-size: cover;
}
</style>
</head>
<body><div class="bgimg w3-display-container w3-animate-opacity w3-text-white"><div class="w3-display-middle">
<center><h2>Register</h2></center>
<form name="form1" method="post" action="welcomeloginpage.php" autocomplete = "off">
<p class="w3-large w3-center">
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Your full name" autofocus required>
</p>
<p class="w3-large w3-center">
<label for="age">Age: </label>
<input type="number" name="age" id="age">
</p>
<p class="w3-large w3-center">
<label for="gender">Gender: </label>
<input type="radio" name="gender" value="M"> Male
<input type="radio" name="gender" value="F"> Female<br> <id="gender">
</p>
<p class="w3-large w3-center">
<label for="email">Email: </label>
<input type="email" name="email" id="email" placeholder="xxx#xx.xx">
</p>
<p class="w3-large w3-center">
<label for="username">Username: </label>
<input type="text" name="username" id="username">
</p>
<p class="w3-large w3-center">
<label for="password">Password: </label>
<input type="password" name="password" id="password" maxlength="10" placeholder="password" data-toggle="password">
</p>
<p style="text-align: center;">
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
If you want your connect.php script to send the user to another page if the registration is successful then you use a header() command like this
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "ktm_member";
//Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (!empty($username)) {
if (!empty($password)) {
if (mysqli_connect_error()) {
die ('Connect error('.mysqli_connect_errno().')'
.mysqli_connect_error());
} else {
// this query style is very dangerous see note below
$sql = "INSERT INTO `member list`
(`name`, `age`, `gender`,
`email`, `username`, `password`)
VALUES ('$_POST[name]', '$_POST[age]', '$_POST[gender]',
'$_POST[email]', '$_POST[username]', '$_POST[password]')";
if ($conn->query($sql)) {
// remove echo as you will never see it now
//echo "New record added successfully.";
header('Location: otherPage.php');
exit; // important as header does not stop code execution in this script
} else {
echo "Error".$sql."<br>".$conn->error;
}
$conn->close();
}
} else {
echo "Password should not be empty";
}
} else {
echo "Username should not be empty";
die();
}
?>
You do have at least 2 serious flaws in this code though that I must mention.
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
Never store plain Text password in your database. The most likely place where these things get compromised is from within the company running this database. An unhashed password is a total givaway for a DB Admin who just got refused a pay rise!
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords
If you are using a PHP version prior to 5.5 there is a compatibility pack available here
How would I make it so on the user being registered they get redirected to a different page. Ive tried most things, and yes it registers fine but im just struggling with this one bit D:
regsister.inc.php
<?php
//Start session:
session_start();
//Include db settings and create a connection:
include("config.inc.php");
//Create variable for username input and prevent sql injections:
$username = mysql_real_escape_string($_POST['usern2']);
//Create variable for password input, prevent sql injections and hash it with md5:
$password = mysql_real_escape_string(md5($_POST['pass2']));
//Select matching username and password from admin table based on input:
$sql = "INSERT INTO admin VALUES('$username', md5('$password'))";
//$sql = "SELECT * FROM admin WHERE username = '$username' AND password = '$password'";
//Execute query to db:
$execute = mysql_query($sql);
if (mysql_num_rows($execute) == 1) {
$_SESSION['user'] = $username;
echo "<p>Register Successful</p>";
}
register.php
<?php
include ("includes/register.inc.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="container">
<?php echo $errormsg; ?>
<h2>Register</h2>
<form method="post" action="register.php">
<label>Username: </label>
<input type="text" size="25" name="usern2" value=""><br>
<label>Password: </label>
<input type="password" size="25" name="pass2" value=""><br>
<input type="submit" value="Register!">
</form>
</div>
</body>
</html>
Much help would be appreciated, dont roast me im new to PHP D:
This question already has answers here:
Fatal error: Cannot use isset() on the result of an expression
(3 answers)
Closed 6 years ago.
I am creating a simple registration form, I have created all files needed to make complete form registration and login. registration should have Firstname, Lastname, username and password, I have tested with two parameters meaning username and password my codes works perfectly but when I add more parameters eg Firstname and Lastname I get error: Fatal error: Cannot use isset() on the result of an expression
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Registration</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<?php
#include database connection files
require('db.php');
//inserting data to our database
// If form submitted, insert values into the database.
if(!isset($_REQUEST['username'] || $_REQUEST['Firstname'] || $_REQUEST['Lastname'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$Firstname = stripslashes($_REQUEST['Firstname']);
$Firstname = mysqli_real_escape_string($con,$Firstname);
$Lastname = stripslashes($_REQUEST['Lastname']);
$Lastname = mysqli_real_escape_string($con,$Lastname);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, Firstname, Lastname, password, email, trn_date)
VALUES ('$username',Firstname,Lastname, '".md5($password)."', '$email', '$trn_date')";
$result = mysqli_query($con,$query);
if($result){
echo "<div class='form'>
<h3>You are registered successfully.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}
else{
?>
<div class="form">
<h1>Registration</h1>
<form name="registration" action="" method="post">
<input type="text" name="Firstname" placeholder="Firstname" required/>
<input type="text" name="Lastname" placeholder="Lastname" required/>
<input type="text" name="username" placeholder="Username" required />
<input type="email" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
</div>
<?php } ?>
</body>
</html>
Unfortunately, I can't figure it out , what is wrong with my code?
Haven't done PHP in a while, but my guess is that you need to change this:
if(!isset($_REQUEST['username'] || $_REQUEST['Firstname'] || $_REQUEST['Lastname'])){
with this:
if(!isset($_REQUEST['username']) || !isset($_REQUEST['Firstname']) || !isset($_REQUEST['Lastname'])){
actually you probably want the opposite of that, given that you want to only save if all the data is available right?
I want to create a working login form. Here's what I have done and this displays cannot select db.
Edited login.php file
<?php
error_reporting(E_ALL);
//Connection Variables:
$dbhost = "localhost";
$dbname = "";
$dbuser = "";
$dbpass = "";
try{
//Connection to SQL:
$conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
//Error messagin enabled:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$user = '';
$pass = '';
$sum = 0;
$error_msg = "Please type a username and a password";
if(isset($_POST['login']))
{
//Start a session:
session_start();
$user = $_POST['email'];
$pass = $_POST['password'];
if(empty($user) && empty($pass))
{
echo $error_msg;
$pass = '';
}
if(empty($user) || empty($pass))
{
echo $error_msg;
$user = '';
$pass = '';
}
if(!empty($user) && !empty($pass))
{
//SQL:
$query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
$query->bindParam(":u", $user);
$query->bindParam(":p", $pass);
//Execute query:
$query->execute();
$number_rows = $query->fetch(PDO::FETCH_NUM);
if($number_rows>0)
{
echo $user;
$_SESSION['usern'] = $user;
$_SESSION['passw'] = $pass;
header("Location: ./pages/home.php");
}
//echo $user;
else
{
echo "Invalid username or password";
header("Location: index.html");
}
}
}
if(!isset($_POST['login']))
{
echo "Login button not clicked";
}
?>
I read more and more articles on this, still I can't find a solution.
Edited HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Signin for OTMS</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="signin.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form action="login.php" method="post" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
</form>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
Please help me to find what is the error.
I created my database using phpMyAdmin and it's in localhost. And interfaces I designed using Bootstrap.
This is the error I'm getting now:
database name- otmsdb
table name- login
email, passowrd,
button name- login
Sir, your code is vulnerable to SQL injections. Please start using MySQLi or PDO. Here is a PDO code for login that should works fine with you:
Source: Udemy Online course.
EDIT: use this code, and change the variables into yours
<?php
session_start();
if(isset($_POST['login'])){
$errmsg_arr = array();
// configuration
$dbhost = "localhost";
$dbname = "your database name";
$dbuser = "your username";
$dbpass = "your password";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// new data
$user = $_POST['username'];
$password = $_POST['password'];
if($user == '') {
$errmsg_arr[] = 'You must enter your Username';
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
}
// query
if (!$errmsg_arr) {
$result = $conn->prepare("SELECT * FROM login WHERE username= :user");
$result->execute(['user' => $username]);
$row = $result->fetch(PDO::FETCH_NUM);
if($row && password_verify($_POST['password'], $row['password']) {
$_SESSION['user'] = $row;
header("location: ./pages/home.php");
exit;
}
else{
$errmsg_arr[] = 'Username and Password are not found';
}
}
}
?>
HTML FORM:
<body>
<?php foreach($errmsg_arr as $msg): ?>
<?=htmlspecialchars($msg, ENT_QUOTES) ?><br>
<?php endforeach ?>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" value="<?=htmlspecialchars($user, ENT_QUOTES)?>" />
<input type="password" name="password" placeholder="password" value="<?=htmlspecialchars($password, ENT_QUOTES)?>"/>
<input type="submit" name="login_submit" value="login"/>
</form>
</body>
Suggestions:
echo mysql_error() to determine why the error is occurring:
mysql_select_db("$db_name") or
die("cannot select DB: " . mysql_error());
Stop using deprecated functions " mysql_connect()", "mysql_query()" and friends. You'd be much better served with mysqli instead.
Use Prepared Statements instead of building your "select" directly from your POST parameters.
So I have a Login and a Create account form. The create account system works perfectly, sending all the information to mySQL database.
Now, I have written a 'login_user.php' script, which connects to the database, fetches the values of a registered user, and outputs the correct message according to correct or incorrect user input. It looks like the operation runs through the whole code and outputs the last message 'Invalid username or password' every single time, even when there is no input, or wrong username/passwords entered. Below I will provide all of my login form php code. Can you spot any mistakes? Please let me know if you would like a reference to a specific part of the html code.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$query = mysql_query("SELECT * FROM Client_Information WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows != 0){
while($row = mysql_fetch_assoc($query)){
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername){
if($password==$dbpassword){
echo "You are logged in.";
}else{
echo "Invalid password.";
}
}else{
echo "Invalid username.";
}
}else{
echo "This name does not exist.";
}
}else{
echo "Invalid username or password.";
}
?>
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1,IE=edge" />
<title>LOGIN</title>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="logo"></div>
<div class="login-block">
<h1>Log In</h1>
<form action="login_check.php" method="post">
<input type="text" value="" placeholder="Username" id="username" name="username" />
<input type="password" value="" placeholder="Password" id="password" name="password" />
<button>Log In</button>
Sign Up for New Account?
</form>
</div>
</div>
</body>
</html>
When using $_POST for PHP, you have to reference the input's name attribute, not its id attribute.
<input type="text" value="" placeholder="Username" id="name" name="name" />
<input type="password" value="" placeholder="Password" id="password" name="password" />