PHP - Test if $_GET value is one of the following - php

First ever question on stackoverflow (new user) so bare with me.
I have a website www.website.com/?view=overview .
I want to test if VIEW exists, if it does not then I redirect to another page
(this is done with empty($_GET['view') and works
If that test passes, I now want to get that view is one of 5 values, if it is then I allow the user to continue if not I redirect to another page.
I have tried with a variable and array, with in_array and the most I can get it to do is properly recognize a single value. When I try to test for more than one, it always redirects. Here is the example if I am testing for two values (overview and settings) but again the total number tested should be 5.
if (empty($_GET['view'])) {
header("Location: www.website.com/?view=overview");
} else {
if (($_GET['view'] != "overview") || ($_GET['view'] != "settings")) {
header("Location: www.website.com/?view=overview");
}
}
}
I searched everywhere and I am stuck!

You're using || (OR) when you should be using && (AND)
if (empty($_GET['view'])) {
header("Location: www.website.com/?view=overview");
} else {
if (($_GET['view'] != "overview") && ($_GET['view'] != "settings")) {
header("Location: www.website.com/?view=overview");
}
}
}
If $_GET['view'] equals 'settings' then it's not equal to 'overview', that part of the condition will pass and your code will redirect. And vice versa.

You can use in_array(needle, haystack) having a list of valid values:
$valid_views = ['overview', 'settings'];
if (!in_array($_GET['view'], $valid_views){
header("Location: www.website.com/?view=overview");
} else {
// view is ok, continue
header("Location: www.website.com/?view=".$_GET['view']);
}

Related

Redirect user after return false

I have some validation fields like this :
if (empty($_POST['finalidade_imob']) || $finalidade_imob == "Escolha 1" ||
!in_array($_POST['finalidade_imob'], $fi_options)) {
$finalidade_imob = "Escolha 1";
$error++;
} else {
$finalidade_imob = $_POST['finalidade_imob'];
}
//on the end
if ($error !== 0) {
return false;
}
But the location of my form is on bottom of my page, so when return false is called the page is reloaded on the top.
If i put this:
if ($error !== 0) {
header('location:perfil.php#content_cadastro_completo');
return false;
}
This page is reloaded for exactly to the place i need, but return false dont work... I know why return dont work, i put that for explain what i need...
So what i need do to goal this target?
Sorry my bad english...
Edit Without js... Only PHP.
My question no clear for this solution, but in my all context this work.
The solution that I found is put placeholder in my action.
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>#content_cadastro_c‌​ompleto"
and
if($error !== 0)
{ return false;//no need header() to go to the placeholder...
}

two if statements in php

I have two seperate if statements, the first if statement is not working but the second one is.
The first if statement works on my other pages and I am unsure of how to properly code this as I am a beginner to PHP.
<?php
session_start();
if($_SESSION['loggedin'] != 'true') {
header("location:login.php");
}
if ($_SESSION['admin']=='N') {
header("location:errorpage.php");
}
?>
What is true in your conditions? It can be bool type or string type.
If You set like this:
$_SESSION['loggedin'] = TRUE;
$_SESSION['loggedin'] = 'true';
You have got two different variable sets.
You can compare it using == or === to include variable type.
For example:
$_SESSION['test_1'] = TRUE;
$_SESSION['test_2'] = 'true';
var_dump( $_SESSION );
array(2) { ["test_1"]=> bool(true) ["test_2"]=> string(4) "true" }
$_SESSION['loggedin']?
Why don't just clear every SESSION var on logout and if the SESSION vars are set => the user is logged in.
And use after the header(); an exit();
Try var_dump($_SESSION['loggedin']) and edit your question.
Or maybe your loggedin var is not a string but a boolean so you could do if(!$_SESSION['loggedin'])
Try using Boolean values rather than strings. I would also use a const for the admin variables. I would do the following;
$_SESSION['loggedin'] = true/false;
$_SESSION['admin'] = true/false;
public class Priviledges
{
public CONST Admin = 0;
public CONST User = 1;
public CONST Contributor = 3;
//change this to however you want to do it :)
public static function isAdmin($val)
{
if ($val == Priviledges::Admin)
{
return true;
}
else
{
return false;
}
}
}
then when you set the admin session variable you can go;
$_SESSION['admin'] = Priviledges::Admin;
if(!$_SESSION['loggedin'])
{
header("location:login.php");
exit()
}
else if (!Priviledges::isAdmin($_SESSION['admin']))
{
header("location:errorpage.php");
exit()
}
else
{ //do your stuff if none of these conditions are met.. }
Always add an exit() or die() after sending a "Location" HTTP header:
<?php
session_start();
if($_SESSION['loggedin'] !== 'true') {
header("location:login.php");
exit();
}
if ($_SESSION['admin'] === 'N') {
header("location:errorpage.php");
exit();
}
Check: php - Should I call exit() after calling Location: header?.
From aaronsaray blog:
Remember, just because the browser is smart enough not to show the
content, doesn’t mean that this isn’t dangerous. So, it’s a little
less dangerous say if this page is just showing a user search option
or some information. It is much more dangerous if this is a page that
executes an action. This is because the entire PHP page will execute
if you don’t put a die() statement.
On other cases, if you want a condition to be evaluated only when a previous condition is false, you may use a "else if".

Album coding errors, simple PHP

I'm currently trying to develop the following function:
When someone wants to see their album or profile photos, I would like to use either album_id or id in the url, like this:
album.php?album_id=(numeric Number)
album.php?id=(numeric number)
I am currently able to execute the first command and when I attempt the second, it fails to load instead I'm taken to the index page (as per the script's design.)
Here is my code:
$album_id = addslashes(is_numeric($HTTP_GET_VARS["album_id"]));
$profile_id = addslashes(is_numeric($HTTP_GET_VARS["id"]));
?>
<?php
if($album_id==Null||!$profile_id==Null)
{
print("<script language='JavaScript'> window.location='index.php'; </script>");
}
else
{
if ($album_id==$album_id)
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/album_photos.php");
}
else
{
if ($profile_id==$profile_id)
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/profile_photos.php");
}
else
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/album_photos.php");
}
}
}
?>
And to clarify, those "pages" contain nothing but bold saying:
Show album photos and Show user photos
But what I can't seem to fathom as to what my problem might be.
If you call album.php?album_id={id}, $_GET['id'] is null, making your first if statement return to the index page.
if (($album_id == null) || ($profile_id == null)) { ... }
One will always be null unless you call album.php?album_id={aid}&id={pid}
if (($album_id == null) && ($profile_id == null)) {
# redirect to index.php
} else {
if ($album_id != null) {
# load album
} else if ($profile_id != null) {
# load profile
} else {
# both given, redirect to error.
}
}
Your condition if($album_id==$album_id) will always be true because they both are same and the else part is never executed.

