PHP: How to stop executing code when refreshed? - php

I'm new to programming and I'm trying to build a simple login-form with HTML, PHP and Bootstrap. I have a login page and a registration page. I wanted to display a success message once a user was created. But it keeps showing when I come back from a different page and also when I refresh the page.
With header("Location:registration.php"); I redirect to the same page. This prevents inserting into the database when I refresh the page. See my code below from "registration.php".
session_start();
if(isset($_POST['add_user'])) {
//When submitted store entered data in a variable
$add_username = $_POST['add_username'];
$add_password = $_POST['add_password'];
//Database query
$query = "INSERT INTO users(username, user_password) VALUES('{$add_username}', '{$add_password}')";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
} else {
$_SESSION['success_message'] = " ";
header('Location: ' . $_SERVER['PHP_SELF']);
$_SESSION['success_message'] = "<div class='alert alert-success' role='alert'><strong>User Created</strong><br><a href='index.php'>Log In</a></div>";
exit();
}
}

You can try this code to avoid issue.
if (isset($_POST['submit'])) {
// ... your code here
header('Location: ' . $_SERVER['PHP_SELF']);
}

Try this
if (empty($_SESSION['success_message'])) {
// set and display message
}
This way you will display the message only the first time.

Related

How to get alert notification on redirected page using PHP?

I created an HTML form to update my posts. So I used header() function to redirect the page to Updated page so I can see the changes. But I wanna echo a message on the redirected page. I have tried this code but this works only on same page, not redirected page.
<?php
$query_2 = "UPDATE posts SET post_image = '$post_image' WHERE post_id = $post_id ";
$query_2 .= "AND LENGTH('$post_image') > 0 AND post_image <> '$post_image' ";
$editPostImg = mysqli_query($connection, $query_2);
if (!$editPostImg) {
die("Something went wrong.<br>" . mysqli_error($connection));
}
header("Location: posts.php?source=edit_posts&p_id=$post_id");
echo "<p class='alert alert-success'><strong>Post Updated!</strong> <a href='../post.php?p_id=$post_id' class='alert-link' target='blank'>View Post</a><a href='' class='close' data-dismiss='alert'>x</a></p>";
}
?>
After the following line of code:
header("Location: posts.php?source=edit_posts&p_id=$post_id");
the user will be redirected to the new page and won't see the code that is executed after the header directive. To display the message you have to submit the message as GET or POST parameter. Whereas the first option will be the easier one.
As #Dharman mentioned your code is wide open to SQL Injections and should use parameterized prepared statements. You could use PDO or MySQLi. I build a solution with PDO but up to you.
Thus, you could adjust your script as follows:
<?php
try{
//Create new PDO Object
$conn = new PDO("mysql:host=HOST;port=PORT;dbname=DBNAME", USERNAME, PASSWORD);
//Define query
$query = $this->conn->prepare("UPDATE posts SET post_image = :postimage WHERE
post_id = :postid AND LENGTH(post_image) > 0 AND post_image <> :postimage");
$query->bindValue("postimage", $post_image);
$query->bindValue("postid", $post_id);
$query->execute();
//Redirect user and add success message as GET parameter
header("Location: posts.php?source=edit_posts&p_id=$post_id&update=success");
//Make sure script is terminated
exit();
} catch(Exception $ex){
//Log error
error_log($ex->getMessage());
//Show user custom error message
echo "Something went wrong";
//Make sure script is terminated
exit();
}
?>
On the target page (posts.php) you could then insert a code snippet as follows:
<?php
if(isset($_GET['update']) && $_GET['update'] == "success"){
echo "<p class='alert alert-success'><strong>Post Updated!</strong> <a href='../post.php?p_id=$post_id' class='alert-link' target='blank'>View Post</a><a href='' class='close' data-dismiss='alert'>x</a></p>";
}
?>

$_Session variables not accessible on the same page they are created

My issue is that for some reason on the login.php page of my website, I initialize some $_Session Variables from my users table in the corresponding database, but while these variables seem to function properly on other pages I can't do anything with them immediately after initializing them, because they don't seem to exist. This is an issue because I would like to reference the variables I have defined to create other session variables for efficiency, and because I would like to use it for a welcome message like the simple example shown in my code. Here is the code in question:
if(isset($_POST['user_email']) && !empty($_POST['user_email']) AND isset($_POST['user_pass']) && !empty($_POST['user_pass']))
{
$email = mysqli_real_escape_string($link, $_POST['user_email']); // Set variable for the username
$password = mysqli_real_escape_string($link, sha1($_POST['user_pass'])); // Set variable for the password and convert it to an sha1 hash.
$result = mysqli_query($link, "SELECT user_email, user_pass, user_active FROM users WHERE user_email='".$email."' AND user_pass='".$password."' AND user_active='1'") or die(mysqli_error($link));
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_uuid'] = $row['user_uuid'];
$_SESSION['user_level'] = $row['user_level'];
$_SESSION['user_rank'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_uuid'] . '. <br />Proceed to the forum overview.';
}
}
}
I have session_start(); at the top of my connect.php which is included at the top of the signin.php doc.
The result of this code on this page is something like:
Welcome, .
Proceed to the forum overview.
However if I run it on a different page on the site it properly prints, i.e.:
Welcome, username.
Proceed to the forum overview
Thanks.

Redirecting to another page, using variables from the first one

