Get $500+ of the best After Effects files, video templates and music for only $20!
Winners Announced: Free Copies of “Pro PHP and jQuery”

Winners Announced: Free Copies of “Pro PHP and jQuery”

Jason Lengstorf was nice enough to offer our community a handful of copies of his latest awesome book, Pro PHP and jQuery. Be sure to read his latest Nettuts+ tutorial, “Object-Oriented PHP for Beginners,” based on his book.


Winners Announced:

Congratulations to the following winners, who were randomly selected:

  • Jonathan Stuckey
  • Rick Blalock
  • Matt Vickers

Each of you will be contacted shortly about arranging your free copy. Thanks again to everyone who entered!

“This book is for intermediate programmers interested in building Ajax web applications using jQuery and PHP. Along with teaching some advanced PHP techniques, it will teach you how to take your dynamic applications to the next level by adding a JavaScript layer with jQuery.”

To enter for a chance to win a hardcopy version of the book, leave a comment with a PHP tip. It can be as simple or as long as you like. Just as long as it was something that helped you to learn PHP, that will automatically enter you! On Monday morning, we’ll choose the winners!


You can also purchase “Pro PHP and jQuery” here.

Tags: Freebie
Add Comment

Discussion 825 Comments

Comment Page 5 of 15 1 ... 3 4 5 6 7 ... 15
  1. Alex W says:

    You can use the heredoc syntax if you are inputting long strings into variables. For example:

    $str = <<string = ‘Stuff’;
    $this->data = array(‘Age’, ‘Sex’, ‘Location’);
    }
    }

    $test1 = new test();
    $name = ‘Nettuts’;

    echo <<string.
    Now, I would like to know your {$test1->data[2]}.
    LONG;

    • Alex W says:

      Well, that didn’t work.
      Let’s try in a code block.

      You can use the heredoc syntax if you are inputting long strings into variables. For example:

      $str = <<string = ‘Stuff’;
      $this->data = array(‘Age’, ‘Sex’, ‘Location’);
      }
      }

      $test1 = new test();
      $name = ‘Nettuts’;

      echo <<string.
      Now, I would like to know your {$test1->data[2]}.
      LONG;

  2. Steve says:

    PHP

    I recommend xdebug since it adds many debugging-features and even enhances the readability of var_dump()

  3. Yury Nedomolkin says:

    Here are a few tips:

    foreach ($persons as &$person) {
    $person['fullname'] = $person['last_name'] . ‘ ‘ . $person['first_name'];
    }

    where $person passed by reference

    $printThemAll = ”;
    foreach ($persons as $person) {
    $printThemAll .= $person['last_name'] . ‘ ‘ . $person['first_name'] . ‘,’;
    }
    $printThemAll = substr($printThemAll, -1); // nice way to clear last comma

    And a interesting case of using return statement I found out not a long time ago:
    —test.php—
    ‘thing’);
    ?>

    —index.php—

    It works )

    And absolutely usefull thing while creating a function receiving string or array as an argument:
    public function push($items) {
    foreach ((array)$items as $item) {
    $this->_items[] = $item;
    }
    }
    so that will work fine for both string and array values.

    • Yury Nedomolkin says:

      And a interesting case of using return statement I found out not a long time ago:
      —test.php—
      return array(‘some‘ => ‘thing’);

      —index.php—
      $array = include ‘test.php’;

      It works )

    • Yury Nedomolkin says:

      sorry. fix:

      $printThemAll = substr($printThemAll, 0, -1); // nice way to clear last comma

  4. changerOfSea says:

    1 == true works but 1 === true does not only true === true

  5. Todd Austin says:

    I use this to find any syntax errors via terminal:

    php -l filename.php

    This has helped me on many occasions find missing brackets, quotes, etc.

  6. Tony Lara says:

    filter_input() makes validating and sanitizing input data to your application easy.
    To access $_GET data sanitized is easy as

    instead of creating a full grown sanitizing system when it is not necessary.

  7. Charles Wang says:

    Its better to use the <?php opening tag rather than the shortcut <? for good practice.

    Also, it is always good to use variable names that clearly describe what its intended for. Non-descriptive variables can give many long headaches to other programmers that look at your code.

  8. reed roussel says:

    mamp, sequel pro, macgdbp, coda, and firephp make a wonderfully full featured local development environment for php on the mac.

    throw in a few coda plugins and tweak you apache config for multiple vhosts and it becomes even sweeter

  9. DominixZ says:

    I love this step when I want to $_POST key to be variable. Ex. i just submit “email”,”description”,”website”. Just use

    extract($_POST);
    insert_to_db($email,$description,$website);

    All Done!

  10. Always check for valid data and sanitise as necessary – never ever trust a user – especially with data input/database interaction – i can has book?

  11. Jeff Kes says:

    This book would help me learn more about PHP. Rock on.

  12. Rohan says:

    Develop a framework for yourself to use, and separate things into files and functions. Make everything reusable, use functions rather than fill up lines of non reusable code.

    Thats what I’ve learnt!

  13. jez says:

    Never have to update your copyright date manually:

  14. jez says:

    ini_set(‘date.timezone’, ‘Europe/London’);
    $startYear = 2006;
    $thisYear = date(‘Y’);
    if ($startYear == $thisYear) {
    echo $startYear;
    }
    else {
    echo “{$startYear}-{$thisYear}”;
    }

  15. Shane Parker says:

    The simplist thing that helped me when starting out was echo’ing my vars and print_r’ing my array’s. If you’re expecting a result, and you’re not getting it, just print it to see if it’s what you expect! var_dump() also provides even more info. For print_r, wrap it in tags so the output is formatted.

    • Shane Parker says:

      Good grief, how does a site based on web development not have a comments plugin that allows us to post code? C’mon guys!

      “For print_r, wrap it in tags so the output is formatted” should have been “wrap it in ‘pre’ tags”.

  16. Shaymol says:

    Never trust user data. always filter user data when saving at database to avoid sql injection (http://en.wikipedia.org/wiki/SQL_injection) and escape output before rendering to avoid XSS (http://en.wikipedia.org/wiki/Cross-site_scripting)

    ex.

    1. to validate specific type of data you can use is_* (is_numeric, is_int) or ctype_* (ctype_digit, ctype_alnum)
    2. in preparing sql query escape user data by using mysql_escape_string() or mysql_real_escape_string()
    3. when rendering user data at output, escape user data by using htmlentities()

    For more info google with each function or do php.net/fucntion_name .ex php.net/htmlentities

  17. Maxime says:

    I like to use ternary operator:

    1 ? ‘s’ : ”;
    ?>

  18. Derk says:

    Shortened If-Else Structure.

    Here is an example of a regular If-Else structure, used by most people:

    $var = 5;
    if($var > 5){
    echo(“var is bigger than 5″);
    } else {
    echo(“var is equal or smaller than 5″);
    }

    Now this, is quite a lot of code for such a simple thing. This if-Else structure can be shortened like this:

    $var = 5;
    echo ($var >5) ? “var is bigger than 5″ : “var is smaller equal or smaller than 5″;

    this eliminates the unnecessary use of multiple echos, writing the If-Else and the brackets. In the long run this could really shorten your filesize and it makes the code look a lot more structured have it all on 1 line.

  19. Ian Murray says:

    To comment out a comment block:

    /*
    Lots of code you don’t want to execute right now but maybe later
    //*/

    Using those “special” comment tags /* and //*/ you cant uncomment the entire comment block by simply changing the first comment to //*

    //*
    Lots of code you don’t want to execute right now but maybe later
    It’s being executed now =)
    //*/

    Try it! Pretty neat.

  20. Gregory Daynes says:

    Find out which user PHP is running as, helpful for ‘chown’

    • Gregory Daynes says:

      Find out which user PHP is running as, helpful for ‘chown’

      “echo exec(‘whoami’);”

  21. Comment/Document your code. It really helps when you come back after a period of absence and can’t remember what you did!

  22. As with most languages, start learning the fundamentals of the language before jumping into a framework. I see a lot of people try to pick up CodeIgniter because it’s supposed to be easier and faster than coding regular PHP. However, without an understanding of the what’s going on behind the scenes, it’s not that useful and will really limit what you can do with PHP in the long run.

  23. If you are attempting to accept file uploads via php, it is possible to increase/change the maximum file upload size by accessing the ini.php file. If you don’t have direct access to the ini.php file you can use the following function instead:

    string ini_set ( string $varname , string $newvalue )

    Here is a link for more info about the function
    http://php.net/manual/en/function.ini-set.php

  24. Marcus Schumann says:

    #1. Comment a lot. It will literally save you DAYS of work when going back and backtracing a problem or just revising an old code.

    #2. Check NetTuts, duh? They have a lot of PHP-tutorials including Quick Tips and how-to’s.

    #3. If stuck, check php.net. Alternatively you can google if you’re not sure what to search for on php.net

  25. Rob says:

    My tip: Try and take more time to plan the methods in your class before you begin coding it – make them work together instead of writing specific ones for specific tasks, else you end up with hundreds (voice of experience lol) Also – it’s not that hard, you will always – always get better – you have a brain so nothing is impossible.

    writing this on the write page now :D

  26. Jay Volk says:

    Would love a chance to win this book. Thanks for the opportunity.

  27. Patrick says:

    Tip 1: Never mix HTML with PHP or PHP with HTML. If your project grows it’ll be much more harder to maintain your code. Use a template system like smarty or – even better: write your own one. It’s not as hard as it sounds.

    Tip 2: Use MySQLi für Database requests! If you’re smart enough you can display a huge website with only 20 database requests – included statistics, session management and so on!

    Tip 3 is based on tip 1 and more a mysql tip:

    Use JOINs and INDEXes! You can create an index over one or more columns.

    Lets try a theory:

    For a news table you can give your index a name like “news_index” over the columns “news_category_id”, “news_date_posted” and “news_author_id”.

    If you’re smart enogh you don’t need a news index for a user table or for a category table, because you have already one – the PRIMARY key.

    Now, you want to display the name of the category and the author’s name everytime a news is displayed. Some of you will do 1 database request for the newslist, and for every news 2 more requests for the names. If you want do display 10 news, you will have 20 database requests plus 1 for the news. Too much!

    Now, its possible to get ALL news with only 1 request:

    SELECT
    n.news_text, n.news_author_id, n.news_category_id,
    c.category_id, c.category_name,
    u.user_id, u.user_name
    FROM
    prefix_news AS n
    INNER JOIN
    prefix_categories AS c
    ON
    c.category_id=n.category_id
    INNER JOIN
    prefix_users AS u
    ON
    u.user_id=n.news_author_id
    LIMIT 0,10

    This will give you exactly 10 news included the names of the author and category with only 1 request.

    To speed this up, it’s not a bad idea to use FORCE KEY in the SQL statement:

    SELECT
    n.news_text, n.news_author_id, n.news_category_id,
    c.category_id, c.category_name,
    u.user_id, u.user_name
    FROM
    prefix_news AS n FORCE KEY (news_index)
    INNER JOIN
    prefix_categories AS c FORCE KEY (PRIMARY)
    ON
    c.category_id=n.category_id
    INNER JOIN
    prefix_users AS u FORCE KEY (PRIMARY)
    ON
    u.user_id=n.news_author_id
    LIMIT 0,10

    In some cases this could speed up your scripts up to 400 percent! In general you could say: The more complicated the statement, the more time you can save when you use FORCE KEY.

    To optimize this effect, use tip 4!

    Tip 4: Analyze and pptimize your MySQL-tables! If your site slows down, this will help. Use “ANALYZE tablename” or “OPTIMIZE tablename”. All indexes will be overhauled, trash will be deleted and the size of the database will shrink.

    Hope, this will help someone.

  28. Matt says:

    Write helper functions to speed up mundane repetitive tasks to you use across all projects.

  29. Dejan says:

    Always start your php code blocks with <?php instead of the short <?.

    Greetings

  30. John Morton says:

    My PHP tip? Well, it sounds too easy, but use comments. A lot of them. Also, I keep a folder of PHP ‘cheat’ files, as well as ‘cheat’ files for other languages. By that I mean make simple little files that do a single things, like validate a string as an email address for example. Those files can be anything you find yourself doing multiple times. Over time, it becomes really handy personal resource.

  31. chilts says:

    always filter any user inputting data that is being used to query a database:

    $sql = sprintf(“SELECT * FROM user_accounts WHERE username = ‘%s’”, mysql_real_escape_string($_POST['email']));

    sprintf: to make sure the data inserted into the string is the data type you want: string, int, etc.
    mysql_real_escape_string: to escape any sensitive characters for the mysql

  32. One pretty interesting tip is regarding a boolean value, which is a bit unusual. Look at the following code:

    $boolean = sqrt(2.0) * sqrt(2.0) – 2.0

    if ($boolean)
    print (“A bit surprising, right?”);
    else
    print (“You were lucky”);
    print (“boolean = $boolean”);

    It’s not at all a common thing, but I like to know these little tricks, because you never know what use can you make of them. Anyway, the thing here is that there could be some problems with the rounding. In this example as you can see, square root of two multiplied by square root of two (which of course should be 2, but because of the rounding is just almost two) minus two is NOT zero, so instead of getting a FALSE value, we get a TRUE value.

    I’m not very advanced in PHP, but the book Jason is offering would be of very much help. Good luck to everyone :)

  33. Jak says:

    What helped me start getting a handle on PHP was watching the “Diving into PHP” series from Nettuts!

    Seriously!

    Since then, the FirePHP plugin has been very helpful (though I have to disable it when I use the User Agent Switcher plugin, lest it add undesirable bits to the end of the user agent).

  34. Federico Alvarez says:

    It is good practice to create a class “Persistence” (MySQL Handler) or download one. Methods like “save()” or “update()” can save your life and lot of work (You’ll never have to do an “INSERT INTO” statement ! :D ).
    Logical classes then inherit the persistence class, making it easier all the work.

    I Hope you like this.
    (Sorry for my english!)

  35. Using PHPUnit or Simpletest will save you time in the long run.

  36. Realmaker says:

    For all the german readers here is a very good introduction into the php and mysql basics: http://www.schattenbaum.net/php/anfang.php

  37. Wechr says:

    Use a caching system like memcached to speed up your database load: http://memcached.org/

  38. Kasakka says:

    If you have problems uploading very large files via PHP, you may have to check the PHP settings for maximum allowed filesizes. The defaults aren’t that big and you don’t get any error message when the upload fails.

    Also when handling files, it’s a good idea to check the MIME type of the file as well as the extension before processing further.

  39. ChrisS says:

    A fast shortcut to looking up functions, parameters, etc. in the PHP manual is to append the function name after php.net, e.g. http://php.net/explode will take you to http://php.net/manual/en/function.explode.php

  40. Nick Mertz says:

    Here are some of my tips:

    1. If I am stuck with a particular piece code, I always use var_dump() to see what kind of result I am being returned. I find this especially helpful when working with arrays.

    2. It does not hurt to examine other people’s code just to see how they handle a particular situation or problem. Use that as a learning tool to help you come up with your own solutions.

    3. Reference php.net. It has a vast array of documentation that can help anyone understand php.

  41. Logie says:

    This is how I altered an example from NetTuts.

    For listing all different images inside different folders.

    I.E.

    Folder Structre;
    - Gallery
    – July-04
    — Image.jpg
    — Image.jpg
    — Image.jpg
    — Image.jpg
    – July-08
    — Image.jpg
    — Image.jpg
    – July-10
    — Image.jpg
    — Image.jpg
    — Image.jpg
    — Image.jpg

    It will echo out like this.
    July-05
    ImageName.jpg
    ImageName.jpg
    ImageName.jpg
    ImageName.jpg

    etc..

    Found it useful for applying it to my Galleria folder by assigning unique ids to each listing and then calling Galleria to apply to each listing ;P Worked well!

      • Logie says:

        Sorry guys I didn’t know we weren’t allowed the PHP tags.

        //Loop each folder in the gallery folder
        //Change the directory to match your own.
        foreach(glob(‘images/gallery/*’, GLOB_ONLYDIR) as $longFolder) {
        //Split the folders up by “/”
        $arrayFolder = explode(“/”, $longFolder);

        //End folder name should always be position 2
        //Unless your directory has more than 2 slashes.
        $folder = $arrayFolder[2];

        //Echo folder
        echo $folder;

        //Now loop each image of the folder we got above
        foreach(glob(‘images/gallery/’ . $folder . ‘/*’) as $image) {
        //Echo out the img source
        echo ‘Image Name – ‘ .$image;

        }

        }

  42. epochdev says:

    Always sanitize your database entries:

    mysql_real_escape_string( strip_slashes( htmlentities( trim( $value ),ENT_QUOTES,’UTF-8′) ) );

  43. chrisberthe says:

    If you’re a beginner programmer and are learning PHP, there will undoubtedly be times where you will get frustrated and feel clueless. Although not necessary, I highly recommend to learn another / more object oriented programming language prior to learning PHP, such as Java or C. This helped me to learn PHP much faster and more efficiently.

    Also, when building applications, focus primarily on developing the execution of your code rather than the design. Once you have something that is concrete, you can then modify in such a way to make it more compact and understandable; e.g ternary operation.

  44. Sun Pietro says:

    mb_strtolower and mb_strtoupper were very useful for me to change the Polish letters within PHP for my OWL search engine

  45. Ryan says:

    make sure you know where your php logs are going and check them frequently. They can be invaluable for debugging.

  46. Dalibor Sojic says:

    Protect mail addresses from spam spiders. This is originaly CI hook and I plan to do screencast for CI hooks with this example.

    php

    Before show the output, call this function.

    function despammail($text) {

    $regExMail = “/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i”;
    preg_match_all($regExMail, $text, $mails);

    if ($mails[0]) {

    $search = array(‘@’, ‘.’);
    $replace = array(‘ [at] ‘, ‘ [dot] ‘);

    foreach ($mails[0] as $key=>$mail) {
    $protectedMails[$key] = str_replace($search, $replace, $mail);
    }

    foreach ($protectedMails as $key=>$mail) {
    $result[$key] = ”.$mail.”;
    }

    $text = str_replace($mails[0], $result, $text);
    }
    return $text;
    }

    javascript jquery: (call on document complete)
    $(‘.mail’).each(function(i) {
    /* <![CDATA[ */
    var mail = ($(this).text());
    mail = mail.replace(' [dot] ', '.');
    mail = mail.replace(' [at] ', '@');

    var result = '‘+mail+’‘;
    // x = result.replace(‘ [dot] ‘, ‘.’);

    $(this).html(result);
    /* ]]> */
    });

  47. Philip Brown says:

    My tip would be to create helper functions or packages within a Singleton Class and check out PDO. PDO is the best for connecting with different types of databases.

  48. Gregory Pike says:

    Follow Net Tuts :P

  49. $array = array(1,2,3,4,5);

    Arrays lengths are not obtained the same way in PHP as in many other languages using an object’s function like:

    //wrong code
    $value = $array.length;

    Instead a php method is used

    //right
    $value = count($array);

Comment Page 5 of 15 1 ... 3 4 5 6 7 ... 15

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.