#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    4
    Rep Power
    0

    Fixing PHP Syntax


    I need to use PHP to set a conditional and change the css style for the following element:

    <h3 id="h3_g_<?= $gall["url"] ?>" class="ir"><?= $gall["name"] ?></h3>

    Something like:

    PHP Code:
    <?php
             
    if ($workpage) {
                 print(
    "<h3 id=\"h3_g_<?= $gall[\"url\"] ?>\" class=\"ir\" style=\"top:59px!important;\"><?= $gall[\"name\"] ?></h3>");
             } else {
                 print(
    "<h3 id=\"h3_g_<?= $gall[\"url\"] ?>\" class=\"ir\"><?= $gall[\"name\"] ?></h3>");
             }
    ?>
    However, I donít have the syntax right. Another option would be to assign a different class (rather than try to use an inline style). I could use some help with the syntax first - thanks.
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    This is a general misunderstanding, I think.

    You cannot have PHP generate an HTML string containing PHP code which generates HTML (I think my brain just crashed).

    You can divide the script into sections of PHP and sections of raw output. That's it. If you wanna insert variables into a string within a PHP section, you need to use string operations, either concatenation or interpolation.

    However, the real problem is that you write spaghetti code: You have a wild mixture of CSS nested in HTML nested in PHP. This makes this trivial h3 headline almost impossible to read. While your application becomes more complex, you'll quickly reach a point where you no longer understand your own code. That's a problem.

    In modern web development, people separate the different languages and aspects (layout vs. programming logic) as much as possible. Instead of stuffing all the PHPSQLHTMLCSSJavaScript into one big blob like in the old times, we now have separate files for each language and aspect.

    I strongly recommend you do that as well:

    • Consider using a template engine like Twig instead of stuffing HTML into PHP scripts (or PHP tags into HTML).
    • Use external CSS files instead of style attributes
    • Use external JavaScript files instead of event attributes

    This may seem to be more work at first. But it will make your code much more readable and flexible, and many problems won't even come up.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    4
    Rep Power
    0
    Originally Posted by Jacques1
    However, the real problem is that you write spaghetti code: You have a wild mixture of CSS nested in HTML nested in PHP. This makes this trivial h3 headline almost impossible to read. While your application becomes more complex, you'll quickly reach a point where you no longer understand your own code. That's a problem.
    I hear you, Jacques - the further problem is - I didn't write the original code, but need to come up with a quick fix to this particular page. No one will be paying me to redo the project from the ground up. It's a momentary fix, until the website is redone completely.

    I did manage to stop the errors with this rewrite:

    PHP Code:
    <?php
             
    if ($workpage) {
                 print(
    "<h3 id=\"h3_g_\".$gall{[\"url\"]}\" class=\"ir\" style=\"top:159px!important;\">$gall{[\"name\"]} ?></h3>");
             } else {
                 print(
    "<h3 id=\"h3_g_\".$gall{[\"url\"]}\" class=\"ir\">$gall{[\"name\"]}</h3>");
             }
        
    ?>
    But the ID name isn't being formed correctly to work. And so I slog on...
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    Originally Posted by pherank
    I didn't write the original code, but need to come up with a quick fix to this particular page.
    Man, PHP is becoming the COBOL of web programming.



    Originally Posted by pherank
    But the ID name isn't being formed correctly to work. And so I slog on...
    Please take 5 minutes to look up the correct syntax and test it in a small script.

    The current code looks like you just guessed. Also, you need to escape your stuff before you can insert it into HTML.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    4
    Rep Power
    0
    And the correct answer is:

    PHP Code:
    <?php
             
    if ($workpage) {
                 print(
    "<h3 id=\"h3_g_$gall[url]\" class=\"ir\" style=\"top:59px!important;\">$gall[name]</h3>");
             } else {
                 print(
    "<h3 id=\"h3_g_$gall[url]\" class=\"ir\">$gall[name]</h3>");
             }
        
    ?>
  10. #6
  11. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    The variables are still not escaped, so this will blow up at the next opportunity.

    I suggest you fix it now. Otherwise, you'll fix it next week with an angry boss or customer yelling at you because "the code still doesn't work".
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    4
    Rep Power
    0
    It actually did work fine on the server, AFTER I removed the braces, etc. But it bothered me that there were no single quotes. So I've now learned that it works when I don't escape them. Hmmm.

    PHP Code:
    if ($workpage) {
                 print(
    "<h3 id=\"h3_g_{$gall['url']}\" class=\"ir\" style=\"top:59px!important;\">{$gall['name']}</h3>");
             } else {
                 print(
    "<h3 id=\"h3_g_{$gall['url']}\" class=\"ir\">{$gall['name']}</h3>");
             } 
  14. #8
  15. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    No. I mean escaping in the sense of "convert characters that have a special meaning in HTML into HTML entities". See the link I gave you.

    If the variables you dump into the HTML happen to contain characters like < or ", then the whole HTML breaks. If the variables are user-defined, you even risk cross-site scripting attacks, which is a very serious danger.

    So you need to do this properly. See the link I gave you. It's all explained there.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    58
    Rep Power
    1
    I think it'd be cleaner this way:
    PHP Code:
    // Start the H3 line with what will be in either case
    echo '<h3 id="h3_g_' $gall['url'] . '" class="ir"';
    // If the $workpage variable, then add in a certain style, too
    if ($workpage) {
    echo 
    ' style="top:59px!important;">'
    }
    // Either way, close the tag
    echo $gall['name'] . '</h3>'
    Does that get you the same result?
  18. #10
  19. Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jan 2004
    Location
    New Springfield, OH
    Posts
    1,214
    Rep Power
    1469
    Originally Posted by Jacques1
    You cannot have PHP generate an HTML string containing PHP code which generates HTML (I think my brain just crashed).
    Sure you can.

    Just add curly braces.
    PHP Code:
    <?php
             
    if ($workpage) {
                 print(
    "<h3 id=\"h3_g_{$gall['url']}class=\"ir\" style=\"top:59px!important;\">{$gall['name']}</h3>");
             } else {
                 print(
    "<h3 id=\"h3_g_{$gall['url']}\" class=\"ir\">{$gall['name']}</h3>");
             }
    ?>
    Alternatively, you can use the alternate If syntax.
    PHP Code:
    <?php if ($workpage) : ?>
    <h3 id="h3_g_<?=$gall['url']?>" class="ir" style="top:59px!important;"><?=$gall['name']?></h3>"
    <?php else : ?>
    <h3 id="h3_g_<?=$gall['url']?>" class="ir"><?=$gall['name']?></h3>
    <?php endif; ?>
    All of this being said, I would recommend a different approach. The second example I've given is great for logic portion, but I would recommend using CSS classes as mentioned by others.
    Last edited by Nilpo; November 21st, 2013 at 08:27 AM.
    Don't like me? Click it.

    Scripting problems? Windows questions? Ask the Windows Guru!

    Stay up to date with all of my latest content. Follow me on Twitter!

    Help us help you! Post your exact error message with these easy tips!
  20. #11
  21. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    Originally Posted by Nilpo
    Sure you can.
    Please read the whole thread (starting with the first post), not just a random sentence.

    All right, since there seems to be a lot of confusion about what you can and should do, this is the correct way:

    PHP Code:
    <?php

    // escaping is crucial! otherwise, the site may crash or be attacked at any time
    function html_escape($input) {
        return 
    htmlspecialchars($inputENT_QUOTES'utf-8');    // make sure to set the right encoding here
    }

    // escape the variables and use string concatenation to create the HTML
    print('<h3 id="h3_g_' html_escape($gall['url']) . '" class="ir">' html_escape($gall['name']) . '</h3>');
    Yes, PHP has the theoretical ability of embedding variables directly into a string. I mentioned this above, and pherank used it already.

    But this is not an option unless the variables themselves are already escaped. I strongly advice against string interpolation in the context of HTML strings.

    Comments on this post

    • paulh1983 agrees : Amen to that and thanks to jacques, i have learnt quite a lot :)
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  22. #12
  23. Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jan 2004
    Location
    New Springfield, OH
    Posts
    1,214
    Rep Power
    1469
    Originally Posted by Jacques1
    Please read the whole thread (starting with the first post), not just a random sentence.

    All right, since there seems to be a lot of confusion about what you can and should do, this is the correct way:

    PHP Code:
    <?php

    // escaping is crucial! otherwise, the site may crash or be attacked at any time
    function html_escape($input) {
        return 
    htmlspecialchars($inputENT_QUOTES'utf-8');    // make sure to set the right encoding here
    }

    // escape the variables and use string concatenation to create the HTML
    print('<h3 id="h3_g_' html_escape($gall['url']) . '" class="ir">' html_escape($gall['name']) . '</h3>');
    Yes, PHP has the theoretical ability of embedding variables directly into a string. I mentioned this above, and pherank used it already.

    But this is not an option unless the variables themselves are already escaped. I strongly advice against string interpolation in the context of HTML strings.
    This is just an argument over semantics now. Several correct methods have been demonstrated. It's up to the OP now to decided which one fits their coding style the best.

    I would argue that if you are escaping these variables in the print statement, there is already something fundamentally wrong with the code. I would prefer to handle that much sooner. Sanitizing, escaping, and validating data should be done in the business layer long before you begin generating output. But that is a matter of preference. Either way works.

    The OP also made no mentions of security, they simply asked how to fix their syntax.
    Don't like me? Click it.

    Scripting problems? Windows questions? Ask the Windows Guru!

    Stay up to date with all of my latest content. Follow me on Twitter!

    Help us help you! Post your exact error message with these easy tips!
  24. #13
  25. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    Originally Posted by Nilpo
    Several correct methods have been demonstrated.
    Sure. It's just that your objection didn't make a lot of sense, because I was referring to this line from the original post:

    PHP Code:
    print("<h3 id=\"h3_g_<?= $gall[\"url\"] ?>\" class=\"ir\" style=\"top:59px!important;\"><?= $gall[\"name\"] ?></h3>");
    You obviously can't embed PHP tags in a string generated by PHP.

    Nobody has doubted the existence of string interpolation. We've already used it multiple times in this thread.



    Originally Posted by Nilpo
    I would argue that if you are escaping these variables in the print statement, there is already something fundamentally wrong with the code. I would prefer to handle that much sooner. Sanitizing, escaping, and validating data should be done in the business layer long before you begin generating output.
    Hardly. This brings back bad memories about scripts which would escape every single variable somewhere on top of the script, and you never know if a variable is escaped until you actually look it up. That's just terrible. And it bloats the code beyond recognition.

    Escaping is an output problem. It belongs into the view. And that's just like modern template engines do it. Twig, Smarty etc. all have the concept of modifiers which let you escape or encode your values before you echo them. And they also have automatic escaping.



    Originally Posted by Nilpo
    The OP also made no mentions of security, they simply asked how to fix their syntax.
    People rarely ask for security advice. Many programmers haven't even heard of things like SQL injections or cross-site scriping.

    That doesn't mean we should abandon people to their fate. I think it's our duty to point out security problems. What's the point of fixing a tiny issue when there's a much bigger problem in the code? What kind of help is this?
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo