Basic knowledge of PHP

Source: Internet
Author: User
Tags apc apcu bind variables in sql query http request spl sql injection sqlite stmt
basic knowledge of PHPGo to the end of the metadata go to the beginning of the meta data Transmission Door

[Basic knowledge]

Type

Variable

Constant

An expression

Operator

Process Control Programming Paradigm

PHP is a flexible dynamic language that supports a variety of programming paradigms. Over the years has been evolving, important milestones include PHP 5.0 (2004) Add a perfect object-oriented model, PHP 5.3 (2009) Add anonymous functions and Namespaces and PHP 5.4 (2012) Add traits. Object Oriented Programming

PHP has full object-oriented programming features such as classes, abstract classes, interfaces, inheritance, constructors, clones, and exceptions. Learning PHP object-oriented programming function Programming

PHP supports the first class function (first-class function), where functions can be assigned to variables, including user-defined functions and built-in functions, which are then invoked dynamically. A function can be passed as a parameter to another function (that is, a higher order function), or it can be returned as a function return value.

PHP supports recursive invocation of functions, that is, the function itself calls itself, but in the actual PHP code, we prefer to use iterations instead of recursion. Learning Dynamic call function Call_user_func_array meta programming

PHP supports meta programming in a variety of ways through reflection APIs and magic method mechanisms. Developers can change the behavior of a class by magic methods such as __get (), __set (), __clone (), __tostring (), __invoke (), and so on. Ruby developers often say that PHP does not have a method_missing method, and that it actually accomplishes the same function through __call () and __callstatic (). Learn the Magic method Learn reflection namespaces

As mentioned earlier, many developers in the PHP community have developed a lot of code. This means that the PHP code in one function library might use the same class name in another library, and if they shared a namespace, a conflict would result in an exception.

namespace solves this problem. As described in the PHP manual, namespaces are similar to directories in the operating system, and two files with the same name can coexist in different directories. Similarly, PHP classes with the same name can coexist under different PHP namespaces, as simple as this.

It is therefore necessary to put the code under its own namespace, so that others can safely use the code without worrying about naming conflicts with other library functions.

PSR-0 provides a recommended way to use namespaces, trying to provide a standard usage of files, classes, and namespaces to make the code Plug and Play.

In December 2013, Php-fig released a new automatic loading standard: PSR-4, which may replace the old PSR-0 standard in the future. PSR-4 requirements PHP5.3 version above, and many projects are now used PHP5.2, so the current two standards are available, but for new applications or packages, should give priority to PSR-4. Learn more namespace exceptions

Exceptions are standard features of most popular languages, but PHP developers do not attach much importance to them. Other languages such as Ruby rely heavily on exceptions, throwing an exception when any error occurs, such as an HTTP request failure, DB query error, or even a picture resource not found, to prompt for an error.

PHP is very relaxed about this, such as calling file_get_contents () failure, but returning false and prompting a warning message. Many old PHP frameworks, such as CodeIgniter, return false, and then record a message in their own logs, and developers need to use a method such as $this->upload->get_error () to see what went wrong. Doing so requires you to check for errors, and you need to invoke different methods to get the error message based on different classes, rather than making the error manifest.

Another disadvantage of this approach is that when a class automatically prints an error on the screen and then exits the process, it prevents other developers from dynamically handling the error. The exception is to let the developer know that something is wrong and let them choose what to do with it:

<?php
$email = new Fuel\email;
$email->subject (' my subject ');
$email->body (' How is the heck are you? ');
$email->to (' guy@example.com ', ' Some guy ');
Try
{
 $email->send ();
}
catch (fuel\email\validationfailedexception $e)
{
 //the validation failed
}
catch (fuel\email\ Sendingfailedexception $e)
{
 //The driver could not send the email
}
finally
{
 // Executed regardless of whether an exception has been thrown, and before normal execution resumes
}
SPL Exception

