Five suggestions on PHP security

Source: Internet
Author: User
Tags bbcode

The combination of Chinese and English is really good. I have previously reposted my summary of PHP security programming. Some people say it's an old growth talk. This time, let's look at the works of foreign friends. According to the latest survey, the usage of PHP language has exceeded that of the old language C ++, becoming the third-party Programming Language . It has many useful functions, but there may be many problems. This article Article Five common suggestions are listed to help you create secure PHP applications. PHP is one of the most popular programming languages for the web. sometimes a feature-friendly language can help the programmer too much, and security holes can creep in, creating roadblocks in the development path. in this tutorial, we will take a look at 5 tips to help you avoid some common PHP security pitfalls and Development glitches. Recommendation 1: use error reports as appropriate

Tip 1: error reports are useful during use proper error reporting. It helps you find a series of problems. However, if you still enable this function in a formal application, it will enrich the information for malicious users. You canCodeAdd error_reporting (0) before. If you want to know about some problems, enter the error report to a protected file. This can be done using the set_error_handler function.

During the development process, application error reporting is your
Best friend. error reports can help you find spelling mistakes in your
Variables, detect incorrect function usage and much more. However, once
The site goes live the same reporting that was an ally
Development can turn traitor and tell your users much more about your
Site than you may want them to know (the software you run, your folder
Structure, etc ).

Once your site goes live, you should make sure to hide all error
Reporting. This can be done by invoking the following simple function
At the top of your application file (s ).

Error_reporting (0 );

If something does go wrong, you still want and need to know about
It. Therefore, you shoshould always make sure to log your errors to
Protected file. This can be done with the PHP function set_error_handler.

Suggestion 2: Disable the bad function of PHP Tip 2: PhP developers in the early days of disable PHP's "bad features" liked to add some special features, many of which have been proven to be bad and may cause many security problems. They may be banned in the upcoming PhP6.

Register globals (register_globals)

It seems that PhP5 has been banned by default. Magic quotes (magic_quotes_gpc, magic_quotes_runtime, magic_quotes_sybase) Disable magic_quotes_gpc = off by modifying PHP. ini.
Magic_quotes_runtime = off
Magic_quotes_sybase = off
From its earliest days, PHP's designers have always supported ded some
Features to make development easier. Or so they thought! Some of these
Helpful features can have unintended consequences. I call these "bad
Features "because they have allowed data validation nightmares and
Created a pathway for bugs to finding their way into scripts. One
The first things you shoshould do when the development process begins is
Disable certain of these features.

Note: depending on your host, these may or may not be turned off
You. If you are developing on your own computer or other similar local
Environment, they probably won't be turned off. Some of these features
Have also been removed in the upcoming PhP6, but are ubiquitous in PhP4
Applications and are only deprecated in PhP5 applications.

Register globals (register_globals)

In short, register_globals was meant to help rapid application
development. take for example this URL,
http://yoursite.tld/index.php? Var = 1, which has des a query string. the
register_globals statement allows us to access the value with $ var
instead of $ _ Get ['var'] automatically. this might sound useful to you,
but unfortunately all variables in the Code now have this property, and
we can now easily get into PHP applications that do not protect against
This unintended consequence. the following code snippet is just one
common example you will see in PHP scripts:

If (! Empty ($ _ post ['username']) & $ _ post ['username'] = 'test '&&! Empty ($ _ post ['Password']) & $ _ post ['Password'] = "test123 ")
$ Access = true;

If the application is running with register_globals on, a user cocould
Just place access = 1 into a query string, and wocould then have access
Whatever the script is running.

Unfortunately, we cannot disable register_globals from the script
Side (using ini_set, like we normally might), but we can use
. Htaccess files to do this. Some hosts also allow you to have a PHP. ini
File on the server.

Disabling with. htaccess

Php_flag register_globals 0

Disabling with PHP. ini

Register_globals = off

Note: If you use a custom PHP. ini file that is not applicable to
Entire server, you must include these declarations in every sub folder
That has PHP.

Magic quotes (magic_quotes_gpc, magic_quotes_runtime, magic_quotes_sybase)

Magic quotes was a feature meant to save programmers the trouble
Using addslashes () and other similar security features in their code.
There are at least three problems associated with magic quotes. One
Problem with this helpful feature is if both magic quotes and
Addslashes () are used. If this is the case, then you end up
Multiple slashes being added, causing errors. The second problem is if
You make the assumption magic quotes is turned on and it actually is
Not. Then all the input goes unchecked. The third problem is that magic
Quotes only escapes single and double quotes, but if you are using
Database Engine, there are also databases-specific characters that
Also need to be escaped. It is recommended use that you disable this
Feature and use proper variable validation instead (see below ).

Unfortunately, we also cannot disable magic quotes from the script
Side using ini_set. As with register_globals, we can use. htaccess or
PHP. ini files to do this.

Disabling with. htaccess

Php_flag magic_quotes_gpc 0 php_flag magic_quotes_runtime 0

Disabling with PHP. ini

Magic_quotes_gpc = off
Magic_quotes_runtime = off
Magic_quotes_sybase = off

Note: If you use a custom PHP. ini file that is not applicable to
Entire server, you must include these declarations in every sub folder
That has PHP.

