search

PHP光速教程

日期:2010-07-29 |  来源:redice's Blog |  作者:redice |  182 人围观 |  0 人鼓掌了! // by redice 2010.07.29
// redice@163.com


为公司实习生写的PHP学习提纲,根据自己的学习及项目开发经验总结了PHP语言最核心的知识点。可以作为PHP快速入门的教程。

1 客户端脚本和服务端脚本
客户端:VBscript(对IE依赖性很强,放弃)、Javascript
服务端:ASP、PHP、Perl

JSP(服务端,非脚本)
Python(可用服务端,非脚本)



2 学习一门语言的要点/顺序
功能、特点、语法、变量、运算符、流程控制、函数、数据结构



3 学习服务端语言的要点
数据输入输出、数据库操作、session和cookie的使用


4 PHP的功能

支持与众多服务器软件(Apache,IIS ISAPI/FastCGI,Nginx等)结合进行数据处理


5 PHP的特点

跨平台、内置函数库非常丰富(写得少做得多)、语法简洁、参考资料非常多


6 PHP的语法

// 这是注释行,注释行以//开始

phpinfo();  // 语句以;结束
?>

7 PHP的变量

松散类型,自动声明,强制转换
PHP变量以$开头(从钱开始,很实惠的一种语言)

$txt = "Hello World!";  // 字符串用""包围,转义",\
$number = 16;
?>


松散类型语言:VB,VBscript,ASP,PHP,Python
强类型语言:C(C++),JSP


8 PHP的运算符

算术运算:+,-,*,/,%(取余),++(自增1),--(自减1)

赋值运算:=,+=,-=,*=,/=,.=,%=

比较运算符:==,===,!=,>,=,
逻辑运算符:&&,||,!

其它运算符:.(字符串连接)

$i=10;
$i+=1;

echo $i;   // echo 数据输出函数,还可以用print

echo ++$i; // ?
echo $i++; // ?
?>


*两等号与三等号

== 只比较值是否相等,会将两侧值进行类型转换
=== 比较值和类型是否相同,不会进行类型转换,类型和值都相同才为真

例如:

$a="2";    // 字串型2
$b=2;    // 数值型2
$a==$b, 是对的,都是2
$a===$b,是不对的,因为$a是字符型$b是数值型,值虽一样,但类型不一样


9 PHP流程控制

顺序语句

分支语句:if else,Switch

// if else语句
if (condition)
  code to be executed if condition is true;