The default exception class exception contains little contextual information and is not convenient for debug, and it is common practice to create more specific subclasses:

<?php
class Validationexception extends Exception {}

This allows you to include multiple catch clauses to handle different exceptions, but this leads to the creation of many custom exception classes that can be used in SPL to mitigate this problem SPL extension.

If you use the __call () Magic method, throw a throw new badfunctioncallexception to a nonexistent method call, avoid the exception exception that throws the ambiguous meaning, and save the trouble of the custom exception class. Learn more exceptions Learn more about SPL Exceptions exception nesting in PHP 5.3 exception Best Practices database

Typically, PHP code uses a database to persist data storage, and there are several ways to connect and manipulate databases. Prior to PHP5.1.0, the recommended approach is MySQL, mysqli, and Pgsql.

If the application is only using a database, the native driver works very well, otherwise use MySQL, but also need to use MSSQL or Oracle database, then there is no way to use only a native driver, can only learn each database-driven API, which is very annoying.

Also note that MySQL, the native driver, is no longer in active development, and is marked as deprecated from PHP5.4.0, meaning that future versions such as PHP 5.6 may remove this extension. If you are using mysql_connect () and mysql_query (), then you may want to rewrite some of the code in the future, so it's best to replace it with MYSQLI or PDO. If you are developing new projects, please do not use MySQL extensions, try to use mysqli extensions or PDO to replace PHP: Choose MySQL API PDO

PDO is a database connection abstraction library, which is provided from PHP5.1.0 to provide a unified operation interface for a variety of databases. PDO does not transform your SQL query or simulate missing features; it simply provides a unified API for connecting to different databases.

More importantly, PDO allows you to bind variables in SQL query statements without worrying about the SQL injection problem, which is done primarily through PDO statements and variable bindings.

Suppose the PHP script receives a numeric ID as the query parameter and retrieves a record from the database. The following is an erroneous approach:

$pdo = new PDO (' sqlite:users.db ');
$pdo->query ("SELECT name from users WHERE id =".) $_get[' id ']); <--no!

This is a very bad code that inserts a raw input variable directly into the SQL, resulting in a potential SQL injection risk. If the hacker constructs url:http://domain.com/?id=1%3bdelete+from+users to pass in the malicious parameter ID, then the variable value of $_get[' ID ' is 1;delete from users, This deletes all users in the datasheet. Therefore, you should use the PDO binding parameter function to handle the ID input parameters.

$pdo = new PDO (' sqlite:users.db ');
$stmt = $pdo->prepare (' SELECT name from users WHERE ID =: id ');
$stmt->bindparam (': Id ', $_get[' id '), PDO::P aram_int); <--automatically sanitized by PDO
$stmt->execute ();

This is the correct code, binding a parameter in the PDO statement to escape the input parameters before the query is sent to the database to prevent SQL injection attacks. Learning PDO

Another issue to note is that if the database connection is not closed implicitly, the number of database connections may exceed the database server limit and the connection fails, which is more common in other programming languages. The PDO object closes the database connection implicitly when it is destroyed, as long as you delete all references to it, such as null. If not, PHP will also close all Non-persistent database connections at the end of the script. Learn more PDO connection cache byte-code caching

When a php file is executed, it is compiled into bytecode (also known as OpCode), and then these bytecode are executed. If the file is not modified, then the bytecode will remain unchanged, which means that the compilation of this step wasted CPU resources.

This is the reason for introducing bytecode caching, which eliminates redundant compilation by saving bytecode in memory, and reuses them for subsequent invocations. Configuring bytecode caching is very simple and can greatly improve the execution efficiency of the application, and there is no reason not to use bytecode caching.

PHP 5.5 starts the built-in bytecode cache component Opcache, the old version of PHP can use a third party bytecode cache components, the popular bytecode caching scheme is: APC (PHP 5.4 and earlier) object caching

