Home Backend Development PHP Tutorial PHP新手上路(六)

PHP新手上路(六)

Jun 01, 2016 pm 02:31 PM

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

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles