echo out message after redirect? - php

I have a button on users profiles that allows another user to add a user to their favorites.
Once this button is clicked they are linked to the sql process file favorite.php.
Once the sql script has run it links the user back to the original profile page which is profile.php.
now what i want to do is find out how i can echo a message on the page profile.php after the sql has completed. I've tried the following but nothing happens.
can someone please show me what i'd need to do to get this working? thank you
favorite.php:
<?php
require_once('includes/session.php');
require_once('includes/functions.php');
require('includes/_config/connection.php');
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$result = mysql_query("INSERT INTO ptb_favorites (user_id, favorite_id) VALUES (".$_SESSION['user_id'].", ".$user_to_id.")")
or die(mysql_error());
header("Location: profile.php?id=" . $user_to_id['user_id'] . "added=1");
?>
profile.php:
<?
if (isset($_GET['added']) && $_GET['added'] == 1) {
$message = "<div class=\"infobox\">This user was successfully added to your favorites.</div>"; ?>
<? } ?>

Your redirected URL will look like this:
profile.php?id=123456added=1
# ^
Notice the missing & in the parameters. Adapt your header() call and include it before the "added=1" concat.
header("Location: profile.php?id=" . $user_to_id['user_id'] . "&added=1");
# ^
On a related note, you would have found out earlier if it wasn't for that isset:
if (isset($_GET['added']) && $_GET['added'] == 1) {
Leave it out, as this is a required param and you want to get a note for such occassions. Instead just turn of notices/warnings on your production server.

Related

PHP-Unable get values from $_SESSION, error msg is Notice: Undefined variable: _SESSION

First let me explain my code.
It comprises of three php files.
inc_fn_header_and_menu.php, contains the HTML and CSS header details
and it initializes the session via session_start();
This is later included in project_status.php] .
In project_status.php] , I have included another file
project_status_app.php which contains a HTML form.
project_status.php:
<?php
include 'inc_fn_header_and_menu.php';
function includeFile($file,$variable) {
$var = $variable;
include($file);
}
if (isset($_GET['id']) && $_GET['id']!="") {
$pid = $_GET['id'];
$_SESSION['pidForApproval'] = $_GET['id'];
$query = 'SELECT * FROM `profile` WHERE pid ='.'\''.$pid.'\'';
$result=mysqli_query($db,$queryToRetrievePP) or die("There are no records to display ... \n".
mysqli_error());
foreach ($result as $row) {
$status = $row['status'];
?>
project_status_app.php
In project_status_app.php I am attempting to retrieve pidForApproval from the $_SESSION array.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include '../../inc/fastlogin.php';
$sql = "UPDATE pp SET customer_purchase_remarks ='{$_POST['remarkstxt']}' WHERE pp.pid='{$_SESSION['pidForApproval']}'";
$result = mysqli_query ( $fastdb, $sql ) ;
if (mysqli_affected_rows($fastdb) != 1) {
$_SESSION['err_cpa_rmks'] = "<p>Error while updating WHERE id='{$_SESSION['pidForApproval']}'</p>";
} else {
$_SESSION['suc_cpa_rmks'] = "<p>Records was updated successfully.</p>";
}
header ("location: project_status.php?id="$_SESSION['pidForApproval']);
exit();
}
?>
When I load project_status.php, project_status_app.php is supposed to display the form. Once the user fills in the form the and the submit button has been pressed, the UPDATE statement is supposed to run and then it is supposed to navigate back to project_status.php?id=FA142. But the update is failing and the when the project_status.php is loaded back, the url looks like this http://localhost/fast/project_status.php?id= . The id is empty. It is supposed to be something like this http://localhost/fast/project_status.php?id=FA142. With the id being populated at the
header ("location: project_status.php?id=".$_SESSION['pidForApproval']);
I suspected that my $_SESSION['pidForApproval'] is not being populated in project_status.php but I echoed back $_SESSION['pidForApproval'] in that file itself and I can see it is being populated. Hence, I suspect that the $_SESSION['pidForApproval'] is not being passed to project_status_app.php. I have already attempted to include session_start(); clause in project_status_app.php but that gives an error, stating that the session has already started, in inc_fn_header_and_menu.php. Can someone help me as to why the $_SESSION['pidForApproval'] is not being passed on to the project_status_app.php file. Thank you.

Redirect if sql column has a specific value

Am new to php, so any help would be greatly appreciated. I have a page to create account for users, and while creating account, there is a select field which has three specific value to select from "notfcode" "tfail" **"tfcode".
There is another page check.php which allows the user check his ttype. What i want to do is make the page try to read the sql table row which is ttype and if the value present on the user's account is "notfcode" it redirects to notfcode.php page, if its "tfail" it redirects to tfail.php and if its "tfcode" it stays on the page. below is the code i have been battling with without success.
<?php session_start();
include_once ('session.php');
require_once 'class.user.php';
if(!isset($_SESSION['acc_no'])){
header("Location: login.php");
exit();
}
$reg_user = new USER();
$stmt = $reg_user->runQuery("SELECT * FROM account WHERE acc_no=:acc_no");
$stmt->execute(array(":acc_no"=>$_SESSION['acc_no']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$email = $row['email'];
$temp = $reg_user->runQuery("SELECT * FROM transfer WHERE email = '$email' ORDER BY id DESC LIMIT 1");
$temp->execute(array(":acc_no"=>$_SESSION['acc_no']));
$rows = $temp->fetch(PDO::FETCH_ASSOC);
$transfertype = $row['ttype'];
if(isset($_SESSION['acc_no'])){
$transfertype = $row['ttype'];
if($transfertype == nocodetf){
header("Location: nocodetf.php");
}
elseif($transfertype == tfail){
header("Location: nocodetf.php");
}
else {
header("Location: check.php");
}
}
include_once ('counter.php');
?>
When the page loads up, it does nothing, no redirects which is what i intend. A pointer in the right direction will be appreciated.
This are strings.
if($transfertype == "nocodetf"){
or
if($transfertype == 'nocodetf'){
Activate PHP error reporting than PHP shows you this.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$transfertype = "foo";
if ($transfertype == nocodetf) { # <-- as you did it
//...
}
// <b>Warning</b>: Use of undefined constant nocodetf - assumed 'nocodetf' (this will throw an Error in a future version of PHP) in ...
I was finally able to resolve it using this code
<?php
$transfertype = $row['ttype'];
if($transfertype == 'nocodetf'){
header('Location: nocodetf.php'); }
else if($transfertype == 'failtf'){
header('Location: failtf.php');
exit();
}
?>
The problem seemed to be in the fact that i wasn't quoting the value which php should try to get from the sql column.

Check redirect source

I have a form to edit an entry, after the user presses the submit button it executes the includes/edit.php?id=XXX script and then redirects using the header('Location: ../index.php'); to the index page where all the entries are being displayed.
On the index page, I want to create a condition:
if the index page is accessed via a redirect from the edit.php?id=XXX page, then show a success message to notify the user that the edit was succesfull.
How should this condition look like?
<?php
require_once('includes/session.php');
require_once('includes/config.php');
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
}
$query = ("SELECT * FROM archive ORDER by id DESC");
$result = mysqli_query($link, $query) or die (mysqli_error());
/*if (condition){
//show success message
}*/
?>
You should take a look at this var :
$_SERVER['HTTP_REFERER'];
As it will return the page from where you come before this one:
So you could just do :
if($_SERVER['HTTP_REFERER'] == "edit.php?id=XXX"){
// your code here
}
you can simply try this :
if(isset($_GET['id']) && !empty($_GET['id']))
{
// your success message
}
If you set a $_SESSION variable with messages you can then display all messages and clear the list afterwards.
Adding a message:
if ( ! isset($_SESSION['messages']) ) {
# initialize messages
$_SESSION['messages'] = [];
}
# Add a new message:
$_SESSION['messages'][] = 'Something was a success!';
Reading messages:
# If there are messages not displayed
if ( isset($_SESSION['messages']) && is_array($_SESSION['messages']) ) {
foreach ( $_SESSION['messages'] as $message ) {
echo $message . '<br>';
}
# Clear messages
unset( $_SESSION['messages'] );
}
The suggested 'HTTP_REFERER' can be manipulated and browsers are not required to send it.
I would suggest to redirect immediately and not execute more code after the location header is set:
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
exit();
}
If $_SESSION['login'] is not set: redirect and exit.
You might consider the rest of the code as one big "else" (= if $_SESSION['login'] is set).
To answer the question from comments: without the exit, the code below will be executed .. and doing that query is not really necessary. Thats why its better to end the program flow by adding an exit. Referencing: Why I have to call 'exit' after redirection through header('Location..') in PHP?
And for the condition you could use $_SERVER['HTTP_REFERER'] or $_GET['id'] to check the page you are coming from. Just compare the strings or parts of them.

$_SERVER['HTTP_REFERER']; Returning .css file when trying to make referral script

Ok so I am trying to make it so users can refer others using the domainname followed by their username.
My site works using Iframes so index.php actually loads home.php in an iframe, where a new user can enter their details, upon which they are submitted to the database.
In index.php I have:
<?php
session_start();
$ref = $_SERVER['HTTP_REFERER'];
$_SESSION['abc'] = $ref;
?>
A user then enters their info and submits in which home.php adds them to the database.
Home.php has the follwing code:
session_start(); //at the top of the file followed by some other code
//If they are a new users. lets say they clicked a referral link in which 'referredby' would show domainname.com/referrerUserName
if (isset($_SESSION['abc'])) {
//insert new user
$run = mysql_query("INSERT INTO ".MYSQLTABLE."(id, address, ip, date, time, referredby) VALUES('','" . $_POST['address'] . "','" . $_SERVER['REMOTE_ADDR'] . "', '".date("Y-m-d")."', '".date("D")."', '".$_SESSION['abc']."')");
}
else {
echo 'error';
}
They are added ok but in the 'referredby' column this is returned: http://domainname.com/screens.css
When it should show http://domainname.com/?r=ReferrersUserName
Any help would be great! Yes I will be changing to SQLI
You should probably change:
<?php
session_start();
$ref = $_SERVER['HTTP_REFERER'];
$_SESSION['abc'] = $ref;
?>
into
<?php
session_start();
if (!isset($_SESSION['abc']) && isset($_GET['r'])) {
$ref = $_GET['r'];
$_SESSION['abc'] = $ref;
}
?>

Issue with PHP header function in Google Chrome

After a successful login (i.e when user clicks the login button after entering the username and password), based on the user type I want to send user to a specific page. Below is my code. (Here, if usertype is 'employee', he should be taken to "data-update.php" page after clicking 'login' button.)
This is the code in the index.php page:
// This file is the home page.
// Require the configuration before any PHP code as the configuration controls error reporting:
require ('config.inc.php');
// The config file also starts the session.
// Require the database connection:
require (MYSQL);
// If it's a POST request, handle the login attempt:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include ('login.inc.php');
}
/* PAGE CONTENT STARTS HERE! */
?>
<!DOCTYPE html>
<html lang="en">
<head>
...
This is the code in the login.inc.php page:
<?php
// This is the login page for the site.
// It's included by index.php, which receives the login form data.
// Array for recording errors:
$login_errors = array();
// Validate the username:
// Validate the password:
if (empty($login_errors)) { // OK to proceed!
// Query the database:
$q = "SELECT id, type FROM users WHERE (username='$u' AND pass='" . get_password_hash($p) . "')";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // A match was made.
// Get the data:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Store the data in a session:
$_SESSION['user_id'] = $row[0];
$_SESSION['username'] = $u;
if ($row[1] == 'employee') {
reset_sms_update_session();
header("Location: http://".BASE_URL."data-update.php");
exit;
}
elseif ($row[1] == 'client'){
header("Location: http://".BASE_URL."About.html");
exit;
}
...
And this is a partial code in "data-update.php" page:
// Start the session:
session_start();
function redirect_invalid_user($check = 'user_id', $destination = 'index.php', $protocol = 'http://') {
// Check for the session item:
if (!isset($_SESSION[$check])) {
$url = $protocol . BASE_URL . $destination; // Define the URL.
header("Location: $url");
exit(); // Quit the script.
}
} // End of redirect_invalid_user() function.
//Redirect to index.php if user not logged in
redirect_invalid_user( );
/* PAGE CONTENT STARTS HERE! */
?>
<!DOCTYPE html>
...
The problem is that, in Google Chrome when user clicks the login button, he is first taken to the index.php page (where the redirection occurs) and then he has to click login button again to be taken to "data-update.php" page.
Why is this happening in Google Chrome?
(FYI: this does not happen in XAMP testing environment in my local PC.)
This does NOT happen in Firefox or IE8 (i.e. user is taken to "data-update.php" first time login button is clicked).
Please help.
I solved this by setting a permanent redirect from CPanel in my webserver for http://example.com to http://www.example.com.

Categories