elseif (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false; 

// switch语句
switch (expression)
{
case label1:
  code to be executed if expression = label1;
  break;  
case label2:
  code to be executed if expression = label2;
  break;
default:
  code to be executed
  if expression is different 
  from both label1 and label2;
}


循环语句:while,for,foreach

// while循环
while (condition)
code to be executed;

// for循环
for (initialization; condition; increment)
{
  code to be executed;
}

// foreach循环,遍历数组
foreach (array as value)
{
    code to be executed;
}


// foreach循环的示例

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

foreach ($arr as $value)
{
  echo "Value: " . $value . "
";
}
?>


*结束PHP程序的执行:

exit($str); // 结束PHP执行并输出$str
die();    // 仅结束PHP执行


10 PHP函数

内置函数:
http://php.chinaunix.net/manual/en/

(1)数据输出:echo,print,print_r(输出数组)
(2)字符串操作:
// 返回$string的长度
int strlen ( string $string )

// 删除$str两端的空格或其它字符
string trim ( string $str [, string $charlist ] )

$str=" xiao ping ni hao! ";
echo trim($str);
echo "
";
echo trim($str," x!")
?>


// 字符串转大小写

string strtolower ( string $str )
string strtoupper ( string $string )

// 寻找字串

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

返回值:返回找到的子串的位置,没有找到返回false
注意:
如果子串$needle在$haystack串首出现将返回0
因此判断是否找到字串应该用===而不能用==

$str="redicecn.com";

// 下面是错误的判断
if(strpos($str,"redice")==false)
{
   echo "没有找到子串!";
}
else
{
   echo "找到了子串!";
}
?>


// 字符串截取

string substr ( string $string , int $start [, int $length ] )

// 字符串替换

string str_replace ( mixed $search , mixed $replace , mixed $subject)
string str_ireplace ( mixed $search , mixed $replace, mixed $subject) // 不区分大小写

(3)时间日期:

// time() 函数返回当前时间的 Unix 时间戳
time(void)

// date() 函数格式化一个本地时间/日期
// 默认是格林威治时区
date(format,timestamp)

// 设置为东8区
date_default_timezone_set('Etc/GMT-8');

echo date("Y-m-d H:i:s",time());
?>


自定义函数:

$sitename="电子工程社区";

function welcom($user)
{
   global $sitename; // 引用全局变量

   // 返回值
   return $user.",欢迎您的光临".$sitename."!"; 
}

// 函数调用
echo welcom("redice");
?>

11 PHP的数据结构

数组

// 数值数组的定义

(1) 自动分配key
$names = array("芙蓉姐姐","凤姐","犀利哥");

(2) 手动分配key
$names[0]="芙蓉姐姐";
$names[1]="凤姐";
$names[2]="犀利哥";

// 关联数组的定义

$ages = array("芙蓉姐姐"=>32, "凤姐"=>29, "犀利哥"=>42);

也可以这样

$ages["芙蓉姐姐"] = 32;
$ages["凤姐"] = 29;
$ages["犀利哥"] = 42;


// 多维数组

$students = array
(
  "0911120688"=>array
  (
  "姓名"=>"齐鹏",
  "年龄"=>24,
  "性别"=>"男"
  ),
  "0911120699"=>array
  (
  "姓名"=>"宋玉伟",
  "年龄"=>22,
  "性别"=>"女"
  ),
  "0911120670"=>array
  (
  "姓名"=>"陈素芳",
  "年龄"=>22,
  "性别"=>"女"
  )
);

12 PHP输入(获取客户端输入)

(1)$_GET 变量
$_GET 变量是一个数组,内容是由 HTTP GET 方法发送的变量名称和值。

(2)$_POST 变量
$_POST 变量是一个数组,内容是由 HTTP POST 方法发送的变量名称和值。

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


13 SESSION和COOKIE的使用

(1)SESSION

保存在服务端,服务器通过COOKIE中的SESSIONID判断,常用来进行身份验证。

使用SESSION前需要用session_start()启动会话,
由于session_start()需要修改HTTP应答报文的COOKIE头(存SESSIONID),
因此session_start()必须在HTTP应答正文输出之前被调用。

// 创建session
session_start();
$_SESSION['user']="redice";
?>


// 读取session
session_start();
echo $_SESSION['user'];
?>

删除SESSION
unset($_SESSION['user']);
?>

session_destroy(); // 将删除所有的session
?>

(2)COOKIE

保存在客户端,随请求报文一起被发送到服务端,
常用来存储用户自定义设置、浏览记录等与安全无关的数据。

*COOKIE在客户端存储,可被用户修改,因此不能存储敏感数据。


// 创建cookie
setcookie(name, value, expire);

setcookie()也需要修改HTTP应答头,因此需要在输出任何正文之前被调用

setcookie("user", "redice", time()+3600);
?>

// 读取cookie
echo $_COOKIE["user"];
?>

// 删除cookie
// 设置立即过期,客户端(浏览器)会自动删除
setcookie("user", "", time()-3600);
?>


14 数据库操作

操作流程:

连接数据库->选择库->设置采用的字符集
->操作数据(查询,更新,删除,插入)->关闭数据库

$conn=0;
$conn = mysql_connect("localhost","root","redice2009");
if (!$conn)
{
  die("不能打开数据库连接,错误: " . mysql_error());
}

// 选择数据库
mysql_select_db("thymall", $conn);

// 设置mysql数据库输出数据的字符集
mysql_query("set names 'gbk'");

$sql="select * from thym_goods LIMIT 5";

// 执行查询
$result=mysql_query($sql,$conn);

// 遍历查询结果
while($result && $row=mysql_fetch_array($result))
{
}

// 关闭数据库
mysql_close($conn);
?>



15 其它

良好的程序风格:缩进,注释

开发工具的选取原则:代码关键字高亮,自动完成
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.