Php 简明教程
PHP - Web Concepts
PHP 是一种服务器端脚本语言,用于创建动态网页。它是 Web 开发中最流行的编程语言之一。本章旨在让您熟悉使用 PHP 进行 Web 应用程序开发的某些重要概念。
PHP is a server-side scripting language that is used to create dynamic webpages. It is one of the most popular programming languages for web development. This chapter aims to let you get familiarized with certain important concepts of web application development using PHP.
基于 Web 的应用程序是网页的集合。网页主要是用 HTML 标记创建的。HTML 包含用于定义页面元素(如文本、图像、表格等)外观的不同 HTML 标记。因此,HTML 本质上创建了一个静态网页。
A web-based application is a collection of webpages. A webpage is mainly created with HTML tags. HTML consists of different HTML tags which are required to define the appearance of page elements like text, image, table, etc. Hence, HTML essentially creates a static webpage.
Web 应用托管在安装了 PHP 模块的 HTTP 服务器上。浏览器作为 http 客户端,遵循 HTTP 协议来与服务器建立通信。
A Web application is hosted on a HTTP server with PHP module installed. The browser acts as a http client, to establish communication with the server, following HTTP protocol.
How to Add Dynamic Content on a Webpage?
要向网页添加动态内容,可以使用两种方式。
To add dynamic content io a webpage, there are two possibilities.
JavaScript 是一种客户端脚本语言,它可以访问 HTML 文档对象模型并在客户端浏览器上呈现动态内容。JavaScript 代码可以嵌入到 HTML 页面中。
JavaScript is a client-side scripting language, that can access the HTML document object model and render dynamic content on the client browser. JavaScript code can be embedded in HTML page.
浏览器可以通过 HTML 表单元素收集用户数据,然后将其发送到 HTTP 服务器进行处理。PHP 是一种广泛使用的服务器端处理语言。PHP 脚本也可以嵌入到 HTML 页面中。
The browser may collect data from the user in the form of HTML form elements and send it to a HTTP server for processing. PHP is a widely used Server-side processing language. PHP script can also be embedded inside HTML page.
Example
在下面的脚本中,嵌入到 HTML 中的 JavaScript 代码根据客户端浏览器呈现当前日期,而 PHP 代码则根据脚本托管的服务器显示当前日期。
In the following script, JavaScript code embedded in HTML renders the current date as per the client browser, and the PHP code displays the current date as per the server, where this script is hosted.
<!DOCTYPE html>
<html>
<body>
<script type="text/JavaScript">
document.write("Client's date :"+Date()+"\n");
</script>
<?php
date_default_timezone_set("Asia/Calcutta");
echo "server's date is " . date("Y-m-d") . "\n";
echo "The time is " . date("h:i:sa");
?>
</body>
</html>
PHP can intercept and process the data from HTML forms 。这使你可以收集你的用户的信息。下一章将讨论 PHP 表单处理。
PHP can intercept and process the data from HTML forms. This allows you to collect information from your users. The next chapter discusses PHP’s form handling.
PHP can be used to interact with databases ,例如 MySQL 和 PostgreSQL。这使你能够存储和检索你的数据库中的数据,并动态填充网页或为 Web 应用程序提供动力。PHP 包括用于数据库处理的 mysql、mysqli 和 PDO 扩展。
PHP can be used to interact with databases such as MySQL and PostgreSQL. This allows you to store and retrieve data from your database, and dynamically populate the web pages or to power the web applications. PHP includes mysql, mysqli and PDO extensions for database handling.
PHP can handle the data received from the client 使用 HTTP GET 和 POST 方法。我们将在后面的章节详细讨论 PHP 如何处理 GET/POST 方法。
PHP can handle the data received from the client with HTTP GET as well as POST methods. We shall discuss in detail, how PHP handles GET/POST methods in one of the latter chapters.
HTTP is a stateless protocol 。不过,它允许在服务器和客户端分别维护会话和 cookie。PHP 可用于创建和管理会话和 cookie。当用户浏览你的网站时,会话允许你跟踪各个用户,而 cookie 允许你将信息存储在用户的计算机上以供日后使用。在后续章节中,我们将学习 PHP 如何处理会话和 cookie。
HTTP is a stateless protocol. However, it allows Sessions and cookies to be maintained on server and client respectively. PHP can be used to create and manage sessions and cookies. Sessions allow you to track individual users as they navigate your website, while cookies allow you to store information on the user’s computer for later use. In of the subsequent chapters, we shall learn how PHP handles sessions and cookies.
PHP can be used to upload files to your web server 。这使你能够创建允许用户上传文件(例如图片、视频或文档)的 Web 应用程序。
PHP can be used to upload files to your web server. This allows you to create web applications that allow users to upload files, such as images, videos, or documents.
You can use PHP to create a login page for your website 。当用户输入他们的用户名和密码时,PHP 可以检查数据库以查看用户是否有效。如果用户有效,PHP 可以让用户登录并将其重定向到你的网站的主页。
You can use PHP to create a login page for your website. When the user enters their username and password, PHP can check the database to see if the user is valid. If the user is valid, PHP can log the user in and redirect them to the main page of your website.
Identifying Browser & Platform
PHP 创建了一些可以在用于设置 PHP 环境的 phpinfo.php 页面中看到的 environment variables 。
PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment.
PHP 设置的环境变量之一是 HTTP_USER_AGENT ,它标识用户的浏览器和操作系统。
One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user’s browser and operating system.
PHP 提供了一个 getenv() 函数来访问所有环境变量的值。HTTP_USER_AGENT 环境变量中包含的信息可用于根据浏览器创建适当的动态内容。
PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the browser.
Example
下面的示例展示了如何识别客户端浏览器和操作系统。
Following example demonstrates how you can identify a client browser and operating system.
NOTE − preg_match() 函数在 PHP Regular expression 会话中讨论。
NOTE − The function preg_match()is discussed in PHP Regular expression session.
<?php
function getBrowser() {
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version = "";
//First get the platform
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
} elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
// Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) {
$bname = 'Internet Explorer';
$ub = "MSIE";
} elseif(preg_match('/Firefox/i',$u_agent)) {
$bname = 'Mozilla Firefox';
$ub = "Firefox";
} elseif(preg_match('/Chrome/i',$u_agent)) {
$bname = 'Google Chrome';
$ub = "Chrome";
} elseif(preg_match('/Safari/i',$u_agent)) {
$bname = 'Apple Safari';
$ub = "Safari";
} elseif(preg_match('/Opera/i',$u_agent)) {
$bname = 'Opera';
$ub = "Opera";
} elseif(preg_match('/Netscape/i',$u_agent)) {
$bname = 'Netscape';
$ub = "Netscape";
}
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) . ')
[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
} else {
$version= $matches['version'][1];
}
} else {
$version= $matches['version'][0];
}
// check if we have a number
if ($version == null || $version == "") {$version = "?";}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
// now try it
$ua = getBrowser();
$yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] .
" on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
这在我的机器上产生以下结果。根据你使用的计算机,此结果可能有所不同。
This is producing following result on my machine. This result may be different for your computer depending on what you are using.
它将产生以下结果 −
It will produce the following result −
Your browser: Google Chrome 54.0.2840.99 on windows reports:
Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/54.0.2840.99 Safari/537.36
Display Images Randomly
PHP rand() 函数用于生成随机数。此函数可以生成指定范围内内的数。应设置随机数生成器的种子,以防止生成规则的数字模式。这是通过使用 srand() 函数来实现的,该函数指定种子号作为其参数。
The PHP rand() function is used to generate a random number.i This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifies the seed number as its argument.
Example
以下示例展示了如何每次从四张图片中显示不同的图片 −
Following example demonstrates how you can display different image each time out of four images −
<?php
srand( microtime() * 1000000 );
$num = rand( 1, 4 );
switch( $num ) {
case 1: $image_file = "/php/images/php_image_sample_1.jpg";
break;
case 2: $image_file = "/php/images/php_image_sample_2.jpg";
break;
case 3: $image_file = "/php/images/php_image_sample_3.jpg";
break;
case 4: $image_file = "/php/images/php_image_sample_4.jpg";
break;
}
echo "Random Image : <img src=$image_file />";
?>
它将产生以下结果 −
It will produce the following result −
Using HTML Forms
处理 HTML 表单和 PHP 时需要注意的最重要一点是 HTML 页面中的任何表单元素都将自动对你的 PHP 脚本可用。
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
Example
通过将源代码放入 test.php 脚本中,尝试以下示例。
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<form action = "<?php <b>$_PHP_SELF</b> ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
它将产生以下结果 −
It will produce the following result −
-
The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called and will produce following result −
-
The method = "POST" is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST chapter.
Browser Redirection
PHP header() 函数向浏览器提供原始的 HTTP 标头,可用于将其重定向到其他位置。重定向脚本应位于页面的最顶部,以防页面任何其他部分加载。
The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading.
目标由 Location: 标头指定为 header() 函数的参数。在调用此函数后,可以使用 exit() 函数来停止解析代码的其余部分。
The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.
Example
以下示例演示如何将浏览器请求重定向到另一个网页。通过将源代码放入 test.php 脚本中,尝试此示例。
Following example demonstrates how you can redirect a browser request to another web page. Try out this example by putting the source code in test.php script.
<?php
if( $_POST["location"] ) {
$location = $_POST["location"];
header( "Location:$location" );
exit();
}
?>
<p>Choose a site to visit :</p>
<form action = "<?php <b>$_SERVER['PHP_SELF']</b> ?>" method ="POST">
<select name = "location">.
<option value = "http://www.tutorialspoint.com">
Tutorialspoint.com
</option>
<option value = "http://www.google.com">
Google Search Page
</option>
</select>
<input type = "submit" />
</form>
它将产生以下结果 −
It will produce the following result −