5.PHP Other features _php basics

Source: Internet
Author: User
Tags ereg http authentication php script php3 file setcookie

5. Other Miscellaneous


5.1 Generating Images



PHP can manipulate image processing. 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);

?>

(Translator Note: The above code snippet is missing comments, please refer to the PHP Manual image processing function section)

This code is


5.2 Cookies



PHP supports cookies based on HTTP. You can use cookies as easily as you would use a generic variable when you need it. Cookies are pieces of information that the browser keeps in the client, so you can tell whether anyone on a particular PC has visited your site, the viewer's trail on your site, and so on. A typical example of using cookies is the screening of viewers ' preferences. Cookies are set by Function Setcookie (). As with the function header () of the output HTTP headers, Setcookie () must be invoked before any actual content cups are exported to the browser. Here's 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 time the cookie was saved

In this case, 1 years.

The time () function returns the number of seconds since January 1, 1970

Setcookie ("Visitedbefore", Time (), Time () + (60*60*24*365));

}

Else

{

Visitors are welcome to visit again

echo "Hello there, welcome back<br>";

Read cookies and judge

if ((Time ()-$VisitedBefore) >= "(60*60*24*7)")

echo "Why did you take a week to come back. You are here should to more often!?
";

}

?>



5.3 Based on HTTP authentication



HTTP-based authentication is not possible when PHP is running in CGI mode. We can use the function header () to send HTTP header enforcement authentication, and the client browser pops up a dialog box for entering a username and password. These two variables are stored in $php_auth_user and $PHP_AUTH_PW, and you can use these two variables to validate the legality and allow entry. The following example validates a user's login through a user name/password pair for 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/password pair is incorrect, force re-verify

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, it is unlikely that the actual reference would be as obvious as the user name/password pair used in the code snippet above, but to access them using a database or encrypted password file.



5.4 File Upload



You can use PHP to implement the function of the file, note that the client's browser should be Netscape3 or above or IE3. Here's a simple demo of this feature:

(upload.html):

<HTML>

<HEAD>

<title>upload Your file</title>

</HEAD>

<BODY>

<form action= "Receiver.php3"

Enctype= "Multipart/form-data" method=post>

<input type= "HIDDEN"

Name= "max_file_size" value= "2000000" >

<input type= "FILE"

Name= "UploadFile" size= "maxlength=" >

<BR><BR>

<input type= "SUBMIT" value= "Upload file!"

Name= "Sendit" >

<input type= "SUBMIT" value= "Cancel"

Name= "Cancelit" ><BR>

</FORM>

<i><font size= "2" > (May notice a slight

Delay while we upload your file.) </FONT></I>

</BODY>

</HTML>



Here is the file to process the upload:

(RECEIVER.PHP3):

?

function Do_upload ()

{

Global $uploadfile, $uploadfile _size;

Global $local _file, $error _msg;

if ($uploadfile = = "None")

{

$error _msg = "You did is 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 access to the following directory

$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 the content of your page

}

<HTML>

<HEAD>

<title>php3 receiving script</title>

</HEAD>

<BODY>

?

if ($error _msg) {echo "<B> $error _msg</b><br><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 of the commonly used functions.



Array





Array-generating arrays

Count-Number of elements in an array

Sort-array ordering, and there are several other sort functions to use

List-list array elements

Each-returns the next Key/value pair

Current-Returns the present array element

Next,prev-Returns the pointer before and after the current array element







Date and time



Checkdate-Validate Date/time format

Date-Generate dates/time formats

Time-Current information

Strftime-Format Date/time



Directory, File system



ChDir-Change Directory

Dir-Directory Category

Opendir, Readdir, Closedir-open, read, close directory

fopen, fclose-Open, close file

Fgets, FGETSS-read content line by row

File-Reads an entire file into an array variable



Regular expressions



Ereg-Matching regular expressions

Eregi-case insensitive matching regular expressions

Ereg_replace-matches regular expressions and replaces

Eregi_replace-case insensitive match regular expression and replace

Split-cut the string by rule and store it in an array situation






String



Addslashes-use string after slash-plus

echo-outputs one or more strings

Join, implode-merging array elements into strings

Htmlentities, Htmlspecialchars-converts HTML special characters to HTML markup form

Split-cut the string by rule and store it in an array situation

5.6 Expansion of our example homepage



We will use some of the functions and ideas mentioned above to add more dynamic content to our example home page. We can add a navigation bar at the top of each page, and make the current page automatically not be linked to the display, but also can be added a user to verify the form to upload music, images and other files and automatically update the page.
Navigation bar



It's actually adding a piece of code to the Footer.inc file. Suppose that all files in your Web site with the suffix. PhP3 appear in the navigation bar, and the following is the code saved as Include/navbar.inc:

?

/* Output the navigation bar, link all except the current page in the station. php3 File * *

# reading Directories

$d = Dir ("./");

echo "<p align=\" Center\ "> | \ n ";

while ($entry = $d->read ())

{

Ignore no file condition

if (!is_file ($entry))

Continue

/* Separate the file name from the extension. Because. is a regular expression special character, should be used to draw/

List ($filenm, $fileext) = Split ("\.", $entry, 2);

Ignore non. php3 file conditions

if ($fileext!= "PhP3")

Continue

/* Now we've selected the. php3 file, search for the first line (title) in the file below

Similar to $title= "something";

and separate the above headings to be used as link text * *

$LINKNM = "";

$FP =fopen ($entry, "R");

while ($buffer =fgets ($fp, 4096))

{

$buffer = Trim ($buffer);

We have placed the title of each file on the first line of the file to search

But when you change the name of the variable, it can be a big problem.

if (Ereg ("title *= *\" ", $buffer))

{

/* We have obtained the title content and can on this basis

To remove space and other processing.

Must be handled in the form of PHP code, such as $title = "blah blah" * *

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 "<a href=\" $entry \ "> $linknm </A>";

echo "|";

}

$d->close ();

echo "</p>\n";

?>



Photo Favorites



We will use HTTP based authentication, file system functions, and file upload functions to maintain the directory where image files are placed.

At the same time we need to create a page that lists all the photos in the directory.



File Upload

?

Include ("Include/common.inc");

We're going to do this again. User authentication

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 it is the wrong user name/password pair, Force again 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, it turns to the first page.

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 is 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 pairs to determine what file: 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")

{

Print 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= ">"

<BR><BR>

<input type= "SUBMIT" value= "Upload file!" Name= "Sendit" >

<input type= "SUBMIT" value= "Cancel" name= "Cancelit" ><BR>

</FORM>

<i><font size= "2" > (your may notice a slight delay while
We upload your file.) </FONT></I>

?

} else {

if ($error _msg) {echo "<B> $error _msg</b><br><br>";
}

if ($sendit) {

Do_upload ();

}

}

Include ("Include/footer.inc");

?>



Photo Gallery





?

Include ("Include/common.inc");

$title = "Gallery";

Include ("Include/header.inc");

?>

<P>

This is are some of our family photos. This PHP script can really

be made better and 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 gallery above.

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.