Table of Contents
1. GUIDELINES
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. GUIDELINES
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):Then refresh your page, and copy the error messages you see to your post.php Code:
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:
W3Schools
Tizag
PHPFreaks
Beginner Video Tutorials
Practical PHP (Free book)
Zend Developer Zone (PHP 101 series)
Books
Beginner:
PHP & mysql web development
Beginning PHP & mysql
Advanced:
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.
http://www.aptana.com/php
http://www.phpeclipse.com/
http://www.zend.com/products/studio/
http://phpanywhere.net/
http://www.activestate.com/komodo/
http://www.netbeans.org/features/php/index.html
http://www.nusphere.com/products/phped.htm
http://www.phpedit.com/en
http://macromates.com/
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.iniPure PHPCode:display_errors = On error_reporting = E_ALLTODO: This section is not yet finished..php Code:
PHPEclipse Plugin for Eclipse
http://www.ibm.com/developerworks/library/os-debug/
http://devzone.zend.com/article/2930...ns-with-xdebug
https://addons.mozilla.org/en-US/firefox/addon/3960
2.5 Profiling your PHP scripts (Performance Benchmarking)
http://particletree.com/features/php-quick-profiler/
Todo: This section is not yet finished..
http://code.google.com/p/webgrind/
http://www.firephp.org/
http://www.xdebug.org/
3. FREQUENTLY ASKED QUESTIONS
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: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.Code:upload_max_filesize = "20M"; post_max_size = "20M";
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:You may also want to set a few other variables if your upload is still failing:Code:php_value upload_max_filesize "20M" php_value post_max_size "20M"
- 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.php Code:
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?php Code:
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:Add this in your HTML:php Code:Setting up your databasehtml4strict Code:<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
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 :Otherwise, execute these queries before any others: (same for PDO)php Code:Processing inputphp Code:
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:Outputting textCode: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
If you're using htmlspecialchars or htmlentities, make sure you specify the third argument and set it to UTF-8:More info:php Code:
http://ferdychristant.com/blog/articles/DOMM-7LDBXK
http://webcollab.sourceforge.net/unicode.html
http://htmlpurifier.org/docs/enduser-utf8.html
3.4 How do I secure my script?
Books
- 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.
Tips
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.If you want to allow HTML, you should use HTML purifier in the input filter stage (before saving to the database)php Code:
- Use form tokens to prevent CSRF
http://codeutopia.net/blog/2008/10/1...ll-your-forms/
- 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-...roof-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.
- ....
Tools
- 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 web application framework is a software framework that is designed to support the development of dynamic websites, Web applications and Web services. The framework aims to alleviate the overhead associated with common activities performed in Web development. For example, many frameworks provide libraries for database access, templating frameworks and session management, and often promote code reuse.
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
Codeigniter
Kohana
Cakephp
Zend Framework
3.6 What is MVC?
MVC stands for Model / View / Controller.Some tutorials on how to write your own MVC framework:An MVC application is a collection of model/view/controller triplets (a central dispatcher is often used to delegate controller actions to a view-specific controller). Each model is associated with one or more views (projections) suitable for presentation (not necessarily visual presentation). When a model changes its state, it notifies its associated views so they can refresh. The controller is responsible for initiating change requests and providing any necessary data inputs to the model.
http://www.phpro.org/tutorials/Model...oller-MVC.html
http://www.onlamp.com/pub/a/php/2005...ontroller.html
http://www.anantgarg.com/2009/03/13/...mework-part-1/