treehouse : what would you like to learn today?
Web Design Web Development iOS Development

if "certain" variable exist... do this.?

  • <?php 
    // for example: thispage.php?word=abracadabra

    if ( $val = $_GET['word'] )
    echo "the word is: $val";

    else
    echo "";

    ?>


    That is the php im using to display certain text on a page, but my issue is, i want to display certain text if the variable ="something specific"

    example.. .com/thispage.php?word=hello so, if word = hello then echo "this text" if it does not =hello, then dont do nothin...

    i dont want someone to be able and type anything after the = sign and have something display, only of what it i that = is what i specify.. heh :) i think i think that makes sense

    any help preeease?
  • Something like this?
    <?php 

    $val = $_GET['word'];

    if ($val == 'Hello') {
    echo "this text";
    // other code for people who know the secret word is "Hello"
    }
    else {
    // do nothing
    }

    ?>
  • You could even cut out the middle man and not use the $val if it's not needed. Also, since you don't want to do anything if it doesn't equal hello, you won't need the 'else' statement either.

    <?php 

    if ($_GET['word'] == 'Hello') {
    echo "this text";
    // other code for people who know the secret word is "Hello"
    }
    ?>
  • but I would put a htmlspecialchars() around the $_GET for security reasons
  • You could also do:


    <?php
    echo isset($_GET['word']) && $_GET['word'] == 'Hello' ? 'Enter Text You want to Echo' : '' ;
    ?>


    by using isset you are ensuring that the $_GET['word'] actually exists and is not null:
  • @mikes02

    Shouldn't it rather be:

    <?php
    isset($_GET['word']) && $_GET['word'] == 'Hello' ? echo 'Enter Text You want to Echo'; ?>
    ?>
    That way it only performs the echo if it exists. If it doesn't exist, there's no need to echo anything and doesn't slow the page.
  • It works the same way in mine, even with the echo in front, it is saying to only echo "Enter Text You want to Echo" if $_GET['word'] isset and it equals Hello, else don't echo anything. It's the PHP Ternary Operator.
  • i <3 you all.. <br />
    31M1k97, thanks for the tip, but i am pretty much php-tarded what do you mean "around" i feel like id spend hours just trying to figure out what you said to do for the security reason.

    Senff, noahgelman, mikes02 thank you muches. i havnt tried either yet but non the less thank you very much
  • @mikeman

    He means like this that when you want to use $_GET['word'] you should use it like this htmlspecialchars($_GET['word'])

    This prevents the user from manually typing in code in the url which could break your code and/or be a security risk (although I don't know all that much about php security best practices)