您的位置:首页 > 编程语言 > PHP开发

php初学笔记

2014-01-02 09:47 197 查看
<?php

?>

$txt1="Hello World";

echo $txt1 . " " . $txt2;

//

/*

*/

strlen() 函数用于计算字符串的长度。

<?php

echo strlen("Hello world!");

?>

trpos() 函数用于在字符串内检索一段字符串或一个字符。

<?php

echo strpos("Hello world!","world");//6,字符串中的首个位置是 0

?>

赋值运算符

运算符 说明 例子

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

.= x.=y x=x.y

%= x%=y x=x%y

<?php

$d=date("D");

if ($d=="Fri")

echo "Have a nice weekend!";

elseif ($d=="Sun")

echo "Have a nice Sunday!";

else

echo "Have a nice day!";

?>

如果需要在条件成立或不成立时执行多行代码,应该把这些代码行包括在花括号中:

<?php

$d=date("D");

if ($d=="Fri")

{

echo "Hello!<br />";

echo "Have a nice weekend!";

echo "See you on Monday!";

}

?>

Switch 工作原理:

对表达式(通常是变量)进行一次计算

把表达式的值与结构中 case 的值进行比较

如果存在匹配,则执行与 case 关联的代码

代码执行后,break 语句阻止代码跳入下一个 case 中继续执行

如果没有 case 为真,则使用 default 语句

<?php

switch ($x)

{

case 1:

echo "Number 1";

break;

case 2:

echo "Number 2";

break;

case 3:

echo "Number 3";

break;

default:

echo "No number between 1 and 3";

}

?>

数值数组

数值数组存储的每个元素都带有一个数字 ID 键。

例子 1

$names = array("Peter","Quagmire","Joe");

例子 2

<?php

$names[0] = "Peter";

$names[1] = "Quagmire";

$names[2] = "Joe";

echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";

?>

关联数组

例子 1

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

例子 2

<?php

$ages['Peter'] = "32";

$ages['Quagmire'] = "30";

$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";

?>

多维数组

$families = array

(

"Griffin"=>array

(

"Peter",

"Lois",

"Megan"

),

"Quagmire"=>array

(

"Glenn"

),

"Brown"=>array

(

"Cleveland",

"Loretta",

"Junior"

)

);

如果输出这个数组的话,应该类似这样:

Array

(

[Griffin] => Array

(

[0] => Peter

[1] => Lois

[2] => Megan

)

[Quagmire] => Array

(

[0] => Glenn

)

[Brown] => Array

(

[0] => Cleveland

[1] => Loretta

[2] => Junior

)

)

显示上面的数组中的一个单一的值:

echo "Is " . $families['Griffin'][2] .

" a part of the Griffin family?";

循环

while 语句

<?php

$i=1;

while($i<=5)

{

echo "The number is " . $i . "<br />";

$i++;

}

?>

do...while 语句

<?php

$i=0;

do

{

$i++;

echo "The number is " . $i . "<br />";

}

while ($i<5);

?>

for 语句

<?php

for ($i=1; $i<=5; $i++)

{

echo "Hello World!<br />";

}

?>

foreach 语句

<?php

$arr=array("one", "two", "three");

foreach ($arr as $value)

{

echo "Value: " . $value . "<br />";

}

?>

创建 PHP 函数:

<?php

function writeMyName()

{

echo "David Yang";

}

writeMyName();

?>

PHP 函数 - 添加参数

<?php

function writeMyName($fname)

{

echo $fname . " Yang.<br />";

}

echo "My name is ";

writeMyName("David");

echo "My name is ";

writeMyName("Mike");

echo "My name is ";

writeMyName("John");

?>

PHP 函数 - 返回值

<?php

function add($x,$y)

{

$total = $x + $y;

return $total;

}

echo "1 + 16 = " . add(1,16);

?>

PHP 表单处理

表单实例:

<html>

<body>

<form action="welcome.php" method="post">

Name: <input type="text" name="name" />

Age: <input type="text" name="age" />

<input type="submit" />

</form>

</body>

</html>

"welcome.php" 文件类似这样:

<html>

<body>

Welcome <?php echo $_POST["name"]; ?>.<br />

You are <?php echo $_POST["age"]; ?> years old.

</body>

</html>

$_GET 变量

$_POST 变量

$_REQUEST 变量

PHP 的 $_REQUEST 变量包含了 $_GET, $_POST 以及 $_COOKIE 的内容。

PHP Date() 函数

