Home  >  Article  >  Backend Development  >  5. Other functions of PHP_PHP tutorial

5. Other functions of PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 16:08:48733browse


5. Other miscellaneous items


5.1 Generate images



PHP can operate and process images. If you have the GD library installed, you can even generate images using PHP.


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’s Note: The above code segment lacks comments, please refer to the image processing function section of PHP Manual)

This code is called in other pages through the following tag , and then the above button.php3 code obtains the text value and obtains the image in another Add this value to the file--in the above code, the image file is images/button1.gif--and finally output it to the browser. If you want to use an image button in a form field, but don't want to have to regenerate a new image every time the text on the button changes, 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 just as easily as regular variables. Cookies are pieces of information that the browser saves on the client, so you can know whether anyone on a specific PC has visited your site, the visitor's traces on your site, and so on. A typical example of using cookies is the screening of browser preferences. Cookies are set by the function setcookie(). Like the function header() that outputs HTTP headers, setcookie() must be called before any actual content is output to the browser. The following is a simple example:


if (empty($VisitedBefore))

{

// If no cookie is set, Assign the current time value to the cookie

// The last parameter in the function declares the time the cookie is saved

// In this example it is 1 year

/ / The time() function returns the time in seconds since January 1, 1970

SetCookie("VisitedBefore",time(), time()+(60*60*24*365) );

}

else

{

// Visitors are welcome to come again

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

// Read the cookie and determine

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

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

}

?>



5.3 HTTP-based authentication



HTTP-based authentication cannot be implemented when PHP is running in CGI mode. We can use the function header() to send an HTTP header to force authentication, and the client browser will pop up a dialog box for entering the username and password. These two variables are stored in $PHP_AUTH_USER and $PHP_AUTH_PW. You can use these two variables to verify legality and allow entry. The following example authenticates a user's login for tnc/nature using a username/password pair:


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 buttonn";

exit;

}

else

{

if ( !($ PHP_AUTH_USER=="tnc" && $PHP_AUTH_PW=="nature")
)

{

// If it is a wrong username/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;

}

else

{

echo "Welcome tnc!";

}

?>

In fact, in actual references, it is unlikely to use the obvious user name/password pair in the code snippet above, but instead uses a database or encrypted Password files 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 above or IE3 or above.以下就是该功能的简单演示:

( upload.html ):





Upload Your File






ENCTYPE="multipart/form-data" METHOD=POST>


NAME="MAX_FILE_SIZE" VALUE="2000000">


NAME="uploadfile" SIZE="24" MAXLENGTH="80">






NAME="sendit"> 


NAME="cancelit">




(You may notice a slight 

delay while we upload your file.)








下面是处理上传的文件:

( receiver.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 ();

// 你需要对以下目录有写权限

$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 () 

{

// 这里是你的页面内容

}





php3 Receiving Script






if ( $error_msg ) { echo "$error_msg

"; 
}

if ( $sendit ) 

{

do_upload ();



elseif ( $cancelit ) 

{

header ( "Location: $some_other_script" );

exit;



else 

{

some_other_func ();

}

?>







5.5 常用函数



我们简单来看看一些常用的函数。



Array





array - generate array

count - number of array elements

sort - Array sorting, there are several other sorting functions available

list - List array elements

each - Return the next key/value pair

current - Returns the current array element

next,prev - Returns the pointers before and after the current array element







Date and Time



checkdate - Verify date/time format

date - Generate date/time format

time - Current time information

strftime - Format date/time



Directory, file system



chdir - Change directory

dir - Directory category

opendir, readdir, closedir - open, read, close the directory

fopen, fclose - open, close the file

fgets, fgetss - read the content line by line

file - Read the entire file into an array variable



Regular expression



ereg - Match regular expression

eregi - Matches regular expressions in case insensitive

ereg_replace - Matches regular expressions and replaces them

eregi_replace - Matches regular expressions in case insensitive cases and replaces them

split - Split the string according to the rules and store it in array form






String



AddSlashes - Use a string after adding a slash

echo - Output one or more strings

join, implode - Combine array elements into a string

htmlentities, htmlspecialchars - Convert HTML special characters into HTML tag form

split - Split the string according to rules and store it in array form

5.6 Extend our sample homepage



We will use some of the functions and ideas mentioned above to add more dynamic content to our sample homepage. We can add a navigation bar at the top of each page, and at the same time make the current page automatically not displayed by links; we can also add a user verification form to upload music, images and other files and automatically update the page.
Navigation bar



is actually adding a piece of code to the footer.inc file. Assuming that all files with the suffix .php3 in your website will appear in the navigation bar, the following is the code saved as include/navbar.inc:


/* Output the navigation bar and link all .php3 files in the site except the current page */

# Read directory

$d = dir("./");

echo "

| n";

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

{

/ / Ignore no file condition

if ( !is_file($entry) )

continue;

/* Separate the file name from the extension. Since . is a special character in regular expressions, it should be introduced */

list($filenm, $fileext) = split(".",$entry, 2);

// Ignore Non-.php3 files

if( $fileext != "php3" )

continue;

/* Now that we have selected all the .php3 files, let’s search The first line (title) in the file

is similar to $title="something";

and separate the above title content as link text */

$linknm = "";

$fp=fopen($entry,"r");

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

{

$buffer = trim($buffer);

// We have put the title of each file on the first line of the file for easy search

// But when you Changing variable names may cause trouble

if (ereg("title *= *"", $buffer))

{

/* We have obtained The title content can be removed based on

.

must be processed in PHP code, such as $title = "blah blah" */

. eval($buffer);

// Then display the link text as title text

$linknm = $title;

break;

}

}

fclose($fp);

if ( $entry == basename($PHP_SELF) )

echo "$linknm";

else

echo "$linknm";

echo " | ";

}

$d->close();

echo "

n";

?>



Photo Collection



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

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



File upload


include("include/common.inc");

// We are here Do another user verification here

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 filesn";

exit;

}

else

{

if ( !($PHP_AUTH_USER==$MyName && $PHP_AUTH_PW==$MyPassword ) )

{

// If it is a wrong username/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 visitor presses the "Cancel" button, it will redirect 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 use this Check file name/type pairs to determine what kind of file it is: 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

?>

" ENCTYPE= "multipart/form-data"
METHOD=POST>



MAXLENGTH="80">












(You may notice a slight delay while
we upload your file.)
< ;/I>


} else {

if ( $error_msg ) { echo "$error_msg

";
}

if ( $sendit ) {

do_upload ();

}

}

include("include/footer.inc");

?>



Photo Gallery






include("include/common.inc");

$title = "Gallery";

include("include/header. inc");

?>



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

be made better, by splitting into multiple pages. while($entry = $d->read())

{

if (is_file("photos/$entry"))

echo "n";

}

$d->close();

?>


include("include/footer.inc");

?>



Also, you can upload the file in the file upload form Add an input element to describe the uploaded file. This element will be stored in the file and then read and displayed by the code in the photo gallery above.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314690.htmlTechArticle5. Other miscellaneous items 5.1 Generate images PHP can operate and process images. If you have the GD library installed, you can even generate images using PHP. ? Header("Content-type:image/gif"); $string=imp...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn