10 Advanced Tips for PHP (middle)

Source: Internet
Author: User
Tags array file system functions pear php and php code sort variable
Advanced | Skill Three, the document is our friend

Regardless of the size of the site you're developing, you should be aware of the importance of code reuse, whether it's HTML or PHP code. For example, you must change the footer that contains the copyright information at least once a year, and if your site contains 1000 pages, it is a chore to modify it once a year.

In PHP, there are at least a few functions that can help you achieve the purpose of code reuse, the functions you use depend on the code you reuse, and the main functions are:

* Include () and include_once ()
* Require () and require_once ()
The Include () function contains and evaluates a given file, for example:
Include ('/home/me/myfile ');

Any code in the include file is executed within the scope of the include (), and you can include a static file on your own server and a target file on the other server by using the combined use of include () and fopen ().

The include_once () feature is the same as include (), and the difference is that it checks whether the code in a file is already contained in an existing script and does not contain it if the code already exists.

The Require () function replaces itself with the contents of a given file, which occurs during the PHP engine's compilation of code rather than during execution, and it does not compute first as include (). The Require () function is used more in static elements, and include () is used more in dynamic elements. Similar to Include_once (), require_once () first checks whether the given code has been inserted, and if the code already exists, it is no longer inserted.

To also understand its content, I tend to use the Require function in copyright information, static text, and other elements that do not contain variables or that depend on other scripts that are executing. 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 () to control many functions at the beginning of a file:

?
Get the function library
Include ('/home/me/myfunctions ');
Do PHP things and my functions?>
<HTML>
<HEAD><TITLE>Something</TITLE></HEAD>
<BODY>
[A lot of content]
</BODY>
</HTML>

The next question is, "Where are the include and require files?" The simple answer to the question is, "anywhere in the system." "If your code contains a database connection with a username and password, you're not going to put it all in the document root directory and open it to everyone," he said.

Included or required files can be anywhere on the system, so long as users on the system on which PHP is running can access the files, you can make those files have any suffix, or do not use suffixes.

Using include () and require () to specify the elements in a Web site is a common phenomenon, and when you need to upgrade the site, it brings you great convenience.

Four, PHP and file system maintenance

PHP has many file system-related functions that not only open files, but also display content, move files, and other features in the directory, and many people even use PHP to develop internet-based file Explorer.

Explanation of file paths: In Windows, you can use/and symbols in paths, but only/symbols in other operating systems. For the sake of consistency, we use/sign uniformly.

The following script sample can display a list of directories that are already included in the code:

? /* Put the full path name of the directory to be read into a variable named $dir_name. */
$dir _name = "/home/me/";
/* Creates a handle whose value is the result of opening a given directory.
$dir = Opendir ($dir _name);
/* Create a block of text to place the list element (file name) * *
$file _list = "<ul>";
/* Use a while statement to read all the elements in the directory that is already open, 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 Open Directory, end PHP module * *
Closedir ($dir);
?>
<!--Start your HTML-->
<HTML>
<HEAD>
<title>directory listing</title>
</HEAD>
<BODY>
<!--use PHP to print the name of this directory you read-->
<p>files in:;? echo "$dir _name";?></p>
<!--use PHP to print the directory listing-->
? echo "$file _list";?>
</BODY>
</HTML>

Well, we've got a list of directories. It is important to note that to read a file (which we will explain later) or the contents of the directory, the user on the system on which PHP is running must have at least the right 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 and display an error message if the copy is not completed.
@copy ($original, $copied) or Die ("couldn ' t copy file.");
?>

This example is a prototype of a file backup system. When the script runs, it copies the files to a different location for saving. By modifying the daemon a little, you can execute it at the moment you specify in the day without the intervention of the user.

Assuming you have Lynx installed on the system, you can create a daemon entry to access the file, access the file to run the script and create a copy file, the following example runs this script at 5 o'clock in the morning, 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 call the binary file directly:
0 5 * * * [username] php/path/to/copyfile.php 1>/dev/null 2>&1

Five, rich array functions

In PHP 4.0, there are 30 newly added functions related to the number of groups, some of which can be used to determine whether an array contains an element, count elements in an array, add or remove elements from an array, or sort the elements in a group.

If you have a large array and you need to find out if it contains a particular element, you can use In_array (). The following example displays "not found in this array" because it finds Albert in an array named $namesarray, and there is no such element 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 "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, simply use the count () function:

? $namesArray = Array ("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John");
$count = count ($namesArray);?>

The value of the returned $count is 7.

You can add an element at the beginning or end of an array. You can also use Array_merge () to create a new array of elements in two or more arrays, and when merging, the order of the elements is arranged in the order specified, and if the original array is ordered, it needs to be reordered after the merge.

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");
/* Display each element and its serial number * *
while (the 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 an element to the beginning of the array, the code is similar to the code above, and the only difference is that you need to replace Array_push () with Array_unshift ().

?
/* Create an array */
$fruitArray = Array ("Apple", "orange", "banana", "kiwi", "pear");
/* Add elements to the array/*
Array_unshift ($fruitArray, "Grape", "pineapple", "tomato");
/* Display each element and its serial number * *
while (the 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");
/*/set up a second array * *
$vegArray = Array ("carrot", "green beans", "asparagus", "artichoke", "corn");
* * Combine these two arrays into an array
$goodfoodArray = Array_merge ($fruitArray, $vegArray);
/* Display each element and its serial number * *
while (the list ($key, $value) = each ($goodfoodArray)) {
echo "$key: $value <br>";
}
?>

Running the above script will get the following results:

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 remove elements from an array. To delete an element from the end of an array you can use the Array_pop () function to remove an element from the beginning of an array using the Array_shift () function. Although using Array_pop () or Array_shift () to remove an element from an array, you can 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);
/* Displays the contents of the array after deletion and the elements you delete * *
while (the list ($key, $value) = each ($fruitArray)) {
echo "$key: $value <br>";
}
echo "<br>and Finally, in $popped: $popped";
?>

Running the script above will result in the following:
0:apple
1:orange
2:banana
3:kiwi
And finally, in $popped: Pear

Let's discuss an example of deleting an element 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);
/* Displays the contents of the array after deletion and the elements you delete * *
while (the list ($key, $value) = each ($fruitArray)) {
echo "$key: $value <br>";
}
echo "<br>and Finally, in $shifted: $shifted";
?>

Running the above script will result in the following display:
0:orange
1:banana
2:kiwi
3:pear
And finally, in $shifted: Apple

There are also several functions that can sort the elements in an array, but here we'll just briefly outline the basic sort functions that describe the ordering process:

? /* Create an array */
$fruitArray = Array ("Apple", "orange", "banana", "kiwi", "pear");
/* Array to sort * *
Sort ($fruitArray);
/* Display each element and its serial number * *
while (the list ($key, $value) = each ($fruitArray)) {
echo "$key: $value <br>";
}
?>

Running the above script will result in the following display:

0:apple
1:banana
2:kiwi
3:orange
4:pear

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.