PHP Validation (SQL) and Redirection - php

I am getting a value "ID" from the URL using GET, as follows -
if ( isset($_GET['id']) && (filter_var($_GET['id'], FILTER_VALIDATE_INT))) {
$colname = $_GET['id'];
}
else
{
$URL="/index.php";
header ("Location: $URL");
exit();
}
I am then checking if the element of that ID exists in the table, as follows -
$query_validate = sprintf("SELECT * from surveys where id = %s", GetSQLValueString($colname, "int"));
$result_validate = mysql_query($query_validate, $conn) or die(mysql_error());
$row_validate = mysql_fetch_assoc($result_validate);
$num_validate = mysql_num_rows($row_validate);
if($num_validate==0)
{
$URL="/index.php";
header ("Location: $URL");
exit;
}
The idea is that when I type in the url as http://example.com/surveys?id=1, it loads the first survey, and so on. If an invalid ID (alphabets, id does not exist in the table, etc) is entered, it should redirect the user back to index.php, this is the basic premise of my code.
However, even if I go to the URL http://example.com/surveys?id=abc, it loads the page and displays an SQL Syntax error. I know that the header function cannot be invoked after output has been given on to the page, but these 2 checks happen very close to the start and I have ensured there is no output happening there.

Try this,
$num_validate = mysql_num_rows($result_validate);
Instead of
$num_validate = mysql_num_rows($row_validate);
Code:
$query_validate = sprintf("SELECT * from surveys where id = %s", GetSQLValueString($colname, "int"));
$result_validate = mysql_query($query_validate, $conn) or die(mysql_error());
$num_validate = mysql_num_rows($result_validate);
if($num_validate==0)
{
$URL="/index.php";
header ("Location: $URL");
exit;
}else{
$row_validate = mysql_fetch_assoc($result_validate);
}

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.

header location unable to redirect

