Cody Raspien
Cody Raspien

Reputation: 1845

Redirect page based on lack of a URL parameter or if parameter is null- PHP

I have a URL e.g. http://foo.com?stone=yes

The page pointing to that URL is coded in PHP.

I can use the following to read stone.

I want to be able to redirect the page if:

  1. stone's value is null
  2. stone isn't present in the URL.

I've tried the following but it's not working.

 $stonevar = $_GET['stone'];

 if ($stonevar = "") {
    header("Location: http://google.com");
 }

Upvotes: 0

Views: 2632

Answers (4)

Emilio Gort
Emilio Gort

Reputation: 3470

You have some erros in your code.

1- If you don't check if the $_GET['stone'] exist you will get a warning like: Undefine variable...

2- In your if stament you're assigning a value, to compare values use == or === instead.

Change your code to:

$stonevar = isset($_GET['stone']) ? $_GET['stone'] : NULL;

if (empty($stonevar)) {
  header("Location: http://google.com");
  exit();
}

Useful links:

isset

empty

Comparison Operators

Ternary Operator

Upvotes: 2

Hüseyin BABAL
Hüseyin BABAL

Reputation: 15550

You can do that with empty()

<?php

if(empty($_GET['stone'])) {
    header("Location: http://google.com");
    exit;
}

?>

Upvotes: 2

Jack
Jack

Reputation: 1015

<?php

if(empty($_GET['stone'])) {
header("Location: http://google.com");
}
?>

Upvotes: 0

Brian Driscoll
Brian Driscoll

Reputation: 19635

The code $stonevar = "" in your if condition is assigning the value "" to the variable $stonevar.

For comparison, you will want to use the equality operator ==, e.g.:

 if ($stonevar == "") {
 header("Location: http://google.com");
  }

Upvotes: 1

Related Questions