Section 13th Miscellaneous

Source: Internet
Author: User
Tags ereg
Other miscellaneous 13.1 generate images PHP can operate and process images. If you have installed the GD library, you can even use PHP to generate images .? Header (Content-type: image/gif); $ stringimplode ($ argv,); $ imimagecreatefromgif (images/button1.gif); $ orangeImage

Miscellaneous

13.1Generating images

  PHPImages can be processed. If you have installedGDLibrary, you can even usePHPGenerate an image.
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, seePHP ManualImage processing function section)

This code is marked as follows on other pages<Img Src= "Button. php3? Text ">Call, and the above sectionButton. php3Code acquisitionTextValue and add the value to the acquired image file.--In the above code, the image file isImages/button1.gif --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.

13.2 Cookies

  PHPSupportsHTTPOfCookies. When needed, you can use it as conveniently as using common variables.Cookie.CookiesIs some information fragments stored in the client by the browser, so you can know whether a specificPCAnyone on your website has visited your site.ByTraces on your site and so on. UseCookiesA typical example is the screening of viewer preferences.CookiesBy functionSetcookie()Set. And outputHTTPHeader functionHeader ()Same,Setcookie()Must be in any actualContent CupCalled before output to the browser. The following is a simple example:

If (empty ($VisitedBefore))
{
//If noCookie, IsCookieAttach currentTime value
//The last parameter in the function declaresCookieTime saved
//In this example1Year
// Time ()Function returned from 1970Year 1Month 1Day Time in seconds
SetCookie("VisitedBefore ", time(), Time () + (60*60*24*365 ));
}
Else
{
//Welcome to visit again
Echo "Hello there, welcome back
";
//ReadCookieAnd judge
If (time ()-$VisitedBefore)> = "(60*60*24*7 )")
Echo "Why did you take a week to come back. You shoshould be here more often !? ";
}
?>

13.3Common 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 nextKey/valuePair
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-Generation 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-Match regular expression
Eregi-Case-insensitive match regular expression
Ereg_replace-Match and replace regular expressions
Eregi_replace-Match and replace the 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, implode-Merge array elements into strings
Htmlentities,Htmlspecialchars-SetHTMLConvert special charactersHTMLTag form
Split-Cut Strings According to rules and store them as arrays


13.4Expand 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

In factFooter. incAdd to fileISegment code. Assume that yourWebAll suffixes in the site are. Php3Files will appear in the navigation bar.Include/Navbar. incCode:

/*Output this navigation bar to link all sites except the current page. Php3File*/
#Read directory
$ D = dir ("./");
Echo"

| N ";
While ($ entry = $ d-> read ())
{
//IgnoreNo fileSituation
If (!Is_file($ Entry ))
Continue;
/*Separate the file name from the extension. Because.It is a special character of a regular expression.*/
List ($Filenm, $Fileext) = Split (".", $ entry, 2 );
//Ignore non-. Php3File status
If ($Fileext! = "Php3 ")
Continue;
/*Now we have. Php3Select all files. search for the first line (title) in the file below)
Similar$ 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
To remove spaces.
Must startPHPCode processing, such$ Title = "blahBlah"*/
Eval($ Buffer );
//Then display the link text as the title text
$Linknm= $ Title;
Break;
}
}
Fclose($Fp);
If($Entry =Basename($ PHP_SELF ))
Echo "$Linknm";
Else
Echo "$Linknm";
Echo "| ";
}
$ D-> close ();
Echo"

N ";
?>

Photo favorites

We will referenceHTTPFile system functions and fileTransfer functionMaintain 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 uploadFilesn";
Exit;
}
Else
{
If (! ($ PHP_AUTH_USER = $MyName& $ PHP_AUTH_PW = $MyPassword))
{
//If the user name is incorrect/Password pair, 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.

";
Exit;
}
}
If ($Cancelit)
{
//When the viewer presses"Cancel"The button is directed to the home page.
Header ("Location: front_2.php3 ");
Exit;
}
FunctionDo_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:Gif, jpg, mp3...
Rename ($Userfile, $Local_file);
Echo "The file is uploaded
N ";
Echo "Go Back
N ";
}
$ Title = "Upload File ";
Include ("include/Header. inc");
If (empty ($Userfile) | $Userfile= "None ")
{
//Output the following form
?>

> (You may notice a slight delay while we upload your file .)
} Else {
If($Error_msg) {Echo"$Error_msg

";}
If ($Sendit){
Do_upload();
}
}
Include ("include/Footer. inc");
?>

Image Library

Include ("Include/Common. inc");
$ Title = "Gallery ";
Include ("include/Header. inc");
?>


Here are some of our family photos. This PHP script can be really
Be made better, by splitting into multiple pages.


$ 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 thenTheThe code of the image library is read and displayed.

Related Article

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.