SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2012
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Differences in declaring values when echoing back results

    Hi All,

    I am now pretty comfortable with this, but at first I found the differences in syntax a bit confusing. Below is two different ways of presenting the same thing. Do the experts have a preference and why?

    Method #1

    echo "<p>Thanks {$_POST['name']}, for your commentsbr />
    {$_POST['comments']}</p>
    <p>We will reply to {$_POST['email']}.</p>\n";

    versus

    Method #2

    $name = $_POST["name"];
    $comments = $_POST["comments"];
    $email = $_POST["email"];


    echo "<p>Thank you, $name, for your commentsbr />
    $comments</p>
    <p>We will reply to $email.</p>\n";

    BTW - I have a preference, but only for one reason. By declaring the variables, it helps me think about the structure of my project more clearly. That said, I think I will eventually not have to worry about this and use method #1.

    Thanks ahead for any further feedback.

    Jim

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Using the incoming variable directly as in $_POST['name'] makes it very obvious where this var has come from, and in this case also makes it very clear that it is not to be trusted, that it needs escaping and may need filtering.

    However it is harder to write and is prone to mistyping, plus it is ugly and hard to read. This befuddles the mind when trying to follow the flow of a script in your head.

    $name is easier to read, making it somewhat easier to follow the code. BUT you cannot be sure where it came from, it is a name, but the name of what? Has the variable been checked? is the variable safe to put into my database or output as html?

    As a rule of thumb, if I a script is only accessing a POST (or GET) var once I leave it as a $_POST['var'];

    If it is going to access that POST var twice, i'd tend to still leave it as $_POST;

    But any more, or if I thought I'd use it more than twice, then yes, I'd do this:

    $name = $_POST["name"];

    This would be especially true if I did any kind of validation or processing on that var.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •