Company Test Question for PHP Programmers

Discussion in 'PHP' started by mayafishing, Jul 16, 2007.

  1. #1
    Hi everyone, I got this question when applying for a PHP programmer position.

    Question:

    Check out the following code and make suggestions on how to improve it based on concerns from Security, Compatibility and Efficiency:

    <?
    echo("<p>The characters you have input are: " .$_GET['q'] . ".</p>");
    ?>


    Anyone up to the challenge?
     
    mayafishing, Jul 16, 2007 IP
  2. SeLfkiLL

    SeLfkiLL Active Member

    Messages:
    85
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    50
    #2
    If you're applying for the position, shouldn't you be answering the question? ;)

    But anyway, it's kind of vague. I really don't see how you could improve the code much, but my best bet would be:

    
    <?php
    echo '<p>The characters you have input are: '.htmlentities($_GET['q']).'.</p>';
    
    PHP:
    Note the missing ?> tag is intentional.
     
    SeLfkiLL, Jul 16, 2007 IP
  3. mayafishing

    mayafishing Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks guys, I learned something new.

    Here is my original answers to the company:


    <p>
    <?php
       echo "The characters you have input are:".validate_input($_POST['q']); 
    ?>
    </p>
    PHP:
    Note: validate_input() is used for removing the tags which might be used for attacking database.
    (Or maybe validate_input() should be called clean_up() or htmlentity(stripslashes(trim())). )

    Explained:

    1. no need () after echo.
    2. <p></p> should be saperated from the php script itself.(might improve efficiency).
    3. use POST instead of GET to inprove security, because the data appended to GET might be stealed on the way to target page. (if the data is sensitive)
    4. ANY input to database should be checked and cleaned to make sure it does not contain any harmful tags.
    5. use GET to transmit data has limitations on the length of the characters.
     
    mayafishing, Jul 16, 2007 IP
  4. SeLfkiLL

    SeLfkiLL Active Member

    Messages:
    85
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    50
    #4
    Those are good points but as far as this piece of code, I don't think you'd need much database protection. :p

    There are some improvements in that code in terms of efficiency I overlooked. You could even go as far as to reduce the code to this:

    
    <p>The characters you have input are: <?=htmlentities(trim($_POST['q'])) ?></p>
    
    PHP:
     
    SeLfkiLL, Jul 16, 2007 IP