Ten advanced PHP skills

Source: Internet
Author: User
Tags uncompress password protection

Administrators of more than 3 million Internet websites around the world are using PHP, making it one of the most popular server-side scripting languages. It features fast running, stable and reliable, cross-platform, and open source software. Different from the level you use, PHP can be very simple or complex. You can only use it to send HTML table elements, and integrate Java and XML in PHP applications.

If you have a certain understanding of PHP or read some preliminary teaching materials, these skills can expand your understanding of PHP, so that you can master some common and advanced PHP functions.

1. install PHP as a DSO of Apache
PHP is often used with Apache on Linux/Unix platforms. When installing PHP, there are three installation methods available: static mode, dynamic mode (DSO), and CGI binary mode.

Because it is easy to maintain and upgrade, I strongly recommend using DSO to install PHP. For example, if the PHP installed for the first time only supports the database and then you want to install a module that supports encryption, you only need to run "make clean" and add new configuration options, then run "make" and "make install". A new PHP module will be installed in an appropriate location in Apache and then restart Apache without re-compiling Apache.

The following steps will install a brand new Apache and install PHP in DSO mode:

1. obtain the latest Apache source code from the Apache Software Foundation;

2. Put the obtained source code in the/usr/local/or/opt/directory, or any directory you specified;

3rd. Run gunzip' To uncompress the file and get the file suffixed with .tar;

4. Run the following command to install the file in the Apache _ [version] directory:

Tar-xvf apache_{version}.tar

5. Go to the/usr/local/Apache _ [version] Directory (or install the compressed file directory in step 4 );

6. Enter the following command to prepare for compiling Apache. Replace [path] With your own path, for example,/usr/local/apache [version]. now the new value of mod_so has been set, which will allow Apache to use the DSO module;

7. Return to the prompt state, type make, and wait for the prompt to return again;

8. Run the "make install" command.

Now that Apache has been installed, the system will return to the prompt state. Next we will start to install PHP:

1. Find the link to the latest version in the Download Area of the PHP homepage;

2. download the file to an appropriate directory, such as/usr/local/or/opt/or any directory you specified;

3rd. Run gunzip' To uncompress the file and get the file suffixed with .tar;

4. Run the following command to install the file in the php-[version] directory:

Tar-xvf php-[version]

5. Enter the/usr/local/php-[version] directory or the directory specified in step 4;

Now, you have prepared for installing PHP using DSO. The only configuration option to be modified is with-apxs (a file in the Apache bin directory ). To achieve high performance, I have not installed a support module for MySQL.

./Configure -- with-mysql =/[path to mysql] -- with-apxs =/[path to apxs]

6. Return to the prompt status and run the make command. Wait until the prompt status is returned again;

7. Run the make install command.

At this point, the system installed PHP In the Module Directory of Apache in DSO mode, and modified the httpd. conf file of Apache, and then returned to the prompt state. After you return to the prompt state, you also need to modify the httpd. conf file of Apache.

1. Find a row containing ServerAdmin and add your email address, as shown below:

ServerAdmin you@yourdomain.com

2. Find the row starting with ServerName and change it to a real value, for example:

ServerName localhost

3. Find the following section:

# And for PHP 4.x, use:

# AddType application/x-httpd-php. php

# AddType application/x-httpd-php-source. phps

Modify the content of these rows so that the AddType of PHP 4.0 is no longer annotated, and add the extension name of the file to be used in PHP. The content above is changed to the following content:

# And for PHP 4.x, use:


AddType application/x-httpd-php. php. phtml

AddType application/x-httpd-php-source. phps

Save the file, return to the upper-level directory, and run the following command to restart Apache:

./Bin/apachectl start

If no error message is displayed at startup, you can create a file named phpinfo. php with only one line of content shown below to test installed Apache and PHP:

<? Phpinfo ()?>

Save the file to the Apache document root directory (htdocs), open the browser, and type http: // localhost/phpinfo. php address, many variables and their values appear on the screen.

To reconfigure PHP, run the make clean command again, and then execute the command with a series of options. /configure command, and then execute the make and make install commands. A new module will appear in the directory module of Apache. You only need to restart Apache to load the new module, everything is OK.

2. Use PHP conversation
The most promising feature of PHP 4.0 should be the support for dialogs. Users of PHP 3.0 must use third-party software. Otherwise, they cannot use dialogs. Not supporting dialogs has always been one of the biggest shortcomings of PHP.

