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?
Related
In my php script, I have a simple username/ email exists condition, but I want to put the error (should it exist) somewhere in my html, so that I can style it and position it over my form. Echo just puts it top-left. How can I do that? Setting a variable seems like not the optimal solution.
<?php
require('connect.php');
if(isset($_POST["register"])){
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$email = mysqli_real_escape_string($conn, $email);
$conflictUserQuery = "SELECT username FROM members WHERE username='$username'";
$conflictUserResult = mysqli_query($conn, $conflictUserQuery);
$conflictUserRow = mysqli_fetch_array($conflictUserResult, MYSQLI_ASSOC);
$conflictMailQuery = "SELECT email FROM members WHERE email='$email'";
$conflictMailResult = mysqli_query($conn, $conflictMailQuery);
$conflictMailRow = mysqli_fetch_array($conflictMailResult, MYSQLI_ASSOC);
if(mysqli_num_rows($conflictMailResult) ==1){
echo "Could not be registered. Mail exists.";
}
elseif(mysqli_num_rows($conflictUserResult) ==1){
echo "Could not be registered. Username exists.";
}
else{
$registerQuery = mysqli_query($conn, "INSERT INTO members (username, password, email) VALUES ('$username', '$password', '$email')");
if($registerQuery){
echo "Thank You! you are now registered.";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<title>Blog</title>
</head>
<body>
<div class="flex-enable flex-center">
<div class="flex-enable flex-center semiOverride flex-center px100">
<div class="flex-enable flex-center flex-column">
<h2 class="big-white-title">Register.</h2>
<h3 class="medium-white-title">Be a part of this.</h3>
<form class="flex-enable flex-center flex-column" method="POST">
<input class="form-input-text small-white-title" type="text" name="username" placeholder="Username">
<input class="form-input-text small-white-title" type="text" name="password" placeholder="Password">
<input class="form-input-text small-white-title" type="text" name="email" placeholder="e-mail">
<input class="form-button small-white-title" type="submit" name="register" value="Register">
</form>
<h3 class="small-white-subtitle">Or <a id="register" href="">login</a> if you have an account.</h3>
</div>
</div>
</div>
<div id="attribution">Photo by Sebastian Kanczok</div>
</body>
</html>
As I stated in comments:
This could be is as simple as assigning a variable to it then, while using an inline CSS styling method:
$error = "<span style=\"color:red;\">Error message here.</span>";
You could also use a stylesheet with an .error class (that can be used for multiple instances as opposed to an #id) and apply it to an error element and simply place the $error variable where you would like it to appear and with an isset().
Note: The use of isset() is important since it will avoid a possible undefined variable notice.
You could also use a ternary operator:
http://php.net/manual/en/language.operators.comparison.php
which also works quite well for something like this, since you could set a default message for it.
As noted in comments, it'd be better to use a prepared statement and using a safe password storing/hashing method is highly advised.
References:
https://en.wikipedia.org/wiki/Prepared_statement
http://php.net/manual/en/faq.passwords.php
Hi I am trying to make a registration form that sends input data to phpmyadmin's database I created. I think I mixed up MySQLI and MySQL any suggestions on how to fix would be great!! I just dont understand why my data is not being sent over to the database on phpmyadmin.
PHP:
// connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "user logins");
if (isset($_POST['register_btn'])) {
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$emailAddress = mysql_real_escape_string($_POST['emailAddress']);
$password = mysql_real_escape_string($_POST['password']);
$password2 - mysql_real_escape_string($_POST['password2']);
}
if ($password == $password2) {
// create user
$password = md5($password); //hash password before storing for security
$sql = "INSERT INTO user logins(firstName, lastName, emailAddress, password) VALUES('$firstName', '$lastName' '$emailAddress', '$password')";
mysqli_query($db, $sql);
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header('location: homepage.html'); //redirect to homepage
} else {
$_SESSION['message'] = "The two passwords do not match";
}
?>
HTML:
<link rel="stylesheet" type="text/css" href="custom.css">
<body class="background">
<div>
<h1 class="header1">Sign in Below</h1>
</div>
<div>
<form action="connect.php" method="post">
<div>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</div>
<div>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</div>
<div>
<label for="emailAddress">Email Address:</label>
<input type="email" name="email" id="emailAddress">
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<div>
<label for="password2">Repeat Password:</label>
<input type="password" name="password2" id="password2">
</div>
<input type="submit" name="register_btn" value="register">
</form>
</div>
</body>
Have you put in a password?
Is your database on your local machine?
Is your database table called user logins (with a space)
Is root your login?
Is your PHP file called connect.php?
Any error messages?
What happens when you click the form button
Sorry just a few things that crossed my mind that might help determine the problem.
You may just need to remove the following curly bracket
$password2 - mysql_real_escape_string($_POST['password2']);
}
and add it at the end of you file so it runs with your isset() function
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
I don't think "user logins" is a valid table name. Change it to "user_logins", or at the very least, use the quote ` around the table name.
INSERT INTO `user logins`(
OR
INSERT INTO user_logins(
Second one you have to rename the table in phpmyadmin. As a general rule, you want to quote table names no matter what. Because sometimes your table name is a MySQL-reserved keyword. It's just good practice.
Also, the 4th parameter in mysqli_connect is database name. So is your database named "user logins"? Don't confuse table name with database name.
solved:(a small mistake)
this line is not a assignment :
$password2 - mysql_real_escape_string($_POST['password2']);
to
$password2 = mysql_real_escape_string($_POST['password2']);
( - ) must be converted to (=)
I am trying to create a user registration form using php and mysql. When I try to hit the submit button no new record is added to my database. The database is functional and has worked with other forms.
HTML/FORM
<?php
include 'header.php';
?>
<section>
<div class="form">
<form action="signup.php" method="post">
<h1> Sign Up!</h1>
<p>First name:
<input type="text" name="fName" maxlength="15" required pattern="^[a-zA-Z]{3,20}$" placeholder="Enter Name" />
</p>
<p>Last name:
<input type="text" name="lName" maxlength="15" pattern="^[a-zA-Z]{3,20}$" required placeholder="Enter Last Name" />
</p>
<p>Email:
<input type="email" name="email" maxlength="40" required placeholder="Enter Email" />
</p>
<p>Username:
<input type="text" name="username" maxlength="20" ^[A-Za-z0-9_]{1,15}$ required placeholder="Enter Username" />
</p>
<p>Password:
<input type="password" name="password" maxlength="20" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required placeholder="Enter Password" />
</p>
<p>Re-type Password:
<input type="password" name="password2" maxlength="20" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required placeholder="Re-type Password" />
</p>
<p>
<button type="submit" name="signupbutton"> Sign up </button>
</p>
</form>
</div>
</section>
<div class="footerspecial">
<?php
include 'footer.php';
?>
</div>
PHP/SQL
<?php
//have they submitted at least once?
if(isset($POST['$password2'])){
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
//do the passwords NOT match?
if ($password !== $password2) {//do string comparison here
echo'<h2>Error: passwrods don\'t match!</h2>';
require ('registerform.php');
}
else {
//does the username already exist?
$sql = mysql_query("SELECT * FROM users WHERE username=='$username'");
if ($results=$con->query($sql)){
echo'<h2>Error: username is already taken</h2>';
require ('registerform.php');
}
else {
$sql = mysql_query("SELECT * FROM users WHERE email=='$email'");
if ($results=$con->query($sql)){
echo'<h2>Error: email already used</h2>';
require ('registerform.php');
}
else {
// If the values are posted, insert them into the database.
$sql= "INSERT INTO users (fName, lName, email, username, password, password2) VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
if (!$con->query($sql)){
echo 'Error: coulndt do suff';
}
else {
echo 'Account made';
}//ENDS SUCCESSFUL INSURT
}//ENDS EMAIL VALIDATION
}//ENDS THE USERNAME VALIDATION
}//END PASSWORD VALIDATION
}
?>
Picture of the form don't really know if its helpful but ya'know
https://gyazo.com/418b86ecb5090604a1f229e1e94fe3bf
I'm guessing here that your database doesn't have a password2 column (seems kind of pointless to have) so trying to insert into it will give an error.
You should read about MySQLi error reporting
Also add error_reporting(-1); at the start of your PHP file to show PHP errors.
P.S. your code is vulnerable to SQL injection, you should use prepared statements to be safe from this.
Could have multiple problems first you do not have the single quotes around $password2. This could be leading to a failed insert.
VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
Also I would echo the sql errors out as you are not doing. you can do this easily. Test the if statement for a true not a false
if ($con->query($sql)){
//if true then runs your code;
}
else {
echo "Error: " . $sql . "<br>" . $con->error; // This will echo out any sql errors you may have
}
My code works perfect with correct data. But when is invalid value in field, it shows an error message with link on page register.php and when I click on this error, it redirects to register form, but there is empty form and all values must be inserted again. I want that valid values are displayed after error and invalid not.
Code:
<html>
<head>
<?php include 'connect.php'; ?>
<?php include 'functions.php'; ?>
<meta charset="UTF-8">
<title>TechnoLab-Registracija</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<?php include 'header.php'; ?>
</head>
<body>
<div id="container">
<div id="left">
<?php include "kategorije.php";?>
</div>
<div id="right">
<?php include "loggedin.php";?>
</div>
<form method="post" id='registerform'>
<br/>
<?php
if(!empty($_POST['username']) && !empty($_POST['password']) )
{
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = md5(mysqli_real_escape_string($con, $_POST['password']));
$email = mysqli_real_escape_string($con, $_POST['email']);
$confirm_email = mysqli_real_escape_string($con, $_POST['confirm_email']);
$ime = mysqli_real_escape_string($con, ucfirst($_POST['ime']));
$prezime = mysqli_real_escape_string($con, ucfirst($_POST['prezime']));
$oib = mysqli_real_escape_string($con, $_POST['oib']);
$ulica = mysqli_real_escape_string($con, $_POST['ulica']);
$mjesto = mysqli_real_escape_string($con, $_POST['mjesto']);
$checkusername = mysqli_query($con, "SELECT * FROM korisnici WHERE Username = '".$username."' OR Oib = '".$oib."'");
if(mysqli_num_rows($checkusername) == 1)
{
echo " <p><a class='one' href=\"register.php\">Unesite drugo korisničko ime!</p>";
exit();
}
$checkusernamelenght = checkusernamelenght($username);
if(!$checkusernamelenght){
echo ' <p><a class="one" href="register.php">Korisničko ime minimalno 4 znaka i ne smije sadržavati razmake između slova!</a></p>';
exit();
}
if (preg_match("/^.*(?=.{6,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST['password']) === 0){
echo ' <p><a class="one" href="register.php">Lozinka mora imati barem 6 znakova i sadržavati mala i velika slova te broj!</a></p>';
exit();
}
$checkemail = mysqli_query($con, "SELECT * FROM korisnici WHERE Email = '".$email."'");
if(mysqli_num_rows($checkemail) == 1)
{
echo " <p><a class='one' href=\"register.php\">Unesite drugu email adresu!</p>";
exit();
}
if ($confirm_email!=$email){
echo " <p><a class='one' href=\"register.php\">Vaše email adrese se ne podudaraju!</a></p>" ;
exit();
}
$validateEmail = validateEmail($email);
if(!$validateEmail){
echo " <p><a class='one' href=\"register.php\">Unesite ispravan format emaila!</a></p>";
exit();
}
$checkOib = checkOib($oib);
if(!$checkOib){
echo " <p><a class='one' href=\"register.php\">Unesite ispravan OIB !</p>";
exit();
}
else{
$registerquery = mysqli_query($con, "INSERT INTO korisnici VALUES('', '$username', '$password', '$email', '$confirm_email', '$ime', '$prezime', '$oib', '$ulica', '$mjesto', 'user')");
if($registerquery)
{
header('location: index');
}
}
}
else
{
?>
<br/>
<div id="reg">
<label for="username">Korisničko ime:</label><input type="text" name="username" required /><br />
<label for="password">Lozinka:</label><input type="password" name="password" maxlength="20" required /><br />
<label for="email">Email:</label><input type="text" name="email" required /><br />
<label for="confirm_email">Potvrdi email:</label><input type="text" name="confirm_email" required /><br />
<label for="ime">Ime:</label><input type="text" name="ime" required /><br />
<label for="prezime">Prezime:</label><input type="text" name="prezime" required /><br />
<label for="oib">OIB:</label><input type="text" name="oib" required /><br />
<label for="ulica">Ulica i kućni broj:</label><input type="text" name="ulica" required /><br />
<label for="mjesto">Mjesto i poštanski broj:</label><input type="text" name="mjesto" required /><br />
<br/>
<input type="submit" name="register" id="register" value="Registracija" />
</div>
</form>
<?php
}
?>
</div>
<?php include "footer.php";?>
</body>
</html>
Is it possible do that only with php or must be javascript or something else?
I've searched on forum and tried with this and similar code but it doesn't work.
<input type="text" name="login" value="<?php if(isset($_POST['login'])){ echo $_POST['login'];}?>">
I appreciate any help!
The $_POST['<value>'] doesn't work because of the redirect, it "drops" the $_POST data.
One way to achieve the desired functionality is to use $_SESSION when the form has been submitted you can store the values in the $_SESSION, or you might prefer to only store them if there's a error.)
You can store/save the values in $_SESSION like so:
$_SESSION['name'] = $_POST['name'];
And then simply check for the $_SESSION['<value>'] instead of the $_POST['<value>'].
<input type="text" name="login" value="<?php if(isset($_SESSION['login'])){ echo $_SESSION['login'];}?>">
You'd have to remember to start the session at the top of each page you want to use sessions on.
session_start();
One thing to be aware of is that you should unset the session values after you are done with them, so you avoid old data being reused.
There are plenty of ways you can use $_SESSION to achieve what you want so it's all about finding the way that suits you best.
You can read more about sessions here
best way is to create session array for complete data and if it is not empty show it in your fields. other method is to pass that post array back to your view when redirecting after invalid values.
hope you will understand.
If you just want the register.php script to fill the fields, simply send the needed info to this script:
$param = "?user=".urlencode($_POST['user']);
$param .= "&email=".urlencode($_POST['user']);
//...concat all needed param here
echo " <p><a class='one' href=\"register.php".$param."\">Unesite drugo korisničko ime!</p>";
Then in your register.php script, just read the $_GET['...'] values to populate your form. don't forget to urldecode() them.
Note: For obvious security reasons, DO NOT pass the password in the GET parameters (nor store it in a $_SESSION variable).
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>