I can't figure out why my redirection wont work?
All I get is a blank page with the same url from where I tried to redirect from..
The code is from my registration page, however I removed some code to make it easier to look at my redirection here. Everything else is working except the redirection.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
//removed bunch of code for clear overview for stackoverflow question
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $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($link);
}
?>
I think your redirect might work if you are going to this page.
Yo get a blank page because your code starts with:
if($_SERVER["REQUEST_METHOD"] == "POST"){
You state that you have removed some code. If the code you expect to run is also in that codeblock and it is no POST (this might be a GET), the code inside that codeblock will not be executed.
There is no form tag in your example, but you could also check if you use method="POST".
Related
I'm trying to create a simple registration form with PHP, storing the user data in a database after processing the form etc. But the PHP code will not work, but not display any errors either. I have turned on error reporting in the php.ini file and also have included:
error_reporting(E_ALL);
ini_set("display_errors", 1);
at the top of all used php files.
I have a feeling that it has something to do with my MySQLi statements.
The most likely lines for error are here:
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
require_once "db_conn.php";
// Prepare a select statement
$sql = "SELECT id FROM estiweb_db WHERE username = ?";
if($stmt = mysqli_prepare($link, $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);
}
There are a few blocks of code similar to this to validate the other fields in register.php.
I have tried already to change the way the code is constructed, different processing order. Also I have tried to change the MySQLi to MySQL (I would prefer not to but it was worth a shot).
I have copied my files into a pastebin, I know I should just use small bits but I am unsure exactly where the problem is originating from. Would appreciate anyone who looks over this and can see anything wrong.
The links are:
register.php: https://pastebin.com/PwfgCby5
validation.php: https://pastebin.com/sbr2DEHK
db_conn.php: https://pastebin.com/j14d8RWw
I have a big issue with my code I suspect.
It only adds the first of $species, $weight and $length. but if there is more than one value in the $_Post.
It should submit them as well from my form. I am having trouble seeing where I have gone wrong.
I hope somebody, can point me in the right direction?
<?php
require 'config.php';
$teamid = $_POST['teamid'];
$species = $_POST['species']; // Can be multiple values depending on how many lines added from form
$weight = $_POST['weight']; // Can be multiple values depending on how many lines added from form
$length = $_POST['length']; // Can be multiple values depending on how many lines added from form
// count($species),($weight),($length) - Should always be the same length
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Prepare an insert statement
$sql = "INSERT INTO indvejninger ( teamid, artid, vaegt, laengde) VALUES (?, ?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
foreach ($species as $key => $value) {
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssss", $_POST['teamid'], $param_species, $param_weight, $param_length);
$param_species = $species[$key];
$param_weight = $weight[$key];
$param_length = $length[$key];
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: index.php?limit=");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
I found the error, after first submit it changes url. So it does not finish the other submissions.
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: index.php?limit=");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
So instead, I need it to finish the other submissions, and then redirect to landing page.
Before I ask the question, I know there are issues with the SQL Injection, I am going to take care of it most likely with PDO, I am just trying to figure this out for now.
I want PHP to read the status column from MySql and if the status column reads -1 where $username = ($_POST["username"]) I want PHP to initially send them to a "change password" screen and then after its changed send an update script to MySql to update column "status" from the default -1 to 1.
If its 1 I want it to log in as normal and if its -1 I want them to be forced to change their password basically and I am having trouble locating a way to do this.
Im assuming my update query would look something like this
$query = "UPDATE login SET status= 1 WHERE user_id='".$username ."' LIMIT 1";
My php login script so far
<?php
// Include config file
require_once 'LoginConn.php';
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = 'Please enter username.';
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST['password']))){
$password_err = 'Please enter your password.';
} else{
$password = trim($_POST['password']);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT username, password FROM scorecardusers WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
/* Password is correct, so start a new session and
save the username to the session */
session_start();
$value= $sql['password'];
$_SESSION['username'] = $username;
header("location: Test.php");
} else{
// Display an error message if password is not valid
$password_err = 'The password you entered was not valid.';
}
}
} else{
// Display an error message if username doesn't exist
$username_err = 'No account found with that username.';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
UPDATED: I added this to my query and it updates correctly.
mysqli_query ($link, "UPDATE Users SET Status = '1' WHERE Status ='-1'and username ='".$username ."' LIMIT 1");
If anyone could help me understand how to pull the status area from my sql and redirect them to the change password page if the status =-1 that would be awesome.
I am just trying to figure out how to redirect to change password if Status =-1 in mysql..
SECOND UPDATE: Ive made a second query that checks the information and sends you to the change password log however I know this is not correct. I feel as if I am getting a lot closer to the answer though. The code works as far as getting me to the right screen but its not getting the correct information. I need the username to be a variable based on what the agent puts in. Again, any help here would be really appreciated.
$id_get = "SELECT Status, username FROM scorecardusers WHERE Status = '-1' and username='MyName' LIMIT 1";
if ($result=mysqli_query($link, $id_get))
{
// Fetch one and one row// check if first time log in
while ($row = mysqli_fetch_assoc($result))
{
$Status=$row["Status"];
$username=$row["MyName"];
if ($Status== "-1" && $username =="MyName");
var_dump($result);
header("location: ChangePW.php");
}
// Free result set
mysqli_free_result($result);
}
I added the update query I posted above after the following code. This has solved my problem and accurately check if the user was logged in before, if they have the website directs them to a change password, if they have logged in it send them to the website. I created a separate query to select status and username so it would not interfere with the password. I am assuming this would work with any user name considering it is completely variable as long as they never logged in before it should direct them. If there is any issues with this code id love to know, however it is working correctly for me.
$id_get = "SELECT Status, username FROM Users WHERE Status = '-1' and username = ?";
if($Check = mysqli_prepare($link, $id_get)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($Check, "s", $param2_username);
// Set parameters
$param2_username = $username;
$param_status=$status;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($Check)){
// Store result
mysqli_stmt_store_result($Check);
if(mysqli_stmt_num_rows($Check) == 1){
// Bind result variables
mysqli_stmt_bind_result($Check, $username, $param2_status);
if(mysqli_stmt_fetch($Check)){
if ($param_status== "-1" && $param2_username == '?');
header("location: ChangePassword.php");
}
}
}
}
I having a difficulty on Log-in procedure. The username & password are both correct based on the database. The name of the fields on the database are also correct. I'm using PDO. When I click the log-in, I'm always redirecting to the else bracket. Please help me,thank you.
<?php
session_start();
include 'config.php';
if ($_POST) {
$user = $_POST['user'];
$pass = md5($_POST['pass']);
$query = "SELECT * FROM useraccounts WHERE USER_NAME=? AND USER_PASSWORD=?";
$stmt = $conn->prepare($query);
$stmt -> bindParam(1,$user);
$stmt -> bindParam(2,$pass);
$stmt -> execute();
$num = $stmt->rowCount();
if ($num>0) {
session_start();
$_SESSION['user']=$user;
$_SESSION['active']=true;
header('location:frontpage.php'); //Must be the destination
echo "SUCCESS";
}
else{
header('location:login.php'); // <-- I'm always directing here
echo "FAILED";
}
}
else{
header('location:login.php');
echo "FAILED";
}
If you are getting redirected to the login.php page, please keep in mind the following:
1) Unless you access that page with a POST request, you will always get the login.page. You have an if statement that looks like this:
if ($_POST) {
So if you access the page directly from the browser, you are redirected straight to the login.php page.
2) If you are getting redirected from the second else statement like you stated with your comment "<-- I'm always directing here" then your query is not returning any result. Your query looks fine. So check the credentials you are passing. Make sure it matches that of the database.
Is your html form using POST or GET in the method attribute. it should be using POST otherwise your database checking code will not be run
We have a system where the user logs in to an admin page to make edits however when they are logging in they can log in with any password as long as the username is correct. The following code is in php tags
include 'database_conn.php';
$sql = "SELECT passwordHash FROM nmc_users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt); // execute the query
mysqli_stmt_bind_result($stmt, $passWDHash);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($passWD, $passWDHash)) {
echo "<p>Password correct!</p><a href='logout.php'>Click here to log off</a></p>\n";
} else {
echo "<p>Sorry we don't seem to have that username.</p>";
session_destroy();
}
if (isset($_SESSION['[url']))
$url = $_SESSION['url'];
else
$url = 'index.php';
header("location $url");
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
Would anyone know how to make it so it only logs users in with the correct username and password that.
The password is in our database as well as the usernames. If any more code is needed then please say and I will reply with the relevant pieces.
From the docs:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie.
If $_SESSION['url'] is set, and the password is wrong, session_destroy() won't unset it. So you're still falling into the success part of the if statement.
Edit: Also, you should be checking authentication on the actual page that requires it. Here, it looks like you're checking on one page and then conditionally redirecting to another. If I type the other page's URL directly into my address bar, will I get that page without an auth check?
Piggybacking on #AlexHowansky answer, you need to do a few things here:
First you need to be sure you're using session_start() at the beginning of the script to make sure the session is set up correctly.
Second, you need to unset the $_SESSION variables to make sure that once the session is destroyed, you can't accss these variables on the current page (they'll be unset on the next page, so you don't have to worry about that).
Third, you'll need to close the mysql connections before redirecting for them to do any good.
Fourth, there was a typo with this: if (isset($_SESSION['[url']))
Your header() redirect also won't work because you're echoing out text before it, which will cause it to fail, but I'll let you fix that.
I'm also not seeing where $passWD is coming from, but I'm assuming you have it in there somewhere.
Updated code:
include 'database_conn.php';
session_start();
$sql = "SELECT passwordHash FROM nmc_users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt); // execute the query
mysqli_stmt_bind_result($stmt, $passWDHash);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($passWD, $passWDHash)) {
echo "<p>Password correct!</p><a href='logout.php'>Click here to log off</a></p>\n";
} else {
echo "<p>Sorry we don't seem to have that username.</p>";
session_destroy();
$_SESSION = array();
}
if (isset($_SESSION['url']))
$url = $_SESSION['url'];
else
$url = 'index.php';
mysqli_stmt_close($stmt);
mysqli_close($conn);
header("location $url");
}
?>