I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();

Login script not working (redirection)

SO, what I've been trying to do is set up a login system. I had the system working, but then I needed to add the menu buttons. For some weird reason, that broke it... all the menu is, is a simple "is the session value 1?" question.
Here's login.php's main code:
<?php
session_start();
$errmsg='';
if($_POST['email']&&$_POST['password']){
$_SESSION['email']=$_POST['email'];
$_SESSION['password']=$_POST['password'];
header("Location: validate.php");
}
if($_SESSION['vcode']){
$code=$_SESSION['$vcode'];
if($code==4){
$errmsg="Invalid login details. Please try again.";
}else{
$errmsg='';
}
$_SESSION['vcode']==0;
}
?>
Then, it redirects to validate.php.
<?php
session_start();
include '/home/raymonf2/mysqlincludeprs.php';
$email=$_SESSION['email'];
$pw=hash('ripemd160', $_SESSION['password']);
$status=0; // Original value is 0; not validated (yet?)
$sql = 'SELECT * FROM users WHERE username = \'' . $email . '\' AND password = \'' . $pw . '\';';
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']. Sorry!');
}
while($row = $result->fetch_assoc()){
if($result->num_rows>0){
$status==1;
}
}
if($status==1){
// Back to homepage if okay.
unset($_SESSION['email']);
unset($_SESSION['password']);
$_SESSION['loggedin']==1;
header("Location: /index.php");
die("Click here if not automatically redirected to index.");
}else{
$_SESSION['loggedin']==0;
$_SESSION['vcode']==4;
header("Location: login.php");
}
?>
Any suggestions would be appreciated.
The problem is that the login page directs to validate, and then back to login without an error message.
if($result->num_rows>0){
$status==1;//should be $status = 1;
}
and maybe you don't need the while section.

PHP $_POST[] not void after redirect

I'm opening myself to honest critizism and sugggestions.
The issue is with the function $_POST[void] being valid after a redirect. Quotes.add.php is a form that directs to quotes.done.php, submitted to mysql and redirected back to quotes.add.php with an echo $msg and reset to be filled out again.
Is header(); the best method in this case?
quotes.done.php
else{
include 'data.php';
$query = "INSERT INTO quotes (`id`, `quotes`, `artist`, `date`) VALUES ('null', '$_POST[text]', '$_POST[artist]', 'null')";
$result = mysql_query($query) or die (mysql_error());
$_POST['void'] = "$_POST[artist] Was Added Successfully to database";
unset ($_POST['artist']);
//var_dump($_POST['void']);
//exit;
header ("location: quotes.add.php");
exit;
}
quotes.add.php
if (isset($_POST['void'])) {
$msg = $_POST['void'];
}else{
$msg = "Please insert artist";
}
If you do a redirect i think you have to use $_SESSION.
I'd do:
session_start();
$_SESSION['msg'] = "$_POST[artist] Was Added Successfully to database";
header ("location: quotes.add.php");
exit;
and then
session_start();
if (isset($_SESSION['msg'])) {
$msg = $_SESSION['msg'];
unset($_SESSION['msg'];
}else{
$msg = "Please insert artist";
}
This is the clean, proper, and secure way to do it:
quotes.done.php
<?php
else{
include 'data.php';
// escape the input, to avoid SQL injection
$text = mysql_real_escape_string($_POST['text']);
$artist = mysql_real_escape_string($_POST['artist']);
$query = "INSERT INTO quotes (`id`, `quotes`, `artist`, `date`) VALUES ('null', '{$text}', '{$artist}', 'null')";
$result = mysql_query($query);
// always set your variables to a default value
$success = false;
// did the query execute successfully?
if($result){
$success = true;
}
header('Location: quotes.add.php?result=addedquote&artist='.urlencode($_POST['artist']).'&success='.urlencode($success));
exit;
}
?>
quotes.add.php
<?php
$msg = '';
if(isset($_GET['result']) && $_GET['result'] == 'addedquote') {
$artist = htmlentities(urldecode($_GET['artist']), ENT_QUOTES, 'UTF-8', false);
$success = (bool) urldecode($_GET['success']);
if($success){
$msg = "$artist Was Added Successfully to database";
} else{
$msg = "Failed to Add $artist to database";
}
} else{
$msg = "Please insert artist";
}
?>
A couple of things for you to note here:
If you are not using a wrapper for running your db queries with prepared parameterized statements, you should use at least mysql_real_escape_string() to remove the nasty stuff in order to prevent SQL injection.
As noted by others header() will do a GET request, hence why you are not getting the $_POST[void] on the page you are redirecting. That's why you will use variables on your url to transfer them to the redirected page, and then fetch them with $_GET.
$_POST[somename] and $_POST['somename'] are two different things. They will work, because PHP will try to see if there is a constant named somename, if there isn't one, you are lucky, but if there is one, then all sky falls down.
If you want to keep the $_POST variables, don't redirect. A redirect causes the client's browser to re-request the page with only $_GET params.
Save the record to the database. Get the new record ID, redirect to a page and pass in the ID. Then use the ID to fetch and display the record.
Redirecting will not POST a value to the page. You could use session or GET.
$message = urlencode("$_POST[artist] Was Added Successfully to database");
header ("location: quotes.add.php?message=" . $message);
On your quotes.add.php page
echo $_GET['message'];

Categories