search
HomeBackend DevelopmentPHP TutorialPHP新手上路(六)

建设一个简单交互的网站(二)

5.5 计数器

  让我们在首页上加上一个计数器。这个例子已经被讲过多次了,但是还是有利于演示怎样读写文件以及创建自己的函数。counter.inc包含以下代码:


/*
|| 一个简单的计数器
*/
function get_hitcount($counter_file)
{
/* 将计数器归零
这样如果计数器还未被使用,初始值将是1
你当然也可以把初始值设成20000来骗人咯
*/
$count=0;
// 如果存放计数器文件已经存在,读取其中的内容
if ( file_exists($counter_file) ) 
{
$fp=fopen($counter_file,"r");
// 我们只取了前20位,希望你的站点不要太受欢迎啊
$count=0+fgets($fp,20);
// 由于函数fgets()返回字符串,我们可以通过加0的方法将其自动转换为整数
fclose($fp);
// 对文件操作完毕
}
// 增加一次计数值
$count++;
// 将新的计数值写入文件
$fp=fopen($counter_file,"w");
fputs($fp,$count);
fclose($fp);
# 返回计数值
return ($count);
}
?>

然后我们更改front.php3文件以显示这个计数器:

include("include/counter.inc");
// 我把计数值放在文件counter.txt中,读出并输出
PRintf ("
%06d

n",
get_hitcount("counter.txt"));
include("include/footer.inc");
?>
看看我们的新front.php3

5.6 反馈表单

  让我们再添加一个反馈表单以便你的浏览者填写并e-mail给你。举例来说我们用一种很简单的方法实现它,我们只需要两个页面:一个为浏览者提供输入表单;一个获得表单数据并处理、mail给你。

  PHP中获取表单数据是很简单的。当一个表单被发送后,表单中所包含的各个元素被赋上了相应的值,而这样就可以像引用一般变量一样使用了。




  在process_form.php3中,变量$mytext就被赋予了输入的值--非常简单!同样的,你可以从列表框、多选框、单选框、按钮等表单元素中取得变量值。你唯一要做的就是为表单中的每一个元素取名以便将来可以引用。

  根据这个方法,我们可以生成一个简单的包含三个元素的表单:姓名、e-mail地址和留言。当浏览者发送表单后,处理该表单的PHP页面(sendfdbk.php3)读取数据,检查姓名是否为空,最后将数据mail给你。

表单:form.php3

include("include/common.inc");
$title = "Feedback";
include("include/header.inc");
?>














include("include/footer.inc");
?>

处理表单:sendfdbk.php3

include("include/common.inc");
$title = "Feedback";
include("include/header.inc");
if ( $name == "" ) 
{
// 现在我很讨厌匿名的留言!
echo "Duh ? How come you are anonymous?";
} 
elseif ($name == "Your name") 
{
// 这个浏览者真是不想透露姓名啊!
echo "Hello ? Your name is supposed to be replaced with
your actual name!";
} 
else 
{
// 输出一段礼貌的感谢语
echo "
Hello, $name.


Thank you for your feedback. It is greatly appreciated.


Thanking you


$MyName

$MyEmailLink
";
// 最后mail出去
mail($MyEmail, "Feedback.","
Name : $name
E-mail : $email
Comment : $comment 
");
}
include("include/footer.inc");
?>

  注意:如果在你的测试过程中,该程序末能正常工作,请查看你的PHP配置文件(PHP3为php3.ini,PHP4为php.in)有没有设置好。因为本程序需要您的PHP配置文件作如下的设置:

  首先,用NotePad打开你的php3.ini或是php.ini文件,查看一下[mail function]有没有设置好,默认的情况如下所示:
SMTP = localhost 
sendmail_from = me@localhost.com
给SMTP设置SMTP服务器,最好是你当地的SMTP服务器,我这里以21cn的SMTP服务器作为例子,然后,在sendmail_from处填上你的E-MAIL地址,例如可以改成这样:
SMTP = smtp.21cn.com
sendmail_from = pert@21cn.com 
修改后不要忘了重启Apache,IIS或PWS服务哦. 


5.7 简单的站内搜索引擎

  PHP可以调用外部程序。在Unix环境下我们可以利用程序grep实现一个简单的搜索引擎。我们可以做的稍微复杂一些:使用一个页面既输出一个表单供用户输入搜索字串又输出查询结果。


include("include/common.inc");
$title = "Search";
include("include/header.inc");
?>


" METHOD="POST">
"
SIZE="20" MAXLENGTH="30">




if ( ! empty($searchstr) ) 
{
// empty()用来检查查询字串是否为空
// 如果不为空,调用grep查询
echo "
n";
// 调用grep对所有文件进行大小写非敏感模式的查询
$cmdstr = "grep -i $searchstr *";
$fp = popen( $cmdstr, "r" ); // 执行命令并输出管道
$myresult = array(); // 存储查询结果
while( $buffer = fgetss ($fp, 4096)) 
{
// grep返回这样格式: 文件名:匹配字串出现行数
// 因此我们利用函数split()分离处理数据
list($fname, $fline) = split(":",$buffer, 2);
// 我们只输出第一次匹配的结果
if ( !defined($myresult[$fname]))
$myresult[$fname] = $fline;
}
// 现在我们将结果存储在数组中,下面就可以处理并输出了
if ( count($myresult) )
{
echo "
    n";
    while(list($fname,$fline) = each($myresult))
    echo "

  1. $fname : $fline
  2. n";
    echo "
n";
} 
else 
{
// 如果没有查询结果
echo "Sorry. Search on $searchstr
returned no results.
n";
}
pclose($fp);
}
?>

include("include/footer.inc");
?>


注释:

PHP_SELF是PHP内建的变量。包含当前文件名。 
fgets()按行读取文件,最多4096(指定)字符长度。 
fgetss()与fgets()相似,只是解析输出的HTML标记。 
split()有一个参数是2,因为我们只需要把输出分成两部分。另外需要省略":"。 
each()是一个数组操作函数,用来更方便的遍历整个数组。 
popen()、pclose()与fopen()、fclose()的功能很相似,只是增加了管道处理。 
请注意以上的代码并不是实现一个搜索引擎的好办法。这只是有助于我们更好学习PHP而举出的一个例子而已。理想的情况是你应该建立一个包含关键字的数据库然后进行搜索。  
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version