SoFunction
Updated on 2025-04-08

Other features of


5. Other miscellaneous


5.1 Generate an image



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

<?

Header("Content-type: image/gif");

$string=implode($argv," ");

$im = imagecreatefromgif("images/");

$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 snippet lacks comments. Please refer to the image processing function section of PHP Manual)

This code is called in other pages with the following tag <img src="button.php3?text">, and then the above button.php3 code obtains the text value and adds the value to the other acquired image file - in the above code, the image file is images/---last output to the browser. If you want to use the image button in the form field, but don't want to have to regenerate a new image after each text on the button changes, you can use such a simple method to dynamically generate the image file.



5.2 Cookies



PHP supports HTTP-based cookies. You can use cookies as conveniently as using general variables when needed. Cookies are some information fragments saved by the browser on the client, so you can know whether anyone on a specific PC has visited your site, the traces of the browser on your site, etc. A typical example of using cookies is the identification of viewer preferences. Cookies are set by the function setcookie(). Like the function header() that outputs HTTP headers, setcookie() must be called before any actual content cup is output to the browser. Here 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 was 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 

{

// Welcome to visit again

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

// Read the cookie and make a judgment

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 verification cannot be implemented when PHP is running in CGI mode. We can use the function header() to send HTTP header to force verification, and the client browser will pop up a dialog box for entering the user name and password. These two variables are stored in $PHP_AUTH_USER and $PHP_AUTH_PW, which you can use to verify that it is legal and allow entry. The following example verifies a user's login by 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 it is the wrong user name/password pair, force 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, it is unlikely that the user name/password pairs are obvious in the code segment as above, but instead use the database or encrypted password file to access them.



5.4 File Upload



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

(  ):

<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="24" MAXLENGTH="80">

<BR><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>



Here are the files that are processed:

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

// You need to have write permissions for 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 () 

{

// This is your page content

}

<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 commonly used functions.



Array





array- Generate array

count - The number of array elements

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

list - List the array elements

each - Return to the next key/value pair

current - Return to the current array element

next,prev - Passing back the pointer 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 the directory

dir- - Catalog category

opendir, readdir, closedir - Open, read, close directory

fopen, fclose - Open and close files

fgets, fgetss- Read content line by line

file - Read the entire file into an array variable



Regular expressions



ereg - Match regular expression

eregi - Case non-sensitive matching regular expression

ereg_replace -Match regular expressions and replace

eregi_replace -Case non-sensitive matching regular expressions and replace

split -  Slice the string according to the rules and store it in an array situation






String



AddSlashes - Use string after adding slashes

echo - Output one or more strings

join, implode - Merge array elements into string

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

split -  Slice the string according to the rules and store it in an array situation.

5.6 Expand our example homepage



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



In fact, it is just adding a piece of code to the file. Suppose that all files in your web site with the suffix .php3 will appear in the navigation bar, and the following is the code stored as include/:

<?

/* Output this navigation bar to link all website .php3 files except the current page */

# Read the directory

$d = dir("./");

echo "<P ALIGN=\"CENTER\"> | \n";

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

{

// Ignore no file

if ( !is_file($entry) )

continue;

/* Separate the file name from the extension. Since . is a special character for regular expressions, it should be exported with \*/

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

// Ignore non.php3 files

if( $fileext != "php3" )

continue;

/* Now we have selected all the .php3 files, search for the first line (title) in the file below.

Similar to $title="something";

And separate the above title contents 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 searching

// But it can cause big trouble when you change the variable name

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

{

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

Do processing such as removing spaces.

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 "<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 where image files are placed.

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



File upload

<?

include("include/");

// We will do user verification again 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 files\n";

exit;



else 

{

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

{

// If it is the wrong user name/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.<P>";

exit;



}

if ( $cancelit ) 

{

// When the viewer presses the "Cancel" button, he will turn to the home 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 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 what kind of file it is: 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/");

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><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><BR>"; 
}

if ( $sendit ) {

do_upload ();



}

include("include/");

?>



Photo gallery





<?

include("include/");

$title = "Gallery";

include("include/");

?>

<P>

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

be made better, by splitting into multiple pages.

</P>

<?

$d = dir("photos");

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

{

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

echo "<IMG SRC=\"photos/$entry\">\n";

}

$d->close();

?>

<?

include("include/");

?>



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 will be read and displayed by the code in the photo gallery above.