Overview:
I am having a block of code where I am checking for a condition and redirect to a page(manage_contents.php) if the condition(mysqli_num_rows($pages_set)>0) satisfies and thus everything after the if condition should not execute as the header has been redirected.
if(mysqli_num_rows($pages_set)>0) {
$_SESSION["message"] = "can't delete a subject with pages";
redirect_to("manage_contents.php?subject={$current_subject["id"]}");
}
$id = $current_subject["id"];
//Standard delete query
$query = "DELETE FROM subjects WHERE id = {$id} LIMIT 1";
$result = mysqli_query($connection,$query);
if($result && mysqli_affected_rows($connection)==1) {
$_SESSION["message"] = "Subjects deleted";
redirect_to("manage_contents.php");
}else{
$_SESSION["message"]="Subject deletion failed";
redirect_to("manage_contents.php?subject={$id}");
}
But if I execute the above the code isn't redirecting(even if the if condition satisfied) and executing whatever is next to the if loop.
redirect_to function:
function redirect_to($new_location) {
header("Location:".$new_location);
}
Working solution for me:
if(mysqli_num_rows($pages_set)>0) {
$_SESSION["message"] = "can't delete a subject with pages";
redirect_to("manage_contents.php?subject={$current_subject["id"]}");
} else {
$id = $current_subject["id"];
//Standard delete query
$query = "DELETE FROM subjects WHERE id = {$id} LIMIT 1";
$result = mysqli_query($connection,$query);
if($result && mysqli_affected_rows($connection)==1) {
$_SESSION["message"] = "Subjects deleted";
redirect_to("manage_contents.php");
}else{
$_SESSION["message"]="Subject deletion failed";
redirect_to("manage_contents.php?subject={$id}");
}
}
So,if i put all the code inside of the else statement then ofcourse it doesn't go to the else section when the if condition satisfies and hence works just fine.
Doubt:
Why the header doesn't redirect if I just leave the code outside of else section and why does it redirect just fine when the code is inside of else block?
I think both the code should work exactly same as far I know about header redirects.(when header is redirected all the following codes execution should skip).
Setting the Location header is not going to stop processing of the current PHP page. You'll need to explicitly exit:
function redirect_to($new_location)
{
header("Location: $new_location");
exit;
}
In other languages/frameworks (ASP.NET's Response.Redirect comes to mind) the current page's execution is stopped for you, but this does not happen in PHP and nothing in the documentation for header indicates otherwise.
Take a look to the caveat in http://php.net/manual/en/function.header.php : when you use the "Location" header you must take care that the code below it will not be executed (and your second code comply with it).

Protecting webpage via authentication

I am developing a portal with PHP, and would need to implement a simple PHP authentication system which restricts access to certain pages depending on the credentials of the user.
I have a function CheckAuth() which takes a paramater (Integer). Ie, my database has five authorization levels 1-5. If I call CheckAuth(3) this will return true if the user has authorization level 3 or above. My code right now reads:
if(!CheckAuth(3) {
die("Sorry, we were unable to deliver the requested content.");
}
The problem with this solution is that it will break the page's layout as other elements such as the page's footer will not be displayed.
What is the best way of conditionally displaying only a portion of the page?
Thanks in advance!
Dario
function CheckAuth() {
require("config.php");
//User ain't been logged in?
if(!isset($_SESSION["login"])) {
return 0;
}
//Alright user is logged in, lets check the level...
//1 = User, 2 = OP (or Admin)
$query = "SELECT * FROM delegations WHERE id=" . $_SESSION["login"];
$results = mysqli_query($con, $query);
while($row = mysqli_fetch_array($results)) {
return $row["Level"];
}
}
Solution is not to use die() but to render another version of page.
if (!CheckAuth(3)) {
// render error page
} else {
// render normal page
}
You shouldnt ask for if (!CheckAuth(3)) you should better go the way of if (CheckAuth(3)) and display the Page data if the user has the permission to view the content, if not redirect him to a 403 page something like this
if(CheckAuth(3))
{
//display page content
}
function CheckAuth($permissionLevel)
{
require("config.php");
//User ain't been logged in?
if(!isset($_SESSION["login"])) {
return 0;
}
//Alright user is logged in, lets check the level...
//1 = User, 2 = OP (or Admin)
$query = "SELECT * FROM delegations WHERE id=" . $_SESSION["login"];
$results = mysqli_query($con, $query);
while($row = mysqli_fetch_array($results)) {
if($row["Level"] == $permissionLevel)
{
return true;
}
}
header("Status: 403 Forbidden");
header("Location: /403.html");
exit;
}

unable to forward pages in php

I have a php page. when users click on edit button then my all other fields data is apperaing the respective textbox, and also if he submits the form my data is updating. But my problem is it is not forwarding to my respected page.
i denoted it like this header('Location: /profile.php'); for forwarding it in my profile page
What could be the reason?
My full code:
<?php
include '../../../include/connection.php';
$idd =$_REQUEST['id'];
$resultt = mysql_query("SELECT * FROM budget WHERE budget_id = '$idd'");
$test = mysql_fetch_array($resultt);
if (!$resultt)
{
die("Error:<font color='red'> Data not found..</font>");
}
$budget_id=$test['budget_id'];
$heads_id=$test['heads_id'];
$amount= $test['amount'];
$from_date=$test['from_date'];
$to_date= $test['to_date'];
if (isset($_POST['submit'])) {
$headsid=$_POST['headsid'] ;
$amount= $_POST['amount'] ;
$todate=$_POST['todate'] ;
$frmdate= $_POST['frmdate'] ;
mysql_query("UPDATE budget SET heads_id ='$headsid',amount ='$amount',from_date ='$frmdate' ,to_date ='$todate',updater_id ='$uid',updated_date=NOW() WHERE budget_id = '$idd'")
or die(mysql_error());
header('Location: /profile.php');// PROBLEM HERE UNABLE TO FORWARD TO THE PAGE
}
?>
header('Location: profile.php');
die;
strip or remove the backslash.
header("Location: http://example.com/path/path/profile.php");
exit;

Categories