search
HomeBackend DevelopmentPHP TutorialTen Advanced Tips for PHP_PHP Programming

Ten Advanced Tips for PHP_PHP Programming

Jun 28, 2017 pm 03:35 PM
phpSkillprogramming


More than 3 million Internet website administrators around the world are using PHP, making it one of the most popular server-side scripting languages. It is characterized by fast running speed, stability, reliability, cross-platform, and open source software. Depending on your level of use, PHP can be very simple or very complex. You can use it only to send HTML table elements, and you can also integrate Java and XML in PHP applications.

If you have a certain understanding of PHP or have read some preliminary textbooks, these techniques can expand your understanding of PHP and enable you to master some common and advanced PHP functions.

1. Install PHP as Apache’s DSO
PHP is often used with Apache on Linux/Unix platforms. When installing PHP, there are three installation methods to choose from: static mode and dynamic mode ( DSO), CGI binary mode.

Since it is easy to maintain and upgrade, I strongly recommend installing PHP in DSO mode. For example, if the installed PHP only supports databases during the initial installation, and then you want to install modules that support encryption, just run "make clean", add new configuration options, and then run "make" and "make install", one The new PHP module will be installed in the appropriate location in Apache, and Apache will be restarted without recompiling Apache.

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

1. Get the latest version of 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 specify;

 3. Run Gunzip to decompress the file and get the suffix .tar file;

4. Run the following command to install the file into the apache_[version] directory:

tar -xvf apache_[version].tar

5. Enter the /usr/local/apache_[version] directory (or the directory where the compressed file was installed in step 4);

6. Type the following command to prepare for compiling Apache, replacing the paths 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. Type make after returning to the prompt state, And wait to return to the prompt state again;

 8. Execute the "make install" command.

At this point, Apache has been installed and the system will return to the prompt state. Next we start installing 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 in, such as /usr/local/ or /opt/ or any directory you specify;

3. Run Gunzip to decompress the file and obtain a file with the suffix .tar;

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

tar -xvf php-[version]

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

At this point, the preparations for installing PHP in DSO mode have been made. The only configuration option that needs to be modified is with-apxs (this is a file in Apache's bin directory). In order to get higher performance, I did not install the support module for MySQL.

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

6. Execute the make command after returning to the prompt state , wait to return to the prompt state;

 7. Execute the make install command.

At this point, the system has installed PHP in Apache’s module directory in DSO mode, and has made appropriate modifications to Apache’s httpd.conf file before returning to the prompt state. After returning to the prompt state, you still need to make some modifications to Apache's httpd.conf file.

1. Find the line that contains ServerAdmin and add your email address, as shown below:

ServerAdmin you@yourdomain.com

2. Find the line that starts with ServerName line, change it to a real value, for example:

ServerName localhost

3. Find the section with the following content:

And for PHP 4.x , use:

 

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

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

Modify the contents of these lines so that the AddType of PHP 4.0 is no longer a comment, and add the file suffix you want to use in PHP. The above content becomes the following:

 # 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 previous directory, and execute the following command Restart Apache:

./bin/apachectl start

If no error message appears during startup, you can create a file named phpinfo.php with only one line as shown below file to test the installed Apache and PHP:

   phpinfo() ?> In the browser, type the http://localhost/phpinfo.php address, and many variables and their values ​​will appear on the screen.

If you want to reconfigure PHP, you need to run the make clean command again, then execute the ./configure command with a series of options, and then execute the make and make install commands. A new directory module will appear in Apache. module, as long as you restart Apache to load this new module, everything will be OK.

2. Dialogue using PHP itself
The most anticipated feature of PHP 4.0 should be the support for dialogue. Users of PHP 3.0 must use third-party software, otherwise they cannot use dialogue. It is not supported. Dialogue has always been one of PHP's biggest shortcomings.

You can use conversations to maintain variables relevant to a specific user as long as the user is browsing your site without having to create multiple cookies, use hidden table fields, or store information in a database.

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

session_start();

Starting a conversation will send an identification
string
(for example, 940f8b05a40d5119c030c9c7745aead9) to the user through a cookie. On the server side, a temporary file matching the identification string will be created, such as sess_940f8b05a40d5119c030c9c7745aead9. This file contains Registered dialog variables and their values. The most common example used to display the role of a dialog is an access counter. Start the PHP module and make sure
PHP code
is the first line of the file. There should be no spaces, HTML codes or other codes before the PHP code. Because the session sends a header, if there are spaces and HTML code before session_start(), you will get an error message.  

  // If there is not yet a user for a certain user, start a conversation:

session_start();

Then Register a variable named count:

Session_register('count');

After registering a conversation variable, as long as the conversation exists, the variable named count will also exist. Now, the count variable has not been assigned a value. If you add 1 to it, its value will become 1.

 $count++; , register a variable named $count, and add 1 to $count to indicate that the user has visited the webpage for the first time.

To know the number of times the user has visited this page in the current conversation, just display the value of the $count variable:

echo "

You've been here $count times .

";

All access counter codes are as follows:



session_start();

session_register( 'count');

 $count++;

echo "

You've been here $count times.

";

 ?> ;

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

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

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

You can register an array variable just like you would a simple variable:

session_register('faves');

Reference to array variables and reference to simple variables There is no difference. If a user points out his hobbies in life on a web page, he can register his hobbies in an array variable called $faves, and then he can easily add these hobbies to another web page. Displayed:

 

session_start();

echo "My user likes:

 
    ";

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

    echo "$v"; }
    ##  echo "
";
##  ?>

Then you get a list of the user’s hobbies.

Dialog variables cannot be overwritten by query strings, which means we cannot enter http:///www.yourdomain.com/yourscript.php?count=56 to specify a new value for the registered variable $count. This An important point for security: you can only delete an unregistered dialog variable in a server-side script.

If you want to completely delete a conversation variable, you first need to unregister it from the system:

session_unregister('count');

The script to completely delete a conversation variable is Very simple, as shown below:

session_destroy();

Using session variables can reduce the frequency of accessing the database, make the code clearer, and reduce the number of cookies sent to the user. It It's the simplest way.


Current page 1/3 1

23Read the full text on the next page

The above is the detailed content of Ten Advanced Tips for PHP_PHP Programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools