1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Guidelines, Tips & Frequently Asked Questions

Discussion in 'PHP' started by premiumscripts, Sep 3, 2009.

Thread Status:
Not open for further replies.
  1. #1
    Table of Contents

    1.1 Format your code
    1.2 Relevant code only
    1.3 Add context
    1.4 Post your error logs
    1.5 Are you posting in the correct section?
    1.6 Search before you post

    2. Tips
    2.1 I want to learn PHP
    2.2 PHP Editors
    2.3 Installing PHP on your local system
    2.4 Debugging your PHP scripts
    2.5 Benchmarking your PHP scripts

    3. Frequently asked questions
    3.1 How do I increase the maximum upload filesize?
    3.2 I receive the error "Headers already sent out"
    3.3 How do I set up a unicode enabled site?
    3.4 How do I secure my script?
    3.5 What are web frameworks?
    3.6 What is MVC?


    1.1 Format your code

    Your code should be in a readable form if you expect any help. Add [ php ] .. [ /php ] (without the spaces) around your code so that it is syntax highlighted and easier to read. If you're just posting HTML, use [ HTML] .. [ /HTML ]. If you're mixing PHP and HTML in the same snippet, use [ CODE ] .. [ /CODE ] instead.

    Additionally, you may want to use an online code beautifier if your code is really messy (lots of whitespace where it shouldn't be, etc..) You can try http://www.codeassembly.com/examples/beautifier.php

    Use the preview button before posting so you can verify that everything is nicely formatted.

    1.2 Relevant code only

    Only add the section of the script that is relevant to your question.

    1.3 Add context

    If your script isn't working correctly, show the input you supplied, the output you received, and how that output is different from what it should be.

    Post a link to your site (if available) and to any javascript or CSS that is relevant to your problem.

    1.4 Post your error logs

    Check your PHP/Apache error logs and add the error messages to your post.

    If you do not have access to your error logs, add this snippet of code at the top of your script (or just before the line where the error occurs):

    ini_set('display_errors', 1);
    Then refresh your page, and copy the error messages you see to your post.

    1.5 Are you posting in the correct section?

    - Javascript questions go in the javascript forum, mod_rewrite questions go in the apache forum, mysql questions go in the mysql forum.

    - "I'm looking for a script that does X" : Please post in the scripts forum instead.

    - "I have an issue with a script I bought" : Ask the script developer for help first, as he/she is most qualified to help you correctly.

    - "I don't know php and I want you to fix this pretty complicated string of issues free of charge" : You should probably consider hiring someone instead.

    1.6 Search before you post

    Before you post a new thread, search the forum. Chances are a similar question has already been answered.

    It's also expected that you at least do a google search as well.

    2. Tips

    2.1 I want to learn PHP

    I really recommend you buy yourself a book, which you can use in addition to online resources. Often times, scripts and examples you find online are riddled with bugs. If you get yourself a good book, you'll be able to spot these more easily. Additionally, most online resources aren't up to date in the latest developments of PHP. For example, w3schools still teaches you how to use the mysql extension, while you really should use mysqli or PDO (preferred) instead.

    Online Resources

    Your go-to site should be PHP.net, learn to love it. Use it to look up function definitions, code samples and more. Whenever you have an issue with a specific function, first go to http://www.php.net/function_name

    Read the comments, someone may have very well already had the same issue.

    Other resources:

    Beginner Video Tutorials
    Practical PHP (Free book)
    Zend Developer Zone (PHP 101 series)


    PHP & mysql web development
    Beginning PHP & mysql

    PHP Objects, patterns & practices
    Pro PHP: Patterns, frameworks, testing & more

    There are many other good books, just browse amazon and read the reviews.

    2.2 PHP Editors

    There are quite a few PHP editors and everyone has his/her own preference. That's why I included this list, not in any particular order.


    2.3 Installing PHP on your local system

    I recommend you use XAMPP (mac or win), WAMP (win), or MAMP (mac) - These will automatically install apache/php/mysql on your system, requiring no extra configuration. Great for a development system.

    2.4 Debugging your PHP scripts

    The first thing you should do is enable error messages:

    In php.ini

    display_errors = On
    error_reporting = E_ALL
    Code (markup):
    Pure PHP

    ini_set('display_errors', 1);
    TODO: This section is not yet finished..

    PHPEclipse Plugin for Eclipse

    2.5 Profiling your PHP scripts (Performance Benchmarking)


    Todo: This section is not yet finished..



    3.1 How do I increase the maximum upload filesize?

    You have two options, either edit your php.ini or add some settings to your .htaccess file.

    For the php.ini method:

    upload_max_filesize = "20M";
    post_max_size       = "20M";
    Code (markup):
    If you don't have SSH to edit your php.ini file, it's sometimes possible just to create a new file called php.ini or php5.ini and place it in your root dir. This is dependent on where you're hosted so you should check with your host.

    Don't try to set these values via ini_set(), it won't work. By the time the script is executed the upload will already be cancelled.

    For the .htaccess method:

    php_value upload_max_filesize "20M"
    php_value post_max_size "20M"
    Code (markup):
    You may also want to set a few other variables if your upload is still failing:

    - max_execution_time (can be set via ini_set())
    - max_input_time
    - memory_limit

    3.2 I receive the error "Headers already sent out"

    You probably received this error when you wanted to set a cookie, start a session, or send a HTTP header to the browser. None of these things can occur if output has already been sent to the browser.

    This means you must ensure that these functions are called before you output anything. If you can't control this, the easiest solution is to simply add the following statement at the top of your script:

    This will enable output buffering, which means that no output is sent from the script until the end of script.

    If you want to, you can add the following line at the end of the script, though it's not necessary:

    3.3 How do I set up a unicode enabled site?

    Setting up your code editor

    Either only use ASCII in your PHP scripts, or make sure your editor saves the pages in UTF-8, without adding a BOM (byte order mark) at the beginning of the file.

    Define the encoding

    Add this to your PHP page:

    header('Content-Type:text/html; charset=UTF-8');
    Add this in your HTML:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    Setting up your database

    Set the character set to utf8 and use the utf8_general_ci collation for your database and tables.

    You'll also have to set the collation for each specific column you want in unicode.

    In PHPMyAdmin, you can set up the collation on the operations tab for your DB & tables.

    Connecting to your database

    If the function is available, use mysql_set_charset / mysqli_set_charset :

    mysql_set_charset('utf8', $link);
    Otherwise, execute these queries before any others: (same for PDO)

    mysql_query("SET NAMES 'utf8'");
    mysql_query("SET CHARACTER SET utf8 ");
    Processing input

    Functions like strlen, strtolower, ucfirst, stristr, etc.. won't work correctly with unicode input. Instead, you'll have to install the MBString extension and then use the multibyte safe equivalent function.

    This is typically "mb_" + the function name. So strlen becomes mb_strlen, and so on.

    You'll want to add the following to your php.ini:

    mbstring.language               = Neutral;
    mbstring.internal_encoding      = UTF-8
    mbstring.encoding_translation   = On 
    mbstring.http_input             = auto	
    mbstring.http_output            = UTF-8	
    mbstring.detect_order           = auto		
    mbstring.substitute_character   = none	
    default_charset                 = UTF-8	
    Code (markup):
    Outputting text

    If you're using htmlspecialchars or htmlentities, make sure you specify the third argument and set it to UTF-8:

    echo htmlentities($text, ENT_COMPAT, 'UTF-8');
    echo htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
    More info:


    3.4 How do I secure my script?


    - Essential PHP security
    - PHP Architect's Guide to PHP Security
    - Pro PHP security
    - Securing PHP Web Applications

    Note that some of these books are already a few years old, new techniques aren't described in them but they're still good for a general overview.


    All the below tips are conceptual in nature, this is by no means a complete list.

    - Filter all input

    Assume all data in $_GET, $_POST, $_COOKIE and $_REQUEST are dirty.
    Even data from $_SERVER can come from the client ($_SERVER['PHP_SELF'], $_SERVER['HTTP_REFERER'] etc)

    You can use the filter functions: http://en.php.net/manual/en/ref.filter.php or write your own functions.

    Use HTML Purifier to prevent XSS attacks.

    - Escape all output

    Use htmlspecialchars / htmlentities on untrusted data to prevent cross site scripting.

    Make sure that you are also specifying the charset argument to these functions, if you don't, new security problems may be introduced.

    htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
    If you want to allow HTML, you should use HTML purifier in the input filter stage (before saving to the database)

    - Use form tokens to prevent CSRF

    - Prevent SQL injection
    Don't just use addslashes or magic quotes. In fact, disable magic quotes right now!

    Instead, use PDO and prepared statements. Or if you're still using the mysql functions directly, use mysql(i)_real_escape_string.

    - Disable magic_quotes and register_globals.
    You should not rely on this functionality and it's already deprecated. It will be removed completely from PHP 6.

    - Prevent session hijacking and fixation.

    Only use cookies for sessions.
    Use session_regenerate_id(true) after changing a user's authorization level.
    http://carsonified.com/blog/dev/how-to-create-bulletproof-sessions/ (be sure to read the comments as well)

    - Keep configuration files (such as database passwords) outside of web accessible directories.

    - Better yet, move all PHP files outside of the web directory and use route all requests through a front controller (index.php) - This can be set up via a rewriterule.
    Why do this? Because after an apache or php upgrade something might have gone wrong and your PHP files are suddenly displayed as text instead of executed. (Happened to facebook)

    - Add brute force login protection. (5 tries, then 30 minutes lockout, or a similar system)

    - Do not store plain text passwords in the database. Hash them (md5 or sha1). Be sure to add a salt (unique for each value), otherwise the password can be easily reverse-engineered via a dictionary.

    - Always use the latest stable version of PHP

    - Use SSL if sensitive data is being processed (such as credit card details)

    - Never fetch a remote file via include(), always use file_get_contents or CURL.
    You may want to disable allow_url_fopen.

    - Disallow remote connections to your database if you don't need them.

    - Make sure that all uploaded files are indeed the types of files you want to allow. Don't just rely on mimetype, that can be spoofed. Clean the filename.

    - ....


    - PHPSecInfo

    PHPSecInfo is a script that will check some of your system settings to see if they're set up correctly.

    - Suhosin

    Suhosin is an advanced protection system for PHP installations. It was designed to protect servers and users from known and unknown flaws in PHP applications and the PHP core.

    - Mod Security

    Mod Security is an open source web application firewall.

    - PHP IDS

    Similar to mod_security.

    3.5 What are web frameworks?

    The wikipedia description is:

    Using a framework helps you stay focused on what is really important, your application and it's functionality. It saves you time.

    A couple of the benefits that frameworks provide are:

    - Easier DB access
    - Authentication
    - Internationalization
    - Input validation
    - Caching
    - Security
    - Error handling

    I generally recommend frameworks because alot of people, whether they know it or not, aren't very good at PHP. Their code is a complete mess that is almost always unreadable, insecure and very hard to update. At least with a framework, you have a sort of structure that has to be followed, which enforces at least some security standards and makes it easier for others to continue the work.

    Examples of well known PHP web frameworks are:

    Yii framework
    Zend Framework

    3.6 What is MVC?
    MVC stands for Model / View / Controller.

    Some tutorials on how to write your own MVC framework:

    premiumscripts, Sep 3, 2009 IP
  2. szalinski

    szalinski Peon

    Likes Received:
    Best Answers:
    Trophy Points:
    Fantastic, an excellent FAQ which proves you can never know enough :)

    About enabling the Unicode website part (3.3) though: if php6 is 'going to support unicode' then how is it possible to even use unicode in php5 - or are you suggesting this will only work when php6 is released? thanks.
    szalinski, Sep 3, 2009 IP
  3. premiumscripts

    premiumscripts Peon

    Likes Received:
    Best Answers:
    Trophy Points:
    Szalinski, this guide is for PHP 5. PHP 6 will support unicode built in - right now you have to use iconv or mbstring extensions if you want to use PHP. And there's other problems that will be solved in php6 as well concerning localization, sorting, searching & encoding detection.
    premiumscripts, Sep 3, 2009 IP
Thread Status:
Not open for further replies.