As long as you are browsing your website, you can maintain variables related to specific users using dialogs without creating multiple cookies, hiding table fields, or storing information in the database.

Starting a conversation on a web page will make the PHP engine know that you want to start a conversation (if it has not been started) or continue the current conversation:

Session_start ();

When a dialog is started, a cookie is used to send an identification string (for example, 940f8b05a40dda-9c030c9c7745aead9) to the user. on the server side, a temporary file that matches the recognition string is created, for example, Token, this file contains the registered peer variables and their values.

The most common example for displaying the role of a dialog is the access counter. Start the PHP module and ensure that the PHP code is the first line of the file. do not include spaces, HTML code, or other code before the PHP code. Because the dialog will send a header, if there is space and HTML code before session_start (), an error message will be obtained.


// If no user exists for a user, start a dialog:

Session_start ();

Then register a variable named count:

Session_register ('Count ');

After registering a dialog variable, the variable named count exists as long as the dialog exists. Now, the count variable has not been assigned a value. If you add 1 to it, its value is changed to 1.

$ Count ++;

Combine the preceding content. If no dialog is started, a dialog is started. If no dialog id exists, a dialog is specified for the user, register a variable named $ count. Adding 1 to $ count indicates that the user has accessed the webpage for the first time.

To know the number of times a user accesses this page in the current dialog, just display the value of the $ count variable:

Echo "<P> You 've been here $ count times. </p> ";

The code for all access Counters is as follows:


Session_start ();

Session_register ('Count ');

$ Count ++;

Echo "<P> You 've been here $ count times. </p> ";


If you reload the above script file, you will find that the variable count value has increased by 1, so cool.

You can also register an array variable in the dialog. Suppose we have registered a variable named $ faves:

$ Faves = array ('chocolate', 'coffee ', 'beer', 'linux ');

You can register an array variable like registering a simple variable:

Session_register ('fafes ');

There is no difference between referencing an array variable and referencing a simple variable. If a user points out that he or she is happy on the webpage, you can register his hobbies into an array variable called $ faves, and then easily display these hobbies on another webpage:


Session_start ();

Echo "My user likes:

<Ul> ";

While (list (, $ v) = each ($ faves )){

Echo "<li> $ v ";}

Echo "</ul> ";


Then you get a list of user hobbies.

The dialog variable cannot be overwritten by the query string, that is, we cannot enter http: // www.yourdomain.com/yourscript. php? Count = 56 specify a new value for the registration variable $ count, which is important to security: Only one unregistered dialog variable can be deleted from the script on the server.

To completely delete a dialog variable, you must first cancel it from the system:

Session_unregister ('Count ');

The script to completely delete a dialog variable is very simple, as shown below:

Session_destroy ();

Using dialog variables can reduce the frequency of accessing the database, make the code clearer, and reduce the number of cookies sent to users. This is the simplest method.
3. Files are our friends
Regardless of the size of the website you are developing, you should be aware of the importance of code reuse, whether the code is HTML or PHP code. For example, you must change the footer containing the copyright information at least once a year. If your website contains 1000 pages, modifying the footer once a year is also annoying.

In PHP, there are at least a few functions that can help you reuse code. The functions used depend on the code you reuse. The main functions are:

* Include () and include_once ()

* Require () and require_once ()

The include () function contains and computes the given file. For example:

Include ('/home/me/myfile ');

Any code in the include file is executed within the scope of the Code that appears in include (). You can use include () and fopen () together to include static files on your own server, include the target file on another server.

Include_once () has the same function as include (). The difference between them is that it checks whether the code in a file is included in an existing script. If the Code already exists, it will not be included again.

The require () function replaces itself with the content of a given file, which occurs during PHP engine code compilation rather than during execution, unlike include () the calculation is performed first. The require () function is more used in static elements, while the include () function is more used in dynamic elements. Similar to include_once (), require_once () first checks whether the given code has been inserted. If the Code already exists, it is no longer inserted.

To learn more about the content, I prefer to use the require function in copyright information, static text, and other elements that do not contain variables, or those that depend on other scripts being executed. For example:


Reference content is as follows:


<HEAD> <TITLE> Something </TITLE> </HEAD>


[A lot of content]


// Insert copyright

Require ('/home/me/mycopyright ');




On the other hand, I often use include () to control many functions at the beginning of a file:


Reference content is as follows:


// Obtain the function library

