Beginning PHP5 Skim Throughs, Part 2: Sessions and A Little Extra


Most of chapter 3 of Beginning PHP5 was skippable for me, since it was covered some HTML basics, form fields, and the like. It then moved into cookies but already looked at that in the tutorial and I didn't see anything new on it.  End of the chapter had sessions! Yay!! Since almost all of our apps have a log in component, we use sessions a lot.

Unfortunately, after I read through the section and did some sample code, I decided to Google the session_register function mentioned to see if a default can be set…and discovered from the PHP docs that session_registered is deprecated and has been removed in v5.4.0+. Right now, we're deving (and I'm testing) on 5.3, so my code worked, but yeah, good to know.  So where this was the code I had following the book:

<?php
    session_register("user_id");
    session_register("user_firstname");
    
    if ($_SESSION["user_id"] == '') {
        $_SESSION["user_id"] = 123123;
        $_SESSION["user_firstname"] = "Jane";
        echo "Session set...reload!";
    }
    else {
        echo "Session:<br />";
        echo "<pre>";
        print_r($_SESSION);    
        echo "</pre>";
    }
?>


After the first run


After the second one

So doing things the proper way, without deprecated stuff, would be more like this:

<?php



    session_start();



    if (!isset($_SESSION["user_lastname"])) {
        $_SESSION["user_lastname"] = "Doe";
        echo "Session set...reload!";
    }
    else {
        echo "Session:<br />";
        echo "<pre>";
        print_r($_SESSION);    
        echo "</pre>";
    }
?>

Since we do use sessions a lot, I looked through the list of other session variables in the PHP docs for something else that is import – deleting session variables. After all, people log in, they also log out.  And helpful docs have some example code on how to do this!

<?php



    session_start();
    echo "<pre>";
    print_r($_SESSION);    
    echo "</pre>";
    
    $_SESSION = array();     if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
           $params["path"], $params["domain"],
           $params["secure"], $params["httponly"]
        );
    }
    
    session_destroy();
    
    echo "<pre>";
    print_r($_SESSION);    
    echo "</pre>";
?>

Odd that you have to manually delete the cookies on top of doing the unset and destroy. Another thing I think CF does better with fewer lines of code, but at least it does seem to work.

Chapter 4 is on Decisions, Loops, and more on Arrays.  All of the decision/loop stuff is the same stuff I already went over, so skimmed most of it.  Did quick read the bit on ! which is the PHP version of NOT (and I used it in the second code sample above).  It is nice to see that with PHP you can still use AND/OR in place of using just the operators of && and ||.  The docs do note, though, that in order of precedence, it puts || above OR and && above AND unless you use parenthesis to indicate the desired precedence.

Oh…a new operator.  Xor (which I found in the docs, not the book) – evaluates to true if one of two conditions is true but not if both are.  I do think it's hilarious there is no example in the docs for it…so we'll just throw some stuff out. It isn't the best example, but it works.

<?php
    $selectedOption1 = "Employed";
    $selectedOption2 = "Not Employed";
    
    if (!($selectedOption1 == "Employed" Xor $selectedOption2 == "Not Employed"))
        echo "You can't be both...";
?>

The array section covers a lot of stuff I already saw in the other bits.  It does mention the current(), next(), and prev() functions for manually stepping through an array, but I honestly can't see why I would ever do that versus looping and using each().  The examples in the book are rather bad, IMHO, as it uses stuff I would push to the DB.  Hence having a DB….

Now the docs to mention an array_walk, which could be more useful – performing a function call on every item in an array without having to manually code in the loop.

<?php
    $aUserSubmittedStuff = array("jane doe", "john doe ", "     gunter     smidt");
    
    echo "<pre>";
    print_r($aUserSubmittedStuff);    
    echo "</pre>";
    
    function cleanSubmissions(&$thisItem, $key) {
        $thisItem = trim($thisItem);
        $thisItem = preg_replace('/\s\s+/', " ", $thisItem);
    }
    
    array_walk($aUserSubmittedStuff, 'cleanSubmissions');
    
    echo "<pre>";
    print_r($aUserSubmittedStuff);    
    echo "</pre>";
?>

And yeah, I jumped ahead a little and threw in a preg_replace which is the equivalent of CF's ReReplace.  Yay 🙂  Chapter 5 is on "robust and healthy code" which includes form validation and, at least from the chapter of contents, try/catch!! Glad to see! But I'll deal with that and probably chapter 6 in the next post 🙂

Note: I've realized that there is a bug in the SyntaxHighlighter causing it to blank out the BR tags from my code.  So if you see echo "" it is supposed to be echo "<br /><br />" and many of the other blank "" at in the concatenated strings are actually "<br />".  So far I haven't found a fix as the code, and while this bug was report on the developer's GitHUb 2 years ago, he has never responded.