I'm currently writing a script that preforms basic user registration.
When the user arrives on the landing page, I have a JS script that identifies their email from the URL and fills it in the email input box (which is disabled). After, the user just needs to put in their password to create an account. However, PHP throws the error "Email is required" even though it's been filled by the JS script.
I've tried to change the status of the input box to disabled to enabled which doesn't do much to help. I've attached the files involved in the process below. Any help would be greatly appreciated.
fillEmail.js
$(document).ready(function() {
var link = window.location.href;
var emailIndex = link.indexOf("email");
if(emailIndex != -1) {
link = link.substring(emailIndex + 6);
} else {
link = "";
}
document.getElementById("email").value = link;
//$('#email').attr('disabled', 'disabled');});
register.php
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div hidden class="input-group">
<label>Username</label>
<input type="text" name="username" value="user">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" id="email" value="<?php echo $email; ?>" disabled>
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
</form>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous">
</script>
<script type='text/javascript' src="fillEmail.js"></script>
</html>
server.php
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
?>
I'm fairly new to PHP so any help would be greatly appreciated. Thanks so much in advance!
As per my comment, you can simply use readonly instead of disabled to achieve a similar effect. Also please use prepared statements to protect against SQL injection. mysqli_real_escape_string is not enough
In order for the value to be submitted the field cannot be disabled.
Simple solution, create another fields as (hidden), these are submitted
<input type="email" id="email" value="<?php echo $email; ?>" disabled>
<input type="hidden" name="email" value="<?php echo $email; ?>">
Or you could simply change the attribute from disables to readonly
Related
This is my code, I really don't know whats wrong does anyone else know? Currently the error that comes up is Oops! Something went wrong. Please try again later. I know that the issue is not a connection issue and is not a permissions issue. I'm really confused about what I've done wrong and have even contacted customer support multiple times and they didn't know what the issue is.
<?php
include ('config.php');
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT username FROM users WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location:Login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>
So, I am trying to retrieve data from my mysql database after a user registers or logins. The thing is that it somehow retrieves the letter "u" and that's weird, because there is no place that contains the letter "u".
This is the result I am getting as of now
https://imgur.com/t3XBrPN
index.php(where user registers or logs in)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function start(){
closeForm();
closeRegForm();
}
function openForm() {
document.getElementById("myForm").style.display = "block";
closeRegForm();
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
function openRegForm() {
document.getElementById("myRegForm").style.display = "block";
closeForm();
}
function closeRegForm() {
document.getElementById("myRegForm").style.display = "none";
}
</script>
</head>
<body onload="start()">
<nav>
<button class="button" type="submit" onclick="openForm()">Влез</button>
<button class="buttonReg" type="submit" onclick="openRegForm()">Регистрирай се</button>
<img src="Logo4.png" class="Logo" alt="Logo">
</nav>
<div class="form-popupRegister" id="myRegForm">
<form method="post" action="server.php" class="form-containerReg">
<h1>Регистрирация</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" placeholder="Въведете името на лейдито" value="<?php echo $username; ?>">
<label for="email"><b>Е-майл</b></label>
<input type="email" name="email" placeholder="Въведете e-mail" value="<?php echo $email; ?>">
<label for="password_1"><b>Парола</b></label>
<input type="password" placeholder="Въведете парола" name="password_1">
<label for="password_2"><b>Повторете Парола</b></label>
<input type="password" placeholder="Въведете парола повторно" name="password_2">
<button type="submit" class="btnReg" name="reg_user">Register</button>
<button type="button" class="btn-cancelReg" onclick="closeRegForm()">Close</button>
</form>
</div>
<div class="form-popup" id="myForm">
<form method="post" action="server.php" class="form-container">
<h1>Влизане</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" value="<?php echo $username; ?>">
<label for="password"><b>Парола</b></label>
<input type="password" name="password">
<button type="submit" class="btn" name="login_user">Login</button>
<button type="button" class="btn-cancel" onclick="closeForm()">Close</button>
</form>
</div>
</body>
</html>
index2.php(where the data should be output)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function getUserStats(){
<?php
$queryThree = "SELECT * FROM `register` WHERE ID='$idQuery' ";
$userStats = mysqli_query($db,$queryThree);
$userStatsTwo = mysqli_fetch_assoc($userStats);
?>
}
</script>
</head>
<body onload="getUserStats()">
<div class="navWrapper">
<div class="statistics">
<div class="profilePicture" name="profilePicture">
<label class="profilePictureLabel" for="profilePicture"><b><?php echo userStatsTwo['username']; ?></b></label>
</div>
<div class="money" name="money">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['money']; ?></b></label>
</div>
<div class="diamond" name="diamond">
<label class="diamondLabel" for="diamond"><b><?php echo userStatsTwo['diamonds']; ?></b></label>
</div>
<div class="ruby" name="ruby">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['ruby']; ?></b></label>
</div>
<div class="level" name="level">
<label class="levelLabel" for="level"><b>Level:<?php echo userStatsTwo['level']; ?></b></label>
</div>
</div>
</div>
</body>
</html>
server.php(where the data is being processed)
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$idQuery = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'id9159890_uregisterdb', 'censored', 'id9159890_registerdb');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM `register` WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO `register` (username, password, email, money, ruby, diamonds, levelpoints, level)
VALUES ('$username', '$password', '$email', '0', '0', '0', '0', '0')";
mysqli_query($db, $query);
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}
}
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM `register` WHERE username='$username'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The results that I should be getting are(from top to bottom and left to right)
Username, Level, Money, Diamond, Ruby and their values should respectively be Username, 0, 0, 0, 0.
I've tried everything and nothing changes, I've re-constructed my code twice and it still outputs only that and nothing else.
You have an issue here in your code:
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
As i mentioned in my comment, check what are you getting in echo "SELECT * FROM register WHERE ID='$idQuery' "; you definitely getting this kind of result:
SELECT * FROM register` WHERE ID= 'SELECT ID FROM `register` WHERE username='somename''
For sub query, remove quotes around your variable from:
"SELECT * FROM register` WHERE ID='$idQuery' ";
should be:
"SELECT * FROM register` WHERE ID = $idQuery";
Note that, this is success case, as you show your result here https://imgur.com/P64hqvI, your query is working fine..
You also need to use some protection for $idQuery if $idQuery == '' then your you can't get any result also.
As #patrick-q mentioned, use session to store username or ID instead of saving a full query.
Second, you code is wide open for SQL injection, for preventing, use PDO.
Some helpful links:
Are PDO prepared statements sufficient to prevent SQL injection?
How can I prevent SQL injection in PHP?
I am trying to create website with login form with some PHP code, were user will try to login with username and password and page will then show "welcome....". AT the moment when user try to put username and password website that shows up is blank, nothing is on it. Also i already have created mysql database with username and password.
this login form on my main page index.html:
<form id="form" method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" name="username" size="15" required="required" />
<label for="password">Password:</label>
<input type="password" name="password" size="15" required="required" />
<input id="loginButton" type="submit" name="submit" value="LOGIN" />
</form>
and this is my php page login.php:
<?php
session_start();
$host = "localhost";
$username = "*******";
$password = "*******";
$db_name = "********";
$tbl_name = "users";
$conn = mysql_connect("$host", "$username", "$password") or die("Cannot connect");
mysql_select_db("$db_name", $conn) or die("Cannot connect");
$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$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("username");
session_register("password");
header("location:page1.html");
} else {
echo "Wrong Username or Password";
}
?>
and on my welcome page - page1.html i have included some php code:
<?php
session_start();
if(!session_is_registered(username)){
header("location:index.html");
}
?>
First off...dont store the password in the session. Thats just asking for trouble.
session_register("password");
Secondly....session_register() is a deprecated function and shouldn't be used anymore.
Instead do...
$_SESSION['username'] = $myusername;
Third....
header("location:page1.html");
Should be a PHP file if you want sessions to work across pages..
header("location:page1.php");
Then in that PHP page do...
session_start();
if(!isset($_SESSION['username'])){
header("location:index.php");
} else {
// Display stuff to logged in user
}
here's the code guys please help me
if mysqli_num_rows==false Than code works but why num rows doesn't work i can't get it i tried everything but same error appears
<?php
//Start session
session_start();
//Include database connection details
require_once('db.php');
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
$query="SELECT * FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($con,$query);
if($row=mysqli_num_rows($result)==1){
mysqli_fetch_array($con,$result);
echo 'Logged in';
header('location:profile.php');
}
else{
echo 'error occured';
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
session_start();
require_once('db.php');
if(!empty(trim($_POST['username'])) && !empty(trim($_POST['password']))){ // check with posetd value
$user_name = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$query = "SELECT * FROM users where username='$username' and password = '$password'"; // don't use plain password, use password hashing mechanism
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)>0){ // if data comes
// here do some data assignment into session
header('location:profile.php'); // go to other page
}else{
echo "Login creadentials are not correct"; // else no user is there with the given credentials
}
}else{
echo "please fill the form value";
}
?>
Note:-
Read and use prepared statements to prevent your code from SQL Injection. :-http://us.php.net/manual/en/mysqli-stmt.prepare.php
Above file extension must be .php
Merry Christmas everyone. I'm building a small landing page and i have a form in it. I have monetized this form with CPA offers, what i would like to happen is to get the user input AFTER the content locking widget has closed.
I tried many ways but im having errors, and the form submits itself once you click the button and the user doesn't haves to complete the offers.
The javascript function i have to call is call_locker();
How can i submit my form after the call_locker(); function is completed?
index.php
<html>
<head>
<meta charset="UTF-8">
<title>Complete a survey to become part of our team.</title>
<!-- Start of content locker code -->
<noscript><meta http-equiv="refresh" content="0;url=https://www.appcaptcha.com/contentlockers/noscript.php" /></noscript>
<script type="text/javascript">var ogblock=true;</script>
<script type="text/javascript" src="https://www.appcaptcha.com/contentlockers/load.php?id=76db12dda6691911c8a119fe7043facd"></script>
<script type="text/javascript">if(ogblock) window.location.href = "https://www.appcaptcha.com/contentlockers/adblock.php";</script>
<!-- End of content locker code -->
</head>
<body>
<?php
$userErr ="";
$emailErr ="";
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=user-empty') !== false) {
$userErr ="Please enter your username!";
}
if (strpos($url, 'error=email-empty') !== false) {
$emailErr ="Please enter your email!";
echo $emailErr;
}
if (strpos($url, 'error=email-incorrect') !== false) {
$emailErr ="Please enter a valid email!";
echo $emailErr;
}
if (strpos($url, 'error=succes') !== false) {
$entry = 'You have entered succesfully!';
}
?>
<h1> Please enter the following info: </h1>
<form method="post" action="enter.php">
Username: <input type="text" name="username" placeholder="Username" /> <br>
<span class="error"><?php echo $userErr ?></span><br>
E-mail: <input type="text" name="email" placeholder="E-mail" /><br>
<span class="error"><?php echo $emailErr ?></span><br>
Social Media: <input type="text" name="smedia" placeholder="Enter your Facebook, twitter, Skype, profile URL" /> (Optional)<br>
<input type="submit" value="Enter" />
<?php echo $entry ?>
</form>
</body>
</html>
enter.php
<?php
include 'connect-mysql.php';
$username = $_POST['username'];
$email = $_POST['email'];
$smedia = $_POST['smedia'];
if(empty($username)) {
header("Location: index.php?error=user-empty");
exit();
}
if(empty($email)) {
header("Location: index.php?error=email-empty");
exit();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: index.php?error=email-incorrect");
exit();
}
else {
$sql = "INSERT INTO user (username, email, socialmedia) VALUES ('$username', '$email', '$smedia')";
$result = mysqli_query($dbcon, $sql);
header("Location: index.php?error=succes");
};
?>
Set id attribute as "myForm" for your form and use the following at the end of your javascript function.
document.getElementById("myForm").submit();
EDIT: And call the function with the button click instead of using submit button.
You need to prevent the submit button from submitting the form, hence use:
"event.preventDefault();" or "return false;"
event.preventDefault() vs. return false
Then at the end of your scripts you can submit the form by using:
document.getElementsByTagname("form")[0].submit();