PHP $_POST[] not void after redirect - php

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'];

Related

PHP: How to stop executing code when refreshed?

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.

Populate Session UserID whilst doing a SQL insert via a form

I want to record the user ID from the current logged in user who enters data into the form which in turn is recorded to a database table
At present the insert query is running and updating all but the user id..the user id variable is definitely working as I am able to echo it out without any issues on the same page
Code is as follows;
$barcode = $_POST['barcode'];
$weight = $_POST['weight'];
$userId = $_SESSION['userId'];
//error handling begins
// check for any empty inputs.
if (empty($barcode) || empty($weight)) {
header("Location: ../record.php?error=emptyfields&barcode=".$barcode."&weight=".$weight);
exit();
}
//we check if valid barcode entered. In this case ONLY letters and numbers.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $barcode)) {
header("Location: ../record.php?error=invalidbarcode&barcode=".$weight);
exit();
}
// check for an invalid weight. In this case ONLY numbers.
else if (!preg_match("/^[0-9].*$/", $weight)) {
header("Location: ../record.php?error=invalidweight&barcode=".$barcode);
exit();
}
else {
$sql = "INSERT INTO trimrecords (barcode, weight, createdby) VALUES (?,?,?);";
// initialize a new statement using the connection from the dbh.inc.php file.
$stmt = mysqli_stmt_init($conn);
// prepare SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error send the user back to the record page.
header("Location: ../record.php?error=sqlerror");
exit();
}
else {
// If there is no error continue the script!
// bind the type of parameters we expect to pass into the statement, and bind the data from the user.
mysqli_stmt_bind_param($stmt, "ssi", $barcode, $weight, $userId);
// execute the prepared statement and send it to the database!
// data is registered to Db at this stage
mysqli_stmt_execute($stmt);
// send back with success
header("Location: ../record.php?record=success");
exit();
}
}
Add session_start() to the top and all worked.

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();

POST variable to another page while redirecting - php

I am redirecting the user back to login page if the login inputs arenot correct.
$sql = "select * from Driver where username=$username and pwd=$pwd";
$driver = mysql_query($sql);
if(!$driver){
header("Location: http://domain.de/login.php");
exit();
}
can i also pass message like "sorry, username isnot correct" to login page?
i dont want to use session. get isnot the option here
you could do it like
header("Location: http://domain.de/login.php?error=username");
and do on the other page
if ($_GET['error'] == 'username') {
echo 'Sorry, username is not correct!';
}
EDIT:
Watch out for SQL injection also
You may add get paramet to location header or save message flag in session. Like this:
$sql = "select * from Driver where username=$username and pwd=$pwd";
$driver = mysql_query($sql);
if(!$driver){
header("Location: http://domain.de/login.php?wasredirect=1");
exit();
}
//////// In login.php
if (isset($_GET['wasredirect'])) {
echo "sorry, username isnot correct";
}
Or this:
$sql = "select * from Driver where username=$username and pwd=$pwd";
$driver = mysql_query($sql);
if(!$driver){
header("Location: http://domain.de/login.php");
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['redirect'] = true;
exit();
}
//////// In login.php
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['redirect'] = true;
if (isset($_SESSION['redirect']) &&$_SESSION['redirect'] ) {
echo "sorry, username isnot correct";
unset($_SESSION['redirect']);
}
I think the best solution is to load that login.php page as a part (the view) of the current script (the controller) and set a variable with the value of the message. Something like:
if(!$driver){
$message = "Sorry, username isnot correct";
}
else {
$message = "Whatever";
}
include('login.php');
$message will be available for you inside login.php script.
For simply giving away a message, you can add it to the URL.
header("Location: http://domain.de/login.php?e=1234");
I recommend using error codes instead of full-length messages for better flexibility.
Note, how ever, that doing it right would require to implement a MVC pattern and then internally load the routing of the error page. But that might be too much for a small script.
I know you donĀ“t ant feedback to your query. No need to worry, unless you are clueless about what SQL injection means.
Best regard
Zsolt
Change the query to:
$sql = "select * from `Driver` where `username`='$username' and `pwd`='$pwd'";
Note the backticks and single quotes

PHP header not redirecting, but there is no output in front of it

I have a php page that allows the user to input some data, and tries to put them into a database. However, my header is not working. It runs the query, but stops at the header, and displays a blank page. Can someone help me out?
<?php
if(isset($_POST['submit'])) {
$user_id = $_POST['user_id'];
$user_vcode = $_POST['user_vcode'];
$send_data = true;
if(empty($user_id) || empty($user_vcode)){
$send_data = false;
}
if($send_data){
require("../../db.php");
$account_id = $_COOKIE['account_id'];
$query = "INSERT INTO api (key_id, key_vcode, owner_id) VALUES ('$user_id', '$user_vcode', '$account_id')";
$result = mysqli_query($dbc, $query) or die("Failed querying database");
mysqli_close($dbc);
header("Location: http://www.google.com");
die();
}
}
?>
Whitespace at the end of the file can be a big pain. Check for any trailing carriage returns or spaces after the final ?> tag.

Categories