SoFunction
Updated on 2025-04-14

Ten advanced tips for PHP (Part 1, Middle 2, Lower) Page 2/3

3. The documents are our friends
Regardless of the size of the website you are developing, you should realize the importance of code reuse, whether it is HTML or PHP code. For example, you must change the footer containing copyright information at least once a year, and if your website contains 1,000 pages, it is annoying to modify it once a year.

In PHP, there are at least several functions that can help you achieve the purpose of code reuse. The functions you use depend on the code you reuse. The main functions are:

* include() and include_once() 

* require() and require_once() 

include() function contains and calculates the given file, for example:

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

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

include_once() has the same function as include(), the difference between the two is that it checks whether the code in a file is already included in an existing script, and if the code already exists, it will not be included again.

The require() function replaces itself with the contents of a given file. This substitution process occurs during the PHP engine compilation of code, rather than during execution. It does not perform calculations first like include(). The require() function is used more in static elements, while include() is used more in dynamic elements. Similar to include_once(), require_once() will first check whether the given code has been inserted, and if the code already exists, it will no longer be inserted.

To understand its content, I tend to use the require function in copyright information, static text, and other elements that do not contain variables or rely on other executing scripts. For example:

<HTML> 

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

<BODY> 

[a lot of content] 

<? 

// insert copyright 

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

?> 

</BODY> 

</HTML> 

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

<? 

//Get the function library

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

// do PHP things with my functions ?> 

<HTML> 

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

<BODY> 

[a lot of content] 

</BODY> 

</HTML> 

The next question should be "where are the include and require files?" The simple answer to this question is, "Anywhere in the system." If your code contains a database connection with a username and password, you will definitely not put them all in the document root directory and open it to everyone.

The included or required files can be anywhere on the system, as long as users on the system running PHP can access these files, you can make these files have any suffix, or use no suffix.

Using include() and require() to concretize elements in the website is a common phenomenon, and it will bring you great convenience when you need to upgrade the website.

4. Maintenance of PHP and file system
There are many file system-related functions in PHP. These functions not only open files, but also display content in directories, move files and some other functions. Many people even use PHP to develop an Internet-based file explorer.

Explanation about file paths: In Windows, / and \ symbols can be used in paths, while only / symbols can be used in other operating systems. For consistency, we use / symbols uniformly.

The following script example can display a directory list, and the comments are already included in the code:

<?/*Save 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 list elements (file name)*/

$file_list = "<ul>"; 

/* Use a while statement to read all elements in the directory that has been opened. If the name of the file 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 open directory and end the PHP module*/

closedir($dir); 

?> 

<!-- Start your HTML --> 

<HTML> 

<HEAD> 

<TITLE>Directory Listing</TITLE> 

</HEAD> 

<BODY> 

<!-- 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"; ?> 

</BODY> 

</HTML> 

OK, we've got a directory listing. It should be noted that to read the contents of a file (we will explain it later) or directory, users on the system running PHP must have at least permission to read the file.

Here is an example of how to copy a file:

<? /* Assign the full path of the original file you want to copy to a variable named $original, and 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 will be displayed*/

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

?> 

This example is a prototype of a file backup system. When this script is running, it copies the file to a different location for saving. A little bit of modification to the daemon can be executed at the moment of the day without user intervention.

Suppose you have Lynx installed on the system, you can create an entry for the daemon to access the file. Accessing the file will run the script and create a copy file. The following example will run the script at 5 a.m. and then close Lynx:

0 5 * * * [username] lynx -dump http://localhost/ 1>/dev/null 2>&1 

If you are running CGI version of PHP, you can skip the Lynx part and directly call the binary file:

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

5. Rich array functions
30 new functions related to the number of groups have been added to PHP 4.0. Some common functions can determine whether an array contains an element, count elements in an array, add or delete elements in an array, or sort elements in an array.

If there is a large array and you need to find out if it contains a specific element, you can use in_array(). The following example will show "Not found in this array" because Albert is found in an array named $namesArray, and such an element does not exist in the $namesArray array.

<? $namesArray = array("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John"); 

$lookingFor = "Albert"; 

