Category: PHP

Things related to http://www.php.net

  • Connection Conundrum

    Define a user like this:

    GRANT ALL ON *.* TO 'myuser'@'localhost' IDENTIFIED BY 'super$ecret';

    Then try a PHP script like this:

    <?php
    mysqli_connect("localhost", "myuser", "super$ecret");
    ?>

    What happens and why? How could you avoid it?

    And for glory, what single line could you add that would prevent the error, without making any changes to the mysqli_connect line?

  • On Request

    Imagine you’re a rat in a scientific lab. There are two doors leading into your cage, one red, one blue. Every morning, the red door opens, and a bit of cheese tumbles in. Sometimes you can eat the cheese, and all is well. Other times, there’s a long silver thing stuck in it. You find that if you eat the cheese where it lies on the metal cage floor, it makes your tongue hurt, your paw jump, and gives you a very bad headache. (more…)

  • Static Variable Variables

    <?php
      class A {
        static function b() {
          echo "It works\n";
        }
      }
      $theClass = "A";
      $x = new $theClass;
    
      /* Are any of the following legal? Which? */
    
      A::b();
      $x->b();
      $theClass::b();
    ?>
    

    Answer: A::b() and $x->b() are legal, $theClass::b() is not.

  • Form Names

    Given the following page:

    <form>
      <input type="radio" name="BT.123" value="active" />
      <input type="radio" name="BT.123" value="inactive" />
      <input type="submit" value="Submit" />
    </form>
    
    <?php
      echo "GET: ", $_GET['BT.123'];
      echo "POST: ", $_POST['BT.123'];
      echo "REQUEST: ", $_REQUEST['BT.123'];
    ?>
    

    Assume the “inactive” button is checked and the form is submitted. What is the output?
    Answer: Because the “.” is converted to “_”, only the string literals (and some warnings, if using E_STRICT) are output.

    GET: 
    POST:
    REQUEST:
    

    In other words, use $_REQUEST[‘BT_123’] instead.

  • Post increment

    <?php
    $a = 4;
    echo $a+++$a++;
    ?>
    

    What is the output?
    Answer: 9. The first $a++ looks up 4, then increments $a. The second $a++ looks up 5, then increments $a. 4 + 5 = 9. $a now contains 6.

  • Concatenate

    What, if anything, is the minimum change (fewest inserted/deleted/modified characters) required to make the output The result is bar:


    <?php
    class A {
      private $foo = "bar";
      public function __toString() {
        return $this->foo;
      }
    }

    $myObject = new A();
    echo "The result is " . $myObject;
    ?>

    Answer:
    echo "The result is " , $myObject;