Include ('/home/me/myfunctions ');

// Do PHP things with my functions?>


<HEAD> <TITLE> Something </TITLE> </HEAD>


[A lot of content]



The next question should be "Where are the include and require files ?", A simple answer to this question is, "anywhere in the system ." If your code contains a database connection with a user name and password, you will not put them in the root directory of the document to be open to everyone.

Stored ded or required files can be stored anywhere on the system, as long as users on the system where PHP runs can access these files, you can make these files have any suffix, or do not use a suffix.

Using include () and require () to externalize the elements on the website is a common phenomenon, and it brings great convenience to you when you need to upgrade the website.

Iv. PHP and file system maintenance

PHP has many functions related to the file system. These functions can not only open files, but also display contents in directories, move files, and other functions, many people even use PHP to develop Internet-based file resource managers.

File Path explanation: in Windows, you can use the/and \ symbols in the path, while in other operating systems, you can only use the/symbol. For the sake of consistency, we use the/symbol in a unified manner.

The following script example shows a directory list with annotations included in the Code:


Reference content is as follows:

<? /* Store the full path name of the directory to be read into a variable named $ dir_name. */

$ Dir_name = "/home/me /";

/* Create a handle whose value is the result of opening a given directory */

$ Dir = opendir ($ dir_name );

/* Create a text block to place the list element (File Name )*/

$ File_list = "<ul> ";

/* Use a while statement to read all the elements in the opened directory. If the file name is not ".." or "..", the name in the list is displayed */