if (in_array($lookingFor, $namesArray)) { 

echo "You've found it!"; 

} else { 

echo "Not found in this array!"; 



?> 

If you change the value of $lookingFor to Mary, you will get the information "You've found it!" because Mary is an element in the $namesArray array.

If you want to count the number of elements in an array, just simply use the count() function:

<? $namesArray = array("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John"); 

$count = count($namesArray); ?> 

The returned $count value is 7.

You can add elements at the beginning or end of an array, and you can also use array_merge() to create a new array containing two or more elements in an array. When merging, the order of elements will be arranged in the specified order. If the original array is sorted, it needs to be reordered after merging.

We can first use array_push() to add an element at the end of the array:

<?/* Create an array */

$fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); 

/* Add elements to the array */

array_push($fruitArray, "grape", "pineapple", "tomato"); 

/*Show each element and its sequence number*/

while (list($key,$value) = each($fruitArray)) { 

echo "$key : $value<br>"; 



?> 

Running the above program will get the following results:

0 : apple 

1 : orange 

2 : banana 

3 : kiwi 

4 : pear 

5 : grape 

6 : pineapple 

7 : tomato 

If you need to add elements at the beginning of the array, the code is similar to the above code. The only difference is that you need to use array_unshift() instead of array_push().

<? 

/* Create an array*/

$fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); 

/* Add elements to the array*/

array_unshift($fruitArray, "grape", "pineapple", "tomato"); 

/* Show each element and its serial number*/

while (list($key,$value) = each($fruitArray)) { 

echo "$key : $value<br>"; 



?> 

Running the above program will get the following results:

0 : grape 

1 : pineapple 

2 : tomato 

3 : apple 

4 : orange 

5 : banana 

6 : kiwi 

7 : pear 

The array_merge() function can combine two or more arrays into an array.

<? /*Create the first array*/

$fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); 

/*/Create the second array*/

$vegArray = array("carrot", "green beans", "asparagus", "artichoke", "corn"); 

/*Combining these two arrays into an array*/

$goodfoodArray = array_merge($fruitArray, $vegArray); 

/* Show each element and its serial number*/

while (list($key,$value) = each($goodfoodArray)) { 

echo "$key : $value<br>"; 



?> 

Running the above script will get the following result:

0 : apple 

1 : orange 

2 : banana 

3 : kiwi 

4 : pear 

5 : carrot 

6 : green beans 

7 : asparagus 

8 : artichoke 

9 : corn 

Now that we have mastered how to add elements and merge arrays, let's take a look at how to delete elements from an array. Deleting an element from the end of an array can use the array_pop() function, and using the array_shift() function can delete an element from the beginning of an array. Although you use array_pop() or array_shift() to delete an element from the array, you can also use this element as a variable.

Use array_pop() to delete an element from the end of an array:

<? 

/*Create an array*/

$fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); 

/* Delete an element from the end of the array*/

$popped = array_pop($fruitArray); 

/* Show the content of the array after deletion and the elements you deleted*/

while (list($key,$value) = each($fruitArray)) { 

echo "$key : $value<br>"; 



echo "<br>and finally, in $popped: $popped"; 

?> 

Running the above script will get the following result:

0 : apple 

1 : orange 

2 : banana 

3 : kiwi 

and finally, in $popped: pear 

Let's discuss an example of deleting elements from the end of an array:

<? 

/* Create an array*/

$fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); 

/*Delete an element from the beginning of an array*/

$shifted = array_shift($fruitArray); 

/* Show the content of the array after deletion and the elements you deleted*/

while (list($key,$value) = each($fruitArray)) { 

echo "$key : $value<br>"; 



echo "<br>and finally, in $shifted: $shifted"; 

?> 

Running the above script will get the following display results:

0 : orange 

1 : banana 

2 : kiwi 

3 : pear 

and finally, in $shifted: apple 

There are also several functions that can sort elements in an array, but here we will only briefly introduce the basic sorting function to explain the sorting process:

<?/*Create an array*/

$fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); 

/* Sort the array*/

sort($fruitArray); 

/*Show each element and its sequence number*/

while (list($key,$value) = each($fruitArray)) { 

echo "$key : $value<br>"; 



?> 

Running the above script will get the following display result:

0 : apple 

1 : banana 

2 : kiwi 

3 : orange 

4 : pear 

Previous page123Next pageRead the full text