$_SESSION never getting set

I'm working on an assignment on a PHP course, and I'm stucked at the last part of it.
The assignment is to create a simple login form and use a session as well as hardcoded usernames and passwords (i.e. no db).
What I have problems with is the class that handles the login, and sessions especially. There's a lot of code and I didn't know what I could remove and therefore I've put it on Pastebin instead, hope that's alright.
Thing is that the unit tests that's built into the class passes except for nr. 4, the one that's checking that the user is logged in. The problem seems to be that $_SESSION[$this->loginSession] doesn't get set, and this is what I need help with.
The variable $loginSession is declared in the beginning of the class, and should be set to "isLoggedIn" when a user types a correct username and password, but that doesn't happen (no error message).
My class is:
<?php
class LoginHandler {
private $loginSession;
public function IsLoggedIn() {
if($_SESSION[$this->loginSession] == "isLoggedIn") {
return true;
}
else {
return false;
}
}
public function DoLogin($username, $password){
if ($username != null && $password != null){
switch ($username){
case "hello";
if ($password == "1234"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
case "hello2";
if ($password == "12345"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
}
}
else {
return false;
}
}
public function DoLogout(){
unset($_SESSION[$this->loginSession]);
}
public function Test() {
$this->DoLogout();
// Test 1: Check so you're not logged in.
if($this->IsLoggedIn() == true){
echo "Test 1 failed";
return false;
}
// Test 2: Check so that it's not possible to login with wrong password.
if ($this->DoLogin("hello", "4321") == true){
echo "Test 2 failed";
return false;
}
// Test 3: Check that it's possible to log in.
if ($this->DoLogin("hello", "1234") == false){
echo "Test 3 failed";
return false;
}
// Test 4: Check that you're logged in
if ($this->IsLoggedIn() == false){
echo "Test 4 failed";
return false;
}
return true;
}
}
?>
I hope it's enough to include the class and not all the other files, otherwise I'll put them up.
Now I see it :-)
$_SESSION[$this->loginSession] == "isLoggedIn";
== should be =
== compares while = sets
You need to start the session. session_start(); Place it at the very top of the documents (only one time on a page load) you are using.
$this->loginSession is never set so it's NULL
$_SESSION[null] is not possible as far as i know
change your code to
private $loginSession = 'testing';
and it should work
Why do you put semicolon in your case instruction case "hello";There should be a colon. case "hello": { ...instructions}

PHP function to check if 2 variables are empty

I have an index page, I want it to include a page called splash.php and not display.php when a user lands on index.php, but once a user does something (sets a variable) ie if a user searches (variable "query") i want it to include display.php and not include splash.php
What is wrong with this code?
function hasGet()
{
return !empty($_GET['fact']);
return !empty($_POST['query']);
}
if (hasGet()) {
include("display.php");
}
else {
include("splash.php");
}
This question should be removed
Only the first return statement is executed. Try:
return !empty($_GET['fact']) && !empty($_POST['query']);
A better way to accomplish what you are trying to do is use sessions.
index.php
<?php
session_start();
if (!isset($_SESSION['visited'])) {
$_SESSION['visited'] = true;
include 'splash.php';
} else {
include 'display.php';
}
?>
This way after a user visits index.php for the first time, $_SESSION['visited'] is set to true and it won't show the splash page throughout their visit.
You cannot have two returns as you are doing. Try
return (!empty($_GET['fact']) && !empty($_GET['query']));
You might want to try this...
if($_SERVER["SCRIPT_NAME"] == "/index.php"){
include("splash.php");
}else{
include("display.php");
}
2.
if(!empty($_GET["fact"]) || !empty($_POST["query"])){
include("display.php");
}else{
include("splash.php");
}

Categories