While ($ file_name = readdir ($ dir )){

If ($ file_name! = ".") & ($ File_name! = "..")){

$ File_list. = "<li> $ file_name ";



$ File_list. = "</ul> ";

/* Close the opened directory and end the PHP module */

Closedir ($ dir );


<! -- Start your HTML -->



<TITLE> Directory Listing </TITLE>



<! -- Use PHP to print the name of the directory you read -->

<P> Files in: <? Echo "$ dir_name";?> </P>

<! -- Use PHP to print the directory listing -->

<? Echo "$ file_list";?>



Now we have a directory list. Note that to read a file (which will be explained later) or directory, users on the PHP running system must have at least the permission to read the file.

The following is an example of how to copy an object:


Reference content is as follows:

<? /* Assign the full path of the original file to a variable named $ original, assign the full path of the copied file to a variable named $ copied */

$ Original = "/home/me/mydatabasedump ";

$ Copied = "/archive/mydatabasedumo_1010 ";

/* Use the copy () function to copy the original file. If the copy is not completed, an error message is displayed */

@ Copy ($ original, $ copied) or die ("Couldn't copy file .");


This example is a prototype of a file backup system. When this script runs, it copies the file to a different location for saving. You can modify the daemon to execute it at the specified time of the day without user intervention.

If you have installed Lynx on the system, you can create a daemon entry to access this file. Accessing this file will run this script and create a copy file, the following example runs the script at five o'clock A.M. and then closes Lynx:

0 5 *** [username] Lynx-dump http: // localhost/copyfile. php 1>/dev/null 2> & 1

If you are running a CGI version of PHP, you can skip the lynx section and directly call the binary file:

0 5 *** [username] PHP/path/to/copyfile. php 1>/dev/null 2> & 1

6. Create dynamic images

As long as you install some third-party library files and have some geometric knowledge, you can use PHP to create and process images. In fact, this does not require much geometric knowledge, because I have not graduated from college and can still use PHP to create images.

Install the GD library file before using basic image creation functions. If you want to create a function using JPEG-related images, you also need to install the jpeg-6b, and if you want to use the Type 1 Font in the image, you must install t1lib.

Before creating an image creation environment, make some preparations. First, install t1lib; then install the jpeg-6b, and then install the GD library file. Be sure to install it in the order given here, because the jpeg-6b is used when compiling GD as the Library, and errors occur during compilation if the jpeg-6b is not installed.

After installing these three components, you also need to reconfigure PHP, which is also one of the places you are glad to install PHP using DSO. Run make clean and add the following content to the current configuration:


Reference content is as follows:

-- With-gd = [/path/to/gd]

-- With-jpeg-dir = [/path/to/jpeg-6b]

-- With-t1lib = [/path/to/t1lib]

After adding the package, run the make command, and then run the make install command. Restart Apache and run phpinfo () to check whether the new settings have taken effect. Now you can start image creation.

Depending on the version of the installed GD library file, you may or may not be able to create GIF or PNG format graphics files if installed with a gd-1.6 or a previous version, you can use a file in GIF format, but you cannot create a PNG file. If you are installing a version later than the gd-1.6, you can create a PNG file but not a file in GIF format.

Many functions are required to create a simple image.

In this example, we will create an image file in PNG format. The following code is a header containing the MIME type of the created image:

<? Header ("Content-type: image/png ");

Use ImageCreate () to create a variable that represents a blank image. This function requires a parameter of the image size in pixels. The format is ImageCreate (x_size, y_size ). To create an image of X in size, use the following statement:

$ NewImg = ImageCreate (250,250 );

Because the image is still blank, you may want to fill it with some color. However, you must first use the ImageColorAllocate () function to specify a name for this color with its RGB value. The format of this function is ImageColorAllocate ([image], [red], [green], [blue]). To define the sky blue, use the following statement:

$ Skyblue = ImageColorAllocate ($ newImg, 136,193,255 );

Next, you need to use the ImageFill () function to fill the image with this color. The ImageFill () function has several versions, such as ImageFillRectangle () and ImageFillPolygon. For simplicity, we use the ImageFill () function in the following format:


Reference content is as follows:

ImageFill ([image], [start x point], [start y point], [color])

ImageFill ($ newImg, 0, 0, $ skyblue );

Finally, after creating the image, release the image handle and occupied memory:


Reference content is as follows:

ImagePNG ($ newImg );

ImageDestroy ($ newImg);?>

The code for creating an image is as follows:

<? Header ("Content-type: image/png ");

$ NewImg = ImageCreate (250,250 );

$ Skyblue = ImageColorAllocate ($ newImg, 136,193,255 );

ImageFill ($ newImg, 0, 0, $ skyblue );

ImagePNG ($ newImg );

ImageDestroy ($ newImg );


If you save the script file as skyblue. php and access it with a browser, you will see an image in PNG format of the sky blue 250X250.

We can also use the image creation function to process the image. For example, we can make a large image into a small image:

Suppose you have an image and want to crop A 35x35 image. What you need to do is to create a 35x35 blank image, create an image stream containing the original image, and then put the original image after the adjusted size into the new blank image.

The key function to complete this task is ImageCopyResized (), which requires the following format:


Reference content is as follows:

ImageCopyResized ([new image handle], [original image handle], [new image X], [new Image Y], [original image X], [original image Y], [new image X], [new image Y], [original image X], [original image Y]).

<? /* Send a header to let the browser know the content type contained in the file */

Header ("Content-type: image/png ");

/* Create a variable to save the height and width of the new image */

$ NewWidth = 35;

$ NewHeight = 35;

/* Create a new blank image with a given height and width */

$ NewImg = ImageCreate ($ newWidth, $ newHeight );

/* Obtain data from the original large image */

$ OrigImg = ImageCreateFromPNG ("test.png ");

/* Copy the adjusted image and use ImageSX () and ImageSY () to obtain the size of the original image in terms of X and Y */

Imagecopyresized ($ newimg, $ origimg, 0, 0, 0, $ newwidth, $ newheight, imagesx ($ origimg), imagesy ($ origimg ));

/* Create the desired image and release the memory */

Imagepng ($ newimg );

Imagedestroy ($ newimg);?>

If you save this short script as resized. php and access it using a browser, you will see a 35x35 PNG image.

7. PHP-based user authentication
If you want to implement password protection on each script, you can use the header () Statement, $ PHP_AUTH_USER, and $ PHP_AUTH_PW to establish a basic authentication scheme, generally, the server-based question/response sequence is as follows:

1. the user requests a file from the server. If the file is protected on the server, a 401 (indicating authorized users) string is returned to the user in the response header.
2. After the browser receives the response, a dialog box asking the user to enter the user name/password is displayed.

3. Enter a user name and password in the dialog box and click OK to return the information to the server for authentication.

4. If the user name and password are valid, the protected file will be open to the user. Authentication will always be valid as long as the user is still using the file.

A simple PHP script file sends an appropriate HTTP header that can automatically display the user name/Password dialog box to imitate the HTTP question/response system, PHP stores the user input information in the username/password dialog box in $ PHP_AUTH_USER and $ PHP_AUTH_PW. These two variables are used, it can be compared with the user name/password stored in a text file, data base, and other files.

In this example, two hard-coded values are used for authentication. However, no matter where the user name and password are stored, the principles are the same.


Reference content is as follows:


/* Check the values in $ php_auth_user and $ php_auth_pw */

If ((! Isset ($ php_auth_user) | (! Isset ($ php_auth_pw ))){

/* If there is no value, send a header that can trigger the dialog box */

Header ('www-Authenticate: Basic realm = "my private stuff "');

Header ('HTTP/1.0 401 unauthorized ');

Echo 'authorization required .';


} Else if (isset ($ php_auth_user) & (isset ($ php_auth_pw ))){

/* Check whether the variables have values */

If ($ php_auth_user! = "Validname") | ($ php_auth_pw! = "Goodpassword ")){

/* If the entered username and password are incorrect, send a header that can be displayed in the dialog box */

Header ('www-Authenticate: Basic realm = "My Private Stuff "');

Header ('HTTP/1.0 401 unauthorized ');

Echo 'authorization Required .';


} Else if ($ PHP_AUTH_USER = "validname") | ($ PHP_AUTH_PW = "goodpassword ")){

/* If both values are correct, the information displayed successfully */

Echo "<P> You're authorized! </P> ";




Note that if you are using a file-based protection mechanism, it does not guarantee the security of all files in the directory. It may protect most files. If you think it can protect all files in a given directory, you need to change your understanding.

8. PHP and COM

If you are adventurous and run CGI, ISAPI, or Apache module version PHP on Windows, you can access COM functions. Well, I will give a detailed explanation of COM work to Microsoft and many big part books. In order to get a simple understanding of COM functions, the following is a short common script.

This PHP script starts Microsoft Word processing on the backend, opens a new document, enters some text, saves the document, and closes the Word.


Reference content is as follows:


// Create an index pointing to the new COM Component

$ Word = new COM ("word. application") or die ("Can't start Word! ");

// Display the version number of the Word currently in use

Echo "Loading Word, v. {$ word-> Version} <br> ";

// Set its visibility to 0 (false). If you want to enable it at the frontend, use 1 (true)

// To open the application in the forefront, use 1 (true)

$ Word-> Visible = 0;

// Create a document in Word

$ Word-> Documents-> Add ();

// Add text to the new document

$ Word-> Selection-> TypeText ("Testing 1-2-3 ...");

// Save the document in the temporary Windows directory

$ Word-> Documents [1]-> SaveAs ("/Windows/temp/comtest.doc ");

// Close the connection with COM components

$ Word-> Quit ();

// Display other information on the screen

Echo "Check for the file ...";


If you have an intranet website where data is stored in SQL Server and you need the Excel format of the data, you can run the necessary SQL query in PHP and format the output, then, use COM to open Excel, convert the data into Excel format, and save the data on your desktop.

9. PHP and Java

Another interesting function of PHP is that it can call methods in existing Java objects so that you can integrate PHP in Java-based applications. If you want to promote PHP applications at work, this function is very useful. The result you get is, "everything here is based on Java ."

To use this function, you must have a JVM (Java VM) installed on your server ). If the JDK is installed by Sun, Kaffe, IBM, or Blackdown, the JVM is installed.

When configuring PHP, add the with-java section to the configuration file, and then modify a part of the php. ini file. The following content must be added to modify the php. ini file:


Reference content is as follows:


Java. library. path =/path/to/library

Java. class. path =/classpath/

Extension_dir =/path/to/extensions

Extension = libphp_java.so

Note that the modification is related to your installation type. You need to read the README file in the ext/java directory of the PHP installation directory and learn how to configure the Java function.

The following is an example of how to create a PHP script for a new Java object. This script will access and display some Java attributes on the display. It is as interesting as the example of COM and should give us some inspiration.


Reference content is as follows:


$ System = new Java ("Java. Lang. system ");

Echo "<p> JAVA version =". $ system-> getproperty ("Java. Version"). "<br> ";

Echo "Java vendor =". $ system-> getproperty ("Java. Vendor"). "</P> ";


If you have Java knowledge, it will be of great help to the development work. This integration capability is critical to the acceptance and growth of PHP in the future.

10. PHP and XML

PHP contains an optional XML extension that supports Expat parsing. Using XML-related functions in PHP, you can create an analytic program to process valid XML documents. If you are using Apache version 1.3.7 or later, you do not need to install additional library files. All you need to do is configure with-xml in PHP.

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.