Home  >  Article  >  Backend Development  >  Other functions_PHP tutorial

Other functions_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 16:01:36788browse

Reprinted from php Chinese user 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 snippet lacks comments, please refer to the image processing function section of the PHP Manual)
This code is called in other pages through the following tag , and then the above The button.php3 code section obtains the text value and adds the value to the image file obtained separately - in the above code, the image file is images/button1.gif - and finally outputs 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 the cookie is not set, assign the current time value to the cookie
// The last parameter in the function declares the time the cookie will be 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 visit again
echo "Hello there, welcome back
";
// 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 Based on HTTP verification

HTTP-based authentication is not possible 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 the wrong username/password Yes, 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, it is more practical References are unlikely to use explicit username/password pairs like the snippet above, but instead use a database or encrypted password file 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 - 生成数组
count - 数组元素个数
sort - 数组排序,另有其他几种排序函数可供使用
list - 列出数组元素
each - 返回下一个key/value对
current - 返回当前数组元素
next,prev - 传回当前数组元素前后指针



日期和时间

checkdate - 验证日期/时间格式
date - 生成日期/时间格式
time - 当前时间信息
strftime - 格式化日期/时间

目录、文件系统

chdir - 改变目录
dir - 目录类别
opendir, readdir, closedir - 开启、读取、关闭目录
fopen, fclose - 开启、关闭文件
fgets, fgetss - 逐行读取内容
file - 将整个文件读入一个数组变量中

正则表达式

ereg - 匹配正则表达式
eregi - 大小写非敏感匹配正则表达式
ereg_replace -匹配正则表达式并替换
eregi_replace -大小写非敏感匹配正则表达式并替换
split - 依规则切开字符串并以数组形势存储



字符串

AddSlashes - 加上斜杠后使用字符串
echo - 输出一个或多个字符串
join, implode - 将数组元素合并为字符串
htmlentities, htmlspecialchars - 将HTML特殊字符转换为HTML标记形式
split - 依规则切开字符串并以数组形势存储
5.6 扩展我们的范例主页

我们将使用以上提到的一些函数和思想为我们的范例主页添加更多的动态内容。我们可以在每个页面的顶部加上导航栏,同时使得当前页自动的不被链接显示;同时还可以添加一个用户验证表单以便上传音乐、图像等文件并自动更新页面。

导航栏

实际上就是在footer.inc文件中加上一段代码。假设你的web站点中所有后缀为.php3的文件都会出现在导航栏中,以下就是被存为include/navbar.inc的代码:
/* 输出该导航栏,链接所有除当前页的站内.php3文件 */
# 读取目录
$d = dir("./");
echo "

| n";
while($entry = $d->read())
{
// 忽略无文件情况
if ( !is_file($entry) )
continue;
/* 将文件名与扩展名分开。Since . is a special character in regular expressions, it should be introduced using */
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 for the first line (title) in the file
similar to $title ="something";
And separate the above title content and use it 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 it may cause trouble when you change the variable name
if (ereg("title *= *"", $buffer))
{
/* We have achieved The title content can be processed based on
to remove 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 "$linknm";
echo " | ";
}
$d->close();
echo "

n";
?>

Photo Favorites

We will use 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 page that can list all the photos in the directory.

File upload
include("include/common.inc");
// Let’s 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 the username/password pair is wrong, 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 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 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>









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

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.


$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 photo gallery above.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/316806.htmlTechArticleReprinted from php Chinese users 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: im...
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