5. Miscellaneous
5.1 generate images
PHP can process images. If you have installed the GD library, you can even use PHP to generate images.
<?
Header ("Content-type: image/gif ");
$ String = implode ($ argv ,"");
$ Im = imagecreatefromgif ("images/button1.gif ");
$ Orange = ImageColorAllocate ($ im, 220,210, 60 );
$ Px = (imagesx ($ im)-7.5 * strlen ($ string)/2;
ImageString ($ im, 3, $ px, 9, $ string, $ orange );
ImageGif ($ im );
ImageDestroy ($ im );
?>
(Note: The above code segment lacks comments. For more information, see the image processing function section of PHP Manual)
In other pages, Mark call, and the preceding button. the php3 code obtains the text value and adds the value to the other obtained image file. In the above Code, the image file is images/button1.gif and is finally output to the browser. If you want to use the image button in the form field, but do not want to have to generate a new image after each text change on the button, you can use this simple method to dynamically generate an image file.
5.2 Cookies
PHP supports HTTP-based cookies. When needed, you can use cookies as easily as using common variables. Cookies are some pieces of information stored in the client by the browser. Therefore, you can know whether anyone on a specific PC has visited your site, and the path of the viewer on your site. A typical example of using cookies is the screening of viewer preferences. Cookies are set by the setcookie () function. Like the header () function that outputs the HTTP header, setcookie () must be called before any actual content cup is output to the browser. The following is a simple example:
<?
If (empty ($ VisitedBefore ))
{
// If no cookie is set, the current time value is assigned to the cookie.
// The last parameter in the function declares the cookie retention time
// In this example, it is 1 year.
// The time () function returns the time in seconds since January 1, January 1, 1970.
SetCookie ("VisitedBefore", time (), time () + (60*60*24*365 ));
}
Else
{
// Welcome again
Echo "Hello there, welcome back <BR> ";
// Read and judge the cookie
If (time ()-$ VisitedBefore)> = "(60*60*24*7 )")
Echo "Why did you take a week to come back. You shoshould be here more often !?
";
}
?>
5.3 HTTP-based verification
HTTP-based verification cannot be implemented when PHP runs in CGI Mode. You can use the function header () to send HTTP header mandatory verification. The client browser displays a dialog box for you to enter the user name and password. These two variables are stored in $ PHP_AUTH_USER and $ PHP_AUTH_PW. You can use these two variables to Verify validity and allow access. The following example shows how to verify the login of a user using the user name/password pair tnc/nature:
<?
If (! Isset ($ PHP_AUTH_USER ))
{
Header ("WWW-Authenticate: Basic realm = \" My Realm \"");
Header ("HTTP/1.0 401 Unauthorized ");
Echo "Text to send if user hits Cancel button \ n ";
Exit;
}
Else
{
If (! ($ PHP_AUTH_USER = "tnc" & $ PHP_AUTH_PW = "nature ")
)
{
// If the user name or password pair is incorrect, force re-verification
Header ("WWW-Authenticate: Basic realm = \" My Realm \"");
Header ("HTTP/1.0 401 Unauthorized ");
Echo "ERROR: $ PHP_AUTH_USER/$ PHP_AUTH_PW is invalid .";
Exit;
}
Else
{
Echo "Welcome tnc! ";
}
?>
In fact, in actual reference, it is unlikely that the above user name/password pairs are used, but the database or encrypted password files are used to access them.
5.4 File Upload
You can use PHP to implement the file function. Note that the client browser should be Netscape3 or later or IE3. The following is a simple demonstration of this function:
(Upload.html ):
<HTML>
<HEAD>
<TITLE> Upload Your File </TITLE>
</HEAD>
<BODY>
<Form action = "er. php3"
ENCTYPE = "multipart/form-data" METHOD = POST>
<Input type = "HIDDEN"
NAME = "maid" VALUE = "2000000">
<Input type = "FILE"
NAME = "uploadfile" SIZE = "24" MAXLENGTH = "80">
<BR>
<Input type = "SUBMIT" VALUE = "Upload File! "
NAME = "sendit">
<Input type = "SUBMIT" VALUE = "Cancel"
NAME = "cancelit"> <BR>
</FORM>
<I> <FONT SIZE = "2"> (You may notice a slight
Delay while we upload your file.) </FONT> </I>
</BODY>
</HTML>
The following describes how to process uploaded files:
(Explorer. php3 ):
<?
Function do_upload ()
{
Global $ uploadfile, $ uploadfile_size;
Global $ local_file, $ error_msg;
If ($ uploadfile = "none ")
{
$ Error_msg = "You did not specify a file for uploading .";
Return;
}
If ($ uploadfile_size> 2000000)
{
$ Error_msg = "Sorry, your file is too large .";
Return;
}
$ The_time = time ();
// You need to have write permission on the following directories
$ Upload_dir = "/local/uploads ";
$ Local_file = "$ upload_dir/$ the_time ";
If (file_exists ('$ local_file '))
{
$ Seq = 1;
While (file_exists ("$ upload_dir/$ the_time $ seq") {$ seq ++ ;}
$ Local_file = "$ upload_dir/$ the_time $ seq ";
};
Rename ($ uploadfile, $ local_file );
Display_page ();
}
Function display_page ()
{
// Here is your page content
}
<HTML>
<HEAD>
<TITLE> php3 indexing ing Script </TITLE>
</HEAD>
<BODY>
<?
If ($ error_msg) {echo "<B> $ error_msg </B> <BR> ";
}
If ($ sendit)
{
Do_upload ();
}
Elseif ($ cancelit)
{
Header ("Location: $ some_other_script ");
Exit;
}
Else
{
Some_other_func ();
}
?>
</BODY>
</HTML>
5.5 common functions
Let's take a look at some common functions.
Array
Array-generate an array
Count-Number of array elements
Sort-array sorting. Other sorting functions are available.
List-list array elements
Each-returns the next key/value pair
Current-returns the current array element
Next, prev-returns the pointer before and after the current array element
Date and Time
Checkdate-verification date/time format
Date-generated date/time format
Time-current time information
Strftime-format date/time
Directory and File System
Chdir-Change directory
Dir-directory category
Opendir, readdir, closedir-enable, read, and disable Directories
Fopen, fclose-enable and disable files
Fgets, fgetss-read content row by row
File-read the entire file into an array variable
Regular Expression
Ereg-Regular Expression matching
Eregi-Regular Expression for case-insensitive matching
Ereg_replace-match and replace the Regular Expression
Eregi_replace-match and replace a regular expression in case-insensitive Mode
Split-cut strings according to rules and store them as Arrays
String
AddSlashes-use a string after adding a slash
Echo-output one or more strings
Join and implode-merge array elements into strings
Htmlentities and htmlspecialchars-convert special HTML characters into HTML Markup
Split-cut strings according to rules and store them as Arrays
5.6 expand our example Homepage
We will use the functions and ideas mentioned above to add more dynamic content to our example homepage. We can add a navigation bar at the top of each page, so that the current page is automatically not linked; you can also add a user verification form to upload music, images, and other files and automatically update the page.
Navigation Bar
It is actually adding a piece of code in the footer. inc file. Assume that all files with the suffix. php3 in your web site will appear in the navigation bar. The following code is saved as include/navbar. inc:
<?
/* Output this navigation bar to link all the. php3 files in the site except the current page */
# Reading Directories
$ D = dir ("./");
Echo "<p align = \" CENTER \ "> | \ n ";
While ($ entry = $ d-> read ())
{
// Ignore the case of no file
If (! Is_file ($ entry ))
Continue;
/* Separate the file name from the extension. Because it is a special character of the regular expression, \ should be used to lead */
List ($ filenm, $ fileext) = split ("\.", $ entry, 2 );
// Ignore non-. php3 files
If ($ fileext! = "Php3 ")
Continue;
/* Now we have selected all. php3 files. Search for the first line (title) in the file below)
Similar to $ title = "something ";
Separate the above headers and use them as link text */
$ Linknm = "";
$ Fp = fopen ($ entry, "r ");
While ($ buffer = fgets ($ fp, 4096 ))
{
$ Buffer = trim ($ buffer );
// We have placed the title of each file in the first line of the file for search.
// However, it may cause a lot of trouble when you change the variable name.
If (ereg ("title * = * \" ", $ buffer ))
{
/* We have obtained the title content and can base on it
To remove spaces.
Must be processed in PHP code, such as $ title = "blah "*/
Eval ($ buffer );
// Display the link text as the title text
$ Linknm = $ title;
Break;
}
}
Fclose ($ fp );
If ($ entry = basename ($ PHP_SELF ))
Echo "$ linknm ";
Else
Echo "<a href = \" $ entry \ "> $ linknm </A> ";
Echo "| ";
}
$ D-> close ();
Echo "</P> \ n ";
?>
Photo favorites
We will reference HTTP-based verification, file system functions, and file upload functions to maintain the directory for storing image files.
At the same time, we need to create a page to list all the photos in this directory.
File Upload
<?
Include ("include/common. inc ");
// Here we will perform another user verification.
If (! Isset ($ PHP_AUTH_USER ))
{
Header ("WWW-Authenticate: Basic realm = \" $ MySiteName \"");
Header ("HTTP/1.0 401 Unauthorized ");
Echo "Sorry, you are not authorized to upload files \ n ";
Exit;
}
Else
{
If (! ($ PHP_AUTH_USER = $ MyName & $ PHP_AUTH_PW = $ MyPassword ))
{
// If the user name or password pair is incorrect, force re-Authentication
Header ("WWW-Authenticate: Basic realm = \" My Realm \"");
Header ("HTTP/1.0 401 Unauthorized ");
Echo "ERROR: $ PHP_AUTH_USER/$ PHP_AUTH_PW is invalid. <P> ";
Exit;
}
}
If ($ cancelit)
{
// When the viewer presses the "cancel" button, the page is redirected to the homepage.
Header ("Location: front_2.php3 ");
Exit;
}
Function do_upload (){
Global $ userfile, $ userfile_size, $ userfile_name, $ userfile_type;
Global $ local_file, $ error_msg;
Global $ HTTP_REFERER;
If ($ userfile = "none "){
$ Error_msg = "You did not specify a file for uploading .";
Return;
}
If ($ userfile_size> 2000000)
{
$ Error_msg = "Sorry, your file is too large .";
Return;
}
// Wherever you have write permission below...
$ Upload_dir = "photos ";
$ Local_file = "$ upload_dir/$ userfile_name ";
If (file_exists ($ local_file )){
$ Error_msg = "Sorry, a file with that name already exists ";
Return;
};
// You can also check the file name/type pair to determine the file type: gif, jpg, mp3...
Rename ($ userfile, $ local_file );
Echo "The file is uploaded <BR> \ n ";
Echo "<a href = \" $ HTTP_REFERER \ "> Go Back </A> <BR> \ n ";
}
$ Title = "Upload File ";
Include ("include/header. inc ");
If (empty ($ userfile)
$ Userfile = "none ")
{
// Output the following form
?>
<Form action = "<? Echo "$ PHP_SELF";?> "ENCTYPE =" multipart/form-data"
METHOD = POST>
<Input type = "HIDDEN" NAME = "MAX_FILE_SIZE" VALUE = "2000000">
<Input type = "FILE" NAME = "userfile" SIZE = "24"
MAXLENGTH = "80">
<BR>
<Input type = "SUBMIT" VALUE = "Upload File! "NAME =" sendit ">
<Input type = "SUBMIT" VALUE = "Cancel" NAME = "cancelit"> <BR>
</FORM>
<I> <FONT SIZE = "2"> (You may notice a slight delay while
We upload your file.) </FONT> </I>
<?
} Else {
If ($ error_msg) {echo "<B> $ error_msg </B> <BR> ";
}
If ($ sendit ){
Do_upload ();
}
}
Include ("include/footer. inc ");
?>
Image Library
<?
Include ("include/common. inc ");
$ Title = "Gallery ";
Include ("include/header. inc ");
?>
<P>
Here are some of our family photos. This PHP script can be really
Be made better, by splitting into multiple pages.
</P>
<?
$ D = dir ("photos ");
While ($ entry = $ d-> read ())
{
If (is_file ("photos/$ entry "))
Echo " \ n ";
}
$ D-> close ();
?>
<?
Include ("include/footer. inc ");
?>
In addition, you can add an input element to the file upload form to describe the uploaded file. This element will be stored in the file, and then read and displayed by the code in the image library above.