PHP Date() 函数可把时间戳格式化为可读性更好的日期和时间。

<?php

echo date("Y/m/d");

echo "<br />";

echo date("Y.m.d");

echo "<br />";

echo date("Y-m-d");

?>

使用 mktime() 函数为明天创建一个时间戳。

mktime() 函数可为指定的日期返回 Unix 时间戳。

语法:

mktime(hour,minute,second,month,day,year,is_dst)

如需获得某一天的时间戳,我们只要设置 mktime() 函数的 day 参数就可以了:

<?php

$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));

echo "明天是 ".date("Y/m/d", $tomorrow);

?>

以上代码的输出类似这样:

明天是 2006/07/12

PHP include 和 require 语句

在服务器执行 PHP 文件之前把该文件插入另一个 PHP 文件中。

require 会产生致命错误 (E_COMPILE_ERROR),并停止脚本

include 只会产生警告 (E_WARNING),脚本将继续

因此,如果您希望继续执行,并向用户输出结果,即使包含文件已丢失,那么请使用 include。否则,在框架、CMS 或者复杂的 PHP 应用程序编程中,请始终使用 require 向执行流引用关键文件。这有助于提高应用程序的安全性和完整性,在某个关键文件意外丢失的情况下。

例子 3

假设我们有一个定义变量的包含文件 ("vars.php"):

<?php

$color='red';

$car='BMW';

?>

这些变量可用在调用文件中:

<html>

<body>

<h1>Welcome to my home page.</h1>

<?php include 'vars.php';

echo "I have a $color $car"; // I have a red BMW

?>

</body>

</html>

fopen() 函数用于在 PHP 中打开文件。

第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件:

<html>

<body>

<?php

$file=fopen("welcome.txt","r");

?>

</body>

</html>

文件可能通过下列模式来打开:

模式 描述

r 只读。在文件的开头开始。

r+ 读/写。在文件的开头开始。

w 只写。打开并清空文件的内容;如果文件不存在,则创建新文件。

w+ 读/写。打开并清空文件的内容;如果文件不存在,则创建新文件。

a 追加。打开并向文件文件的末端进行写操作,如果文件不存在,则创建新文件。

a+ 读/追加。通过向文件末端写内容,来保持文件内容。

x 只写。创建新文件。如果文件已存在,则返回 FALSE。

x+

读/写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。

注释:如果 fopen() 无法打开指定文件,则返回 0 (false)。

例子

如果 fopen() 不能打开指定的文件,下面的例子会生成一段消息:

<html>

<body>

<?php

$file=fopen("welcome.txt","r") or exit("Unable to open file!");

?>

</body>

</html>

关闭文件

fclose() 函数用于关闭打开的文件。

<?php

$file = fopen("test.txt","r");

//some code to be executed

fclose($file);

?>

检测 End-of-file

feof() 函数检测是否已达到文件的末端 (EOF)。

在循环遍历未知长度的数据时,feof() 函数很有用。

注释:在 w 、a 以及 x 模式,您无法读取打开的文件!

if (feof($file)) echo "End of file";

逐行读取文件

fgets() 函数用于从文件中逐行读取文件。

注释:在调用该函数之后,文件指针会移动到下一行。

例子

下面的例子逐行读取文件,直到文件末端为止:

<?php

$file = fopen("welcome.txt", "r") or exit("Unable to open file!");

//Output a line of the file until the end is reached

while(!feof($file))

{

echo fgets($file). "<br />";

}

fclose($file);

?>

逐字符读取文件

fgetc() 函数用于从文件逐字符地读取文件。

注释:在调用该函数之后,文件指针会移动到下一个字符。

例子

下面的例子逐字符地读取文件,直到文件末端为止:

<?php

$file=fopen("welcome.txt","r") or exit("Unable to open file!");

while (!feof($file))

{

echo fgetc($file);

}

fclose($file);

?>

$_FILES["file"]["name"] - 被上传文件的名称

$_FILES["file"]["type"] - 被上传文件的类型

$_FILES["file"]["size"] - 被上传文件的大小,以字节计

$_FILES["file"]["tmp_name"] - 存储在服务器的文件的临时副本的名称

$_FILES["file"]["error"] - 由文件上传导致的错误代码

cookie

setcookie(name, value, expire, path, domain);

注释:setcookie() 函数必须位于 <html> 标签之前。

注释:在发送 cookie 时,cookie 的值会自动进行 URL 编码,在取回时进行自动解码(为防止 URL 编码,请使用 setrawcookie() 取而代之)。