Most of the time, caching objects in your code can yield significant benefits, such as getting expensive data and database calls that have little change in query results. We can cache this data using the object caching system, greatly speeding up subsequent requests for similar access. If you have this data, you cache them in the system, in subsequent requests for these data, you can directly use the object in the cache, this can be a great hint of system performance, reduce server load.

Many popular bytecode caching schemes also allow you to cache custom data, so we should take full advantage of the object caching function. APCU, XCache, and Wincache provide APIs that allow you to cache data in their memory caches.

The most used memory object caching system is APCU and REDIS,APCU is a good object caching scheme, it provides a simple API to allow you to store objects in memory, and configuration and use is very easy, one of its drawbacks is only on the local use. Redis is another way, it is a separate service that can be accessed over the network, which means that you can write data in one place and then access the data in different systems.

Note this when running PHP as a (fast-) CGI application inside your webserver, every PHP process would have its own cache, I . E. APCU data is not shared between your worker processes. In this cases, you might want to consider using Redis instead, as it isn't tied to the PHP processes.

APCU are usually higher on stand-alone performance than Redis, but Redis provides more advanced data structures and more features

Note This prior to PHP 5.5, APC provides both an object cache and a bytecode cache. APCU is a project to bring APC's object cache to PHP 5.5+, since PHP now has a built-in bytecode cache (Opcache).

Learn more Object Caching systems: APCU APC functions Memcached redis XCache APIs wincache functions Framework

We use YAF as the basic framework reference YAF manual http://www.laruence.com/manual/ secure Web application Security

There are always people who are trying to sabotage your Web application, and it's important to think about ways to enhance the security of your Web applications in advance. Fortunately, the Open Web application Security Project (OWASP) has provided a detailed list of known safety issues and countermeasures. Each developer concerned with Web security should read the list carefully. Reading owasp Security Guide data filtering

Never trust external input in PHP code, be sure to filter and validate before use, Filter_var and Filter_input functions can help filter text and verify text formatting (such as email address).

External input can be: $_get and $_post form input data, some values in $_server super variables, and HTTP request bodies obtained through fopen (' Php://input ', ' R '). Keep in mind that external input is not just user-submitted form data, but also uploaded and downloaded files, session variables, cookie data, and data provided by Third-party Web services.

When the external data is stored and merged, the next time they are read, they are external inputs, and each time they are processed in the code, they need to be asked whether they have filtered correctly and can trust them.

Data needs to be filtered differently depending on its usefulness, and if you output unfiltered data to an HTML page, it can execute HTML and JavaScript on your site. Commonly known as Cross-site scripting Attacks (XSS). One strategy to avoid XSS is to use the Strip_tags function to filter all HTML tags that are entered externally, or to use Htmlentities/htmlspecialchars to escape the HTML entities in them.

Another example is the option to pass to command-line commands, which can be very dangerous (usually not a good idea), but you can use the built-in Escapeshellarg function to filter the parameters of the command line.

The final example is the operation of loading files from the file system based on external input, which can be exploited by modifying the file name in the path. You need to filter the input "/", ". /", null bytes, or other special characters to prevent the loading of files that contain sensitive data that cannot be exposed. Learn more about data filtering learn more Filter_var Learn more filter_input learn more null byte processing data Cleaning

Data cleansing is the deletion or escaping of illegal or unsafe characters in external input. For example, to export external data to HTML or INSERT into the SQL statement, you need to first clean the external input. When you bind data through PDO, it escapes input data for you.

It is sometimes necessary to allow external data to contain secure HTML tags and output to HTML pages. This is difficult to handle, you can consider the use of other more stringent formats, such as or bbcode, it is not, you can use the HTML purifier library for data cleansing.

Learn more data cleaning filter data validation

Data validation external input is what you expected, if you are processing the registration form, you need to verify the email address, phone number and age and other data

Learn more about data validation filters

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: info-contact@alibabacloud.com 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.