Suggestion 3: Verify input Tip 3: validate input is very important to verify the input data. For example, the input date in the birthday cannot exceed 31. You can use a regular expression for verification, but that is the final action. Previously, we can use the compile function to check the PHP manual, and you will find a lot. The latest PHP version will include many verification functions, such as the e-mail address verification function. In addition to escaping characters, another great to way to protect
Input is to validate it. With your applications, you actually already
Know what kind of data you are expecting on input. So the simplest way
To protect yourself against attacks is to make sure your users can only
Enter the appropriate data.

For example, say we are creating an application that lists users
Birthdays and allows users to add their own. We will be wanting
Accept a month as a digit between 1-12, a day between 1-31 and a year
In the format of YYYY.

Having this kind of logic in your application is simple and regular
Expressions (RegEx) are the perfect way to handle input validation.
Take the following example:

If (! Preg_match ("/^ [0-9] {1, 2} $/", $ _ Get ['month'])
// Handle error
If (! Preg_match ("/^ [0-9] {1, 2} $/", $ _ Get ['day'])
// Handle error
If (! Preg_match ("/^ [0-9] {4} $/", $ _ Get ['Year'])
// Handle error

In this example, we simply checked (in the first two if statements)
For integers [0-9] with a length of one or two {1, 2} and we did
Same in the third if statement, but checked for a strict length of 4
Characters {4 }.

In all instances, if the data doesn't match the format we want, we
Return some kind of error. This type of validation leaves very little
Room for any type of SQL attack.

RegEx expressions like those abve can be a little difficult
GRASP at first, But explaining them is out of the scope of this
Article. The PHP manual has some additional resources to help you with validation. The pear database also has a few packages such as the validate package to help with emails, dates, and URLs.

Below is an example of the above script in action using 200 as an input for a month, ABC for the day and just 09 for the year.

Suggestion 4: Be careful with cross-site scripting Tip 4: Watch for cross site scripting (XSS) attacks in user input. If HTML editing is allowed in your application, be careful when your users insert JavaScript, it may create cross-site scripting attacks to steal data from cookies. Using code instead of technology can improve this situation. Here is a popular code package: html_bbcodeparser

A Web application usually accepts input from users and displays it
In some way. This can, of course, be in a wide variety of forms
Including comments, threads or blog posts that are in the form of HTML
Code. When accepting input, allowing HTML can be a dangerous thing,
Because that allows for JavaScript to be executed in unintended ways.
If even one hole is left open, your script can be executed and cookies
Cocould be hijacked. This cookie data cocould then be used to fake a real
Account and give an illegal user access to the website's data.

there are a few ways you can protect yourself from such attacks. one
way is to disallow HTML altogether, because then there is no possible
way to allow any JavaScript to execute. however, if you do this then
formatting is also disallowed, which is not always an option for Forum
and blog software.

if you want HTML mostly disabled, but still want to allow simple
formatting, you can allow just a few selected HTML tags (without
attributes) such as or . or, alternatively,
you can allow a popular set of tags called "bbcode" or "BB tags, "
commonly seen on forums in the format of [B] test [/B]. this can be a
perfect way to allow some formatting customization while disallowing
anything dangerous. you can implement bbcode using pre-existing
packages such as html_bbcodeparser or write your own bbcode implementation with regular expressions and a series of preg_replace statements.

Recommendation 5: Prevent SQL injection attacks Tip 5: Protecting against SQL injection the most common problem is SQL injection. (') and (") are prone to problems. There are many tutorials on the Internet, pay attention to it. PHP has many solutions, such as mysqli: $ username = mysqli_real_escape_string ($ get ['username']);
Mysql_query ("select * From tbl_members where username = '". $ username. "'"); Last, but not least, is one of the most well-known security attacks
On the web: SQL Injection. SQL injection attacks occur when data goes
Unchecked, and the application doesn't escape characters used in SQL
Strings such as single quotes (') or double quotes (").

If these characters are not filtered out users can exploit the system by making queries always true and thus allowing them to trick login systems.

Luckily, PHP does offer a few tools to help protect your database
Input. When you are connected to an SQL Server you can use these
Functions with a simple call, and your variables shocould be safe to use
In queries. Most of the major database systems offered with PHP Include
These protection functions.

Mysqli allows you to do this in one of two ways. Either with the mysqli_real_escape_string function when connected to a server:

$ Username = mysqli_real_escape_string ($ get ['username']);
Mysql_query ("select * From tbl_members where username = '". $ username ."'");

Or with prepared statements.

Prepared statements are a method of separating SQL logic from the data being passed to it. the functions used within the mysqli library filter our input for us when we bind variables to the prepared statement. this can be used like so (when connected to a server ):

$ Id = $ _ Get ['id'];
$ Statement = $ connection-> prepare ("select * From tbl_members where id =? ");
$ Statement-> bind_param ("I", $ id );
$ Statement-> execute ();

One thing to note when using prepared statements is the "I" in bind_param. I stands for integer but you can use S for string, D for double, and B for BLOB depending on what data we are passing.

Although this will protect you in most circumstances, you showould
Still keep in mind proper data validation as mentioned previusly.

At the end of the closing short article, we want to tell us that we are concerned about PHP application security. For more information, see Security in the PHP manual this short tutorial can only scratch the surface of Web security.
Ultimately, it is up to developers to ensure that the applications they
Build are safe by educating themselves about the dangers of the Web and
The most common kinds of vulnerabilities and attacks. if you want
Read more about security issues in PHP, there is a section on security in the PHP Manual already Ted to them.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.