I created a signup form and once a user has successfully signed up, it should redirect to home.php. But instead, it's being redirected to index.php. Everything else works (please see the code below). I could see that a user was added to my database, and that the status of the profile picture is 1.
<?php
if (isset($_POST['submitSignup'])) {
include_once 'dbh.inc.php';
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['passwordS'];
if (empty($first) || empty($last) || empty($email) || empty($username) || empty($password)) {
header("Location: ../signup.php?signup=empty"); exit();}
else{
if (!preg_match("/^[A-Za-z\s'-]{2,50}$/", $first) || !preg_match("/^[A-Za-z\s'-]{2,50}$/", $last)) {
header("Location: ../signup.php?signup=flnameinvalid&email=$email&username=$username"); exit();}
else{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=emailinvalid&first=$first&last=$last&username=$username"); exit();}
else{
$mysql = "SELECT * FROM users WHERE user_username='$username';";
$result = mysqli_query($conn, $mysql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=unametaken&first=$first&last=$last&email=$email"); exit();}
else{
if (strlen($password) < 8) {
header("Location: ../signup.php?signup=strlen&first=$first&last=$last&email=$email&username=$username"); exit();}
else{
if (!preg_match("#[0-9]+#", $password)) {
header("Location: ../signup.php?signup=num&first=$first&last=$last&email=$email&username=$username"); exit();}
else{
if (!preg_match("#[A-Z]+#", $password)) {
header("Location: ../signup.php?signup=cap&first=$first&last=$last&email=$email&username=$username"); exit();}
else{
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (user_first, user_last, user_email, user_username, user_password)
VALUES (?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare ($stmt, $sql)) {
echo "SQL error!";}
else{
mysqli_stmt_bind_param ($stmt, "sssss", $first, $last, $email, $username, $hashedPwd);
mysqli_stmt_execute ($stmt);
$sql3 = "SELECT * FROM users WHERE user_username='$username' AND user_first='$first';";
$result = mysqli_query($conn, $sql3);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userid = $row['id'];
$sql4 = "INSERT INTO profileimg (userid, status) VALUES ($userid, 1);";
mysqli_query($conn, $sql4);
}
}
else{ echo "There are no users!";}
}
header("Location: ../home.php?signup=success"); exit();
}
}
}
}
}
}
}
}
else{header("Location: ../signup.php?signup=error");}
The header function doesn't work even if I placed it after the mysqli_execute($stmt).
I tried creating a user-defined function instead, but it is still not working.
It was working last night when I haven't added the last if and else statement yet, the one with $sql3.
========= UPDATED ==========
Somehow, I was able to identify that the redirect it is following is the header function within the last else statement of my home.php. Here's the code
<div class="sideright">
<?php
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg where userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".$fileActualExt'".mt_rand()." height='200' width='200'>";}
else{
echo "<img src='uploads/defaultprofilepicture.jpg' height='200' width='200'>";}
echo $row['user_username'];
echo "</div>";
}
}
}
else{
echo "Sorry, an error occurred.";}
if (isset($_SESSION['key'])) {
echo
'<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" value="Change Profile Picture">
<button type="submit" name="submitFile"> Go </button>
</form>';
echo
'<form action="includes/logout.inc.php" method="POST">
<button type="submit" name="submitLogout"> Log Out </button>
</form>';
}
else{
header("Location: index.php");}
I still haven't fixed it, please help me find out where I went wrong.
try
echo "<script type=\"text/javascript\">".
"window.location='signup.php?signup=error';".
"</script>";
You may try this, it's Working for me.
Replace this code to Your Header Location
<script type=\"text/javascript\">
window.location.href='home.php';
</script>
Related
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
I'm doing an registration form and I'm trying to check if the email that the person inserts in the input is already in another table that has all emails that I allow to be registered. If it is it should register the person. I don't understand where I'm failing. I'm starting now with php. Please help.
<?php
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$username = mysqli_real_escape_string($conn, $_POST['uid']);
$email = mysqli_real_escape_string($conn,$_POST['mail']);
$password = mysqli_real_escape_string($conn,$_POST['pwd']);
$passwordRepeat = mysqli_real_escape_string($conn, $_POST['pwd-repeat']);
$check1 = $_POST['check1'];
$check2 = $_POST['check2'];
if(empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header ("Location: ../header.php?error=emptyfields&uid=".$username."&mail=".$email);
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-z0-9]*$/", $username)){
header("Location: ../header.php?error=invalidadmail&uid=");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
header("Location: ../header.php?error=invalidadmail&uid=".$username);
exit();
}
else if (!preg_match("/^[a-zA-z0-9]*$/", $username)){
header("Location: ../header.php?error=invalidaduid&mail=".$email);
exit();
}
elseif($password !== $passwordRepeat){
header("Location: ../header.php?error=passwordcheck&uid=".$username."&mail=".$email);
exit();
}
elseif((!isset($check1)) || (!isset($check2))){
echo"<script>alert('É necessário confirmar as duas opções :(');
window.location.href='../header.php'</script>";
exit();
}
This is the part of the code that is not working
$sql2 = "SELECT * FROM emails WHERE (email_socio = '$email')";
$res = mysqli_query($conn, $sql2);
if (mysqli_num_rows($res) < 0) {
echo "FAIL";
}
These are other validations and where it will insert the data into final table
else{
$sql = "SELECT uidUsers FROM users WHERE uidUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../header.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if($resultCheck > 0){
header("Location: ../header.php?error=usertaken&mail=".$email);
exit();
}
else {
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../header.php?error=sqlerror");
exit();
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
$sql ="SELECT * FROM users WHERE uidUsers='$username' AND emailUsers='$email'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$userid = $row['idUsers'];
$sql = "INSERT INTO profileimg (userid, status) VALUES ('$userid', 1)";
mysqli_query($conn, $sql);
}
}
header("Location: ../header.php?signup=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../header.php");
exit();
}
Your condition is wrong:
if (mysqli_num_rows($res) < 0) {
echo "FAIL";
}
You're checking for less than zero, when in fact it should be less than one.
So, change it to either of the two:
if (mysqli_num_rows($res) === 0) // it logically cannot contain negative values
if (mysqli_num_rows($res) < 1)
<?php
require_once("db_credentials.php");
$conn = mysqli_connect("localhost", "root", "isdc3333", "collab_schema");
if (isset($_POST["submit"])) {
$first = mysqli_real_escape_string($conn, $_POST["first"]);
$last = mysqli_real_escape_string($conn, $_POST["last"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$uid = mysqli_real_escape_string($conn, $_POST["uid"]);
$pwd = mysqli_real_escape_string($conn, $_POST["pwd"]);
if (empty($first) or empty($last) or empty($email) or empty($uid) or
empty($pwd)) {
header("Location: signup.php?signup=empty");
exit();
} else {
if (!preg_match("/^[a-zA-Z]*$/", $first) or !preg_match("/^[a-zA-
Z]*$/", $last)) {
header("Location: signup.php?signup=invalid");
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: signup.php");
exit();
} else {
$sql = "SELECT * FROM users WHERE uid='$uid'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if ($queryResults > 0) {
header("Location: signup.php?signup=usertaken");
exit();
} else {
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO collab_schema.users (first, last, email, uid,
pwd) VALUES ('$first', '$last', '$email', '$uid',
'$hashedPwd');";
$result = mysqli_query($conn, $sql);
header("Location: signup.php?signup=success");
exit();
}
}
}
}
} else {
header("Location: signup.php");
exit();
echo "Redirecting...";
}
?>
The last sql query won't work, can you list the errors?
Doesn't look like the code is working, but everyone says it fine.
I'm just putting more text because stack overflow says to put more details even when I don't want too :^)
I'm just a beginner in PHP. I'm making a website, and it needs to store the time for login and logout of every user. I found this code for it but it's in ASP.
I tried to make it into PHP but I'm unknowledgeable what will I put in the INSERT INTO of sessionid and logintime.
Table name: userlogtime
logid, userid, sessionid, logintime, logouttime, offline
Here's my code:
<?php
if(isset($_POST['submit'])) {
include 'dbheader.php';
$username = mysqli_real_escape_string($conn, $_POST['uname']);
$password = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error handlers
//Check if inputs are empty
if(empty($username) || empty($password)) {
echo '<script type="text/javascript">alert("Please fill out the following");
window.history.back();
</script>';
exit();
} else {
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck < 1) {
echo '<script type="text/javascript">alert("Login error");
window.history.back();
</script>';
//set the user id value from the Members table in a session variable
$_SESSION('member') = $row($userid);
$sql ="UPDATE userlogtime SET offline=True WHERE offline=False AND userid="$_SESSION('member')"";
$sql = "INSERT INTO userlogtime (userid, sessionid, logintime) VALUES ('$_SESSION('member'), );";
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
//De-hashing the password
$hashedPwdCheck = password_verify($password, $row['password']);
if ($hashedPwdCheck == false) {
echo '<script type="text/javascript">alert("Login error");
window.history.back();
</script>';
exit();
} elseif($hashedPwdCheck == true) {
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['role'] = $row['Role'];
$_SESSION['image'] = $row['image'];
if($_SESSION['role'] == "User"){
header("Location: user.php");
exit();
}
}
}
}
}
} else {
header("Location: user.php?login=error");
exit();
}
$sql = "INSERT INTO userlogtime (userid, sessionid, logintime) VALUES ('$_SESSION('member'), ".session_id().",now());";
Im stuck with some code. Im pretty new to this.
If the else statement ($uidcheck) returns false it should execute the elseif statement ($emailcheck). See code below.
$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
if (empty($username)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($email)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($pwd)) {
header("Location: ../signup.php?error=empty");
exit();
} else {
$sql = "SELECT username FROM user WHERE username='$username'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0) {
header("Location: ../signup.php?error=username");
exit();
} elseif ($uidcheck < 0) {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
header("Location: ../signup.php?error=email");
exit();
} else {
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
}
When the emailadress already exists in the database it should exit and add a parameter to the header.
Thanks in advance!
Sven
Your code may does the purpose. But that is not good enough to read/debug.
if( !isset($_POST["username"]) || !isset($_POST["email"]) || !isset($_POST["pwd"]) || empty($_POST["username"]) || empty($_POST["email"]) || empty($_POST["pwd"]) )
{
header("Location: ../signup.php?error=empty");
exit();
}
$sql = "SELECT username FROM user WHERE username='".mysqli_real_escape_string($username)."'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0)
{
header("Location: ../signup.php?error=username");
exit();
}
else
{
$sql = "SELECT email FROM user WHERE email='".mysqli_real_escape_string($email)."'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
header("Location: ../signup.php?error=email");
exit();
}
else {
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
Here are my Recommendations:
Always check if an variable is declared in the scope using isset() function. If the value of "username" or "email or "pwd" is not submitted in the POST request, your code will throw a Fatal Exception and rendering stops there.....
Don't put the value submitted by the User directly into the SQL query....This will make your web application Vulnerable to SQL Injection Attack.
Try this..
You are checking the MySQL resulted value in a wrong manner. For Example Email is already existed in you DB then your Query results Value, then you don not check with < or > just try with either it is empty or not.
$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
if (empty($username)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($email)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($pwd)) {
header("Location: ../signup.php?error=empty");
exit();
} else {
echo "Username check";
$sql = "SELECT username FROM user WHERE username='$username'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if (!empty($uidcheck)) {
header("Location: ../signup.php?error=username");
exit();
} elseif (empty($uidcheck)) {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
echo $emailcheck = mysqli_num_rows($result);
if (!empty($emailcheck)) {
header("Location: ../signup.php?error=email");
exit();
} else {
echo "asdasd";
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
}
I am a bit new to programming and I am writing a prepared statement for my signup form. Part of the validation is to check and see if the email address already exists. The problem I am having is that the data is not being inserted, the code seems to stop working when i check if an email already exists and I am redirected to an undefined page I.E. www.mywebsite.com/undefined instead of profile.php. I am not getting any errors when check my log. I do not understand why it is doing this and if anyone can assist/teach me what I am doing wrong, it would be greatly appreciated. Mysqlnd is enabled and the API extensions are working. I checked my phpinfo() and the data is being sent and received.
signup.php
<?php
session_start();
include '../dbh.php';
$respond = array(
'status' => true,
'message' => 'There was an error',
'redirect',
'errors'
);
if (isset($_POST['submit'])) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$errorEmpty = false;
$errorEmail = false;
if (empty($first) || empty($last) || empty($email) || empty($pwd)) {
$respond['errors'][] = "Please fill out all fields!";
$respond['errorEmpty'] = true;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$respond['errors'][] = "Please enter a valid email address!";
$respond['errorEmail'] = true;
} else {
$sql = "SELECT email FROM user WHERE email= ? ";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$respond['errors'][] = "That email address already exists!";
$respond['errorEmail'] = true;
}
else {
$encryptpwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO user (first, last, email, pwd) VALUES (?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ssss', $first, $last, $email, $password_hash);
if (mysqli_stmt_execute($stmt)) {
$userID = mysqli_insert_id($conn);
$status = 1;
$sql2 = "INSERT INTO profileImg (email, status) VALUES(?,?)";
$stmt2 = mysqli_prepare($conn, $sql2);
mysqli_stmt_bind_param($stmt2, 'si', $email);
mysqli_stmt_execute($stmt);
$_SESSION['id'] = $userID;
$respond['redirect'] = "../profile.php?id=$userID"; // redirect to the actual ID of the user who just signed up
}
}
}
}
echo json_encode($respond);
?>
profile.php
<?php
session_start();
include 'dbh.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Yahbang</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header class="header_profile">
<nav>
<ul>
</ul>
</nav>
<form class="logout" action='include/logout.inc.php'>
<button>Log out</button>
</form>
</header>
<?php
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileImg WHERE id='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div class='userProfileImage'>";
if ($rowImg['status'] == 0 ) {
echo "<img src='images/profile".$id.".jpg'>";
} else {
echo "<img src='images/profile_default.jpg'>";
}
echo "<p>".$row['first']."</p>";
echo "</div>";
}
}
} else {
echo "There are no users yet!";
}
if (isset($_SESSION['id'])) {
echo "<form action='include/uploadProfile.inc.php' method='POST' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit' name='submit'>UPLOAD</button>
</form>";
} else {
header("Location: ../index.php");
exit();
}
?>
<footer class="footer_profile">
<nav>
<ul>
</ul>
</nav>
</footer>
</body>
</html>