PHP 的 $_COOKIE 变量用于取回 cookie 的值。

使用 isset() 函数来确认是否已设置了 cookie:

<html>

<body>

<?php

if (isset($_COOKIE["user"]))

echo "Welcome " . $_COOKIE["user"] . "!<br />";

else

echo "Welcome guest!<br />";

?>

</body>

</html>

删除 cookie

当删除 cookie 时,您应当使过期日期变更为过去的时间点。

<?php

// set the expiration date to one hour ago

setcookie("user", "", time()-3600);

?>

开始 PHP Session

首先必须启动会话。

session_start() 函数必须位于 <html> 标签之前:

<?php

session_start();

// store session data

$_SESSION['views']=1;

?>

<html>

<body>

<?php

//retrieve session data

echo "Pageviews=". $_SESSION['views'];

?>

</body>

</html>

终结 Session

unset() 函数用于释放指定的 session 变量:

<?php

unset($_SESSION['views']);

?>

您也可以通过 session_destroy() 函数彻底终结 session:

<?php

session_destroy();

?>

注释:session_destroy() 将重置 session,您将失去所有已存储的 session 数据。

基本的错误处理:使用 die() 函数<?php

if(!file_exists("welcome.txt"))

{

die("File not found");

}

else

{

$file=fopen("welcome.txt","r");

}

?>

创建自定义错误处理器

该函数必须有能力处理至少两个参数 (error level 和 error message),但是可以接受最多五个参数(可选的:file, line-number 以及 error context)

错误报告级别

这些错误报告级别是错误处理程序旨在处理的错误的不同的类型:

值 常量 描述

2 E_WARNING 非致命的 run-time 错误。不暂停脚本执行。

8 E_NOTICE

Run-time 通知。

脚本发现可能有错误发生,但也可能在脚本正常运行时发生。

256 E_USER_ERROR 致命的用户生成的错误。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_ERROR。

512 E_USER_WARNING 非致命的用户生成的警告。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_WARNING。

1024 E_USER_NOTICE 用户生成的通知。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_NOTICE。

4096 E_RECOVERABLE_ERROR 可捕获的致命错误。类似 E_ERROR,但可被用户定义的处理程序捕获。(参见 set_error_handler())

8191 E_ALL 所有错误和警告,除级别 E_STRICT 以外。(在 PHP 6.0,E_STRICT 是 E_ALL 的一部分)

可以修改错误处理程序,使其仅应用到某些错误

set_error_handler("customError");

实例

<?php

//error handler function

function customError($errno, $errstr)

{

echo "<b>Error:</b> [$errno] $errstr";

}

//set error handler

set_error_handler("customError");

//trigger error

echo($test);

?>

触发错误

<?php

//error handler function

function customError($errno, $errstr)

{

echo "<b>Error:</b> [$errno] $errstr<br />";

echo "Ending Script";

die();

}

//set error handler

set_error_handler("customError",E_USER_WARNING);

//trigger error

$test=2;

if ($test>1)

{

trigger_error("Value must be 1 or below",E_USER_WARNING);

}

?>

异常的基本使用

<?php

class customException extends Exception

{

public function errorMessage()

{

//error message

$errorMsg = $this->getMessage().' is not a valid E-Mail address.';

return $errorMsg;

}

}

$email = "someone@example.com";

try

{

try

{

//check for "example" in mail address

if(strpos($email, "example") !== FALSE)

{

//throw exception if email is not valid

throw new Exception($email);

}

}

catch(Exception $e)

{

//re-throw exception

throw new customException($email);

}

}

catch (customException $e)

{

//display custom message

echo $e->errorMessage();

}

?>

设置顶层异常处理器

set_exception_handler()

例子

<?php

function myException($exception)

{

echo "<b>Exception:</b> " , $exception->getMessage();

}

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');

?>

PHP 过滤器

过滤数据:

来自表单的输入数据

Cookies

服务器变量

数据库查询结果

如需过滤变量,请使用下面的过滤器函数之一:

filter_var() - 通过一个指定的过滤器来过滤单一的变量

filter_var_array() - 通过相同的或不同的过滤器来过滤多个变量

filter_input - 获取一个输入变量,并对它进行过滤

filter_input_array - 获取多个输入变量,并通过相同的或不同的过滤器对它们进行过滤

<?php

$int = 123;

if(!filter_var($int, FILTER_VALIDATE_INT))

{

echo("Integer is not valid");

}

else

{

echo("Integer is valid");

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: