php 可以单独创建 .php 文件,也可以在 HTML 中添加 php 标记后进行书写.若不显示汉字,需在标记内不添加:
header("Content-type:text/html;charset=utf-8");
一. PHP 的标记
<?php echo “hello php”; ?>
或者
<script language=“php”>echo “hello php”</script>
声明后便可以在其中编写 php 代码 php 还有其他标记方式, 不作了解.
二. php 注释
注释方式与 JS 类似.
三. 变量 与 常量
1. 变量
- 变量的声明形式为:
$a = 10;$b = "aaa";
输出变量的值,可以使用: echo 进行输出查询.同时,变量声明时允许互相进行嵌套, 如:
$n = 'hello';$$n = 'gaoshan';echo $hello;
输出结果为:
gaoshan
- 除此以外, echo还可以输出标签内容
echo "<a href = 'http://www.baidu.com'>这是一个百度的链接</a>";或echo "<input type='button' value='我是一个按钮'></input>";
那么,输出的形式即为一个连接以及一个按钮.
- 有一点需要注意的是, 赋值时$c=$a表示把 a 的值赋给 c 但是对 a 本身没有影响, 而&$c=$a 表示将 a 的储存地址赋值给 c , 之后a 和 c 改一个,另一个就跟着一起变化.
2. 常量
参数定义
常量:不能改变的量常量一经定义,就不能再次被赋值第一个参数:要定义的常量名第二个参数:常量的值第三个参数:对大小写是否 _*不敏感(true)_*
举例:
define("PI", "3.1415926", true);echo PI;echo pi;
此时,两个输出都为3.1415926, 但是如果将参数三的true改为false, 那么echo pi;报错.
3. echo 特点
- echo 后如果连接的字符串中含有变量, 那么应根据需要使用""或者'', 在""中,"$"默认为变量的声明符号,但是在''中,"$"默认为一个符号,以"$"原型进行输出.如
$name = "Tom";$age = 22;echo "我的名字叫$name,年龄$age";echo '我的名字叫$name,年龄$age';
此时的打印结果为
我的名字叫Tom,年龄22我的名字叫$name,年龄$age
- 当我们想要输出一个对象的格式及内容时, 通常采用的输出函数为var_dump( ).如
var_dump($age);var_dump("hhahsdhd");
此时打印的结果为
int(22) string(8) "hhahsdhd"
- echo 会对输出的值进行计算,如
echo "Z12" + "34B" + "5" + true;
此时打印的结果为
40 //0 + 34 + 5 + 1
4. 超关键字
可以在所有场景使用的关键字如:
echo __LINE__; // 输出此行行数
echo __FILE__; // 输出此文件的文件地址
function show() { echo __FUNCTION__; // 输出此函数的函数名};show(); // 输出为 show
次超关键字
echo $_SERVER['HTTP_USER_AGENT']; // 打印服务器信息
定义一个类
class Person { public function showName() { // 函数名不区分大小写 echo __CLASS__; //打印出是哪个类的 结果为Person echo __METHOD__; // 打印出类的方法 }}
使用创建的这个类创建对象
$p = new Person();echo $p -> showName(); // 结果为Person 和Person::showName
5. 字符串
介绍了一些 php 中操作字符串的常用函数
1. 字符串的连接输出的时候是用" . "进行连接的, 如
$str = "world";echo $str . "hahaha"; //显示为: worldhahaha
注:在这里, 用" . "和用" , "连接在视觉上是没有区别的, 但是用点连接是把两个字符串拼接为一个, 而用逗号则是把两个字符串单纯地放在一起显示而已.
2. 获取字符串的长度echo strlen($str); //显示为53. 判断子字符串第一次出现的位置
如判断 "bc" 在 "aabBcbc" 中出现的位置
echo strpos("aabBcbc", "bc"); // 输出为 5
如果不区分大小写
echo stripos("aabBcbc", "bc"); // 输出为 34. 二进制安全的概念
_*概念 :*_ 对字符串做操作时,是否代表字符串结束的"\0"字符做处理,是停止,还是继续往下检查,这个特性是继承 C语言的.
- _*不安全:*_ 停止, 因为无法读取\0后面的字符串
- _*安全:*_ 把"\0"当做字符,继续向下读取
举例:
echo strcoll("aaaa", "aaaa\0asdasds");
这里举了一个不安全的字符串相关函数,是判断两个字符串是否相等的. 我们看到, 在读取第二个字符串时, 函数将"\0"后面的内容都省略了, 判断结果为"0", 即相等.
5. 字符串的替换$str1 = "gaoshan@163.com";echo str_replace("g", "s", $str1); // 这是敏感大小写的方式echo str_ireplace("G", "s", $str1); // 这是忽略大小写的方式// 以上两个输出的结果均为: saoshan@163.com6. 字符串的截取
这里我们使用两种方法:
1) substr(要做处理的字符串, 从第几个开始截取, 截取几个字符)echo substr("hello world", 3, 4); // 输出为: lo w2) 找到字符串第一次出现的位置,并返回之后的字符
echo strstr("hello world", "lo"); // 输出结果为: lo world7. 删除字符串前后的空格
$strT = " hello world!!! "; echo trim($strT);// 输出结果为: hello world!!!8. 字符串大小写的转化
小转大
$strA = "FGJHGkbadkahd";echo strtolower($strA); // 输出结果为: fgjhgkbadkahdecho strtoupper($strA); // 输出结果为: FGJHGKBADKAHD9. 倒序字符串
echo strrev("hello PHP"); // 输出结果为: PHP olleh10. 取出标签内的内容 / 取出含标签的内容
echo strip_tags("<a href = '###'>TOM</a>");// 输出结果为: TOMecho htmlspecialchars("<a href = '###'>TOM</a>");//输出结果为: <a href = '###'>TOM</a>
6. 数组
1. 数组的创建和打印$arr = array(4, 7, 6, 2, 9);var_dump($arr);// 输出结果为: array(5) { [0]=> int(4) [1]=> int(7) [2]=> int(6) [3]=> int(2) [4]=> int(9) }2. 数组元素的访问
echo $arr[2]; // 输出元素为: 63. 添加数组元素
$arr[] = 10;$arr[] = array('a','b');var_dump($arr);// 输出结果为; array(7) { [0]=> int(4) [1]=> int(7) [2]=> int(6) [3]=> int(2) [4]=> int(9) [5]=> int(10) [6]=> array(2) { [0]=> string(1) "a" [1]=> string(1) "b" } } print_r($arr); // 专门用来输出数组的函数, 输出结果为: Array ( [0] => 4 [1] => 7 [2] => 6 [3] => 2 [4] => 9 [5] => 10 [6] => Array ( [0] => a [1] => b ) )4. 数组的标准创建及操作方式
$arrK=array("user"=>"TOM","password"=>"123456");print_r($arrK); // 输出的结果为: Array ( [user] => TOM [password] => 123456 ) echo $arrK["user"]; // 输出结果为: TOM$arrK["sex"] = "male";$arrK[] = "aaa";print_r($arrK); // 输出结果为: Array ( [user] => TOM [password] => 123456 [sex] => male [0] => aaa )5. 数组的遍历
接4代码
foreach ($arrK as $key => $value) { echo $key."的值是:".$value."<br>";};
输出结果为:
user的值是:TOMpassword的值是:123456sex的值是:male0的值是:aaa6. 删除数组中的某个键值对
假设有这样的一个数组
$arr = array("name" => "Tom", "age" => 22);print_r($arr);// 输出结果为: Array ( [name] => Tom [age] => 22 ) echo json_encode($arr);// 输出结果为: {"name":"Tom","age":22}//这是把数组数据转化成 JSON 格式,方便阅读
那么如果要删除数组中的 name 键值对
unset($arr["name"]);print_r($arr); // 输出结果为: Array ( [age] => 22 )7. 数组的长度
echo count($arr);8. 判断一个值是否在数组内
注意:这里的有没有,指的是值,"1"和1是等价的. 这个函数会有一个布尔返回值.
$arr1 = array(3,6,9,5,33,"10");var_dump(in_array(33, $arr1)); // true9. 二维数组
$arrT = array(array(11,22,33),array(44,55,66));echo $arrT[1][2]; // 打印结果为: 6610. 速生成一个数组
$arrfast1 = range(1,9);
$arrfast2 = range("A","a");
7. 表单
php 文件是如何获取 HTML 提交的信息呢?
HTML:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <form action="form.php" method="post"> <!-- get,注意 post 和 get 在地址栏上的不同 // get: ?key=value&&key=value&&key=value...... post: 把信息打成二进制数打包发送给服务器 --> 用户名: <input type="text" name="user" id="user" value="" /><br> 密__码: <input type="password" name="pass" id="pass" value="" /><br> <input type="submit" value="提交"/> </form> </body></html>
PHP:
<?php// 接收表单信息var_dump($_POST); // $_GET 与 HTML 一致即可?>
当在 HTML 文件中提交 Submit 表格时, 信息就会在 PHP 文件中被打印出来.
8. 函数
1. 函数的使用在 php 中函数的使用和 JS 是基本相同的.
function show() { echo "aaaa";};show();
带参数:
function sayHello($a) { echo "<hr>" . $a;};sayHello("asdhkasdh");
带返回值:
function retFunc() { return "lalalala";}echo retFunc();2. 传引用参数
不加 & 的时候,只是将 $a = 20;的那个20的值赋值给函数,在函数中改了参数值,$a的值不变加了 & 的时候,是将$a = 20;的地址赋给函数的参数,在函数中改了参数值,$a的值变化
function varOp(&$c) { $c =40; echo $c;}$a = 20;varOp($a);echo $a;3. 赋给函数参数默认值
function add($m, $n=9) { echo $m + $n;}add(3, 4); // 3+4add(3); // 3+9ADD(3); // 不区分大小写
##**四. 文件控制**利用 php 可以对文件夹内的文件进行控制操作.首先在同一个目录下,创建一个名为11.txt 的文件.
1. 打开文件
$f = fopen("11.txt", "r");
r 为 mode 形式, 生命了可以对文件进行的处理方式.
代码 | 含义 |
---|---|
"r" | 只读方式打开,将文件指针指向文件头。 |
"r+" | 读写方式打开,将文件指针指向文件头。 |
"w" | 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 |
"w+" | 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 |
"a" | 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 |
"a+" | 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 |
"x" | 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。 |
"x+" | 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。 |
2. 读取文件
读取文件有以下四种方式:
1). 按字符读取$str = fread($f, 3);// 读的什么文件 , 以及一次读多长(3个字节表示一个汉字)
可以获取文件的大小, 全部读取
$str = fread($f, filesize("11.txt"));2). 按行读取
$str = fgets($f); // 这是一行 echo $str;
按行遍历文件
while ($str=fgets($f)) { echo $str."<br>";}3). 把文件放在数组里
$arr = file("11.txt");print_r($arr);4). 整篇读取(速度最快)
$str = file_get_contents("11.txt");echo $str;
3. 写入文件
一行行写,写入的内容会覆盖原内容,如果文件本身不存在,会创建新文件,然后写入.
$f = fopen("11.txt","w");fwrite($f, "Tom\n"); fwrite($f, "Jerry\n");
如果需要整篇写入内容:
file_put_contents("11.txt", " 吃葡萄不吐葡萄皮,不吃葡萄倒吐葡萄皮");
4. 关闭文件
操作完关闭文件是一个好习惯
fclose($f);
5. 拷贝文件
直接将文件拷贝一份放在原文件夹内
copy("11.txt", "22.txt");
6. 重命名文件
rename("22.txt", "33.txt"); // 22.txt 被重命名为33.txt
7. 删除文件
unlink("33.txt"); // 33.txt 被删除
##**五. 目录操作**
首先获取当前目录
$d = opendir(".") // . 表示当前目录, .. 表示上级目录
1. 打开当前目录
1). 依次读取当前目录中的一条内容$str = readdir($d);echo $str;
如果想依次读取目录中的几条内容,就将上面的代码重复输入.
2). 读取并打印此目录下的所有文件将此目录中的内容循环读取, 并依次打印
while ($str = readdir($d)) { echo $str . "<hr>";}3). 关闭文件夹
closedir($d);
2. 获取目录文件的数组
$arr = scandir(".");for ($i=0; $i <count($arr) ; $i++) { echo $arr[$i]."<hr>";}
3. 新建 / 删除 一个目录(显示返回值)
新建:
var_dump(mkdir("test")); // bool(true)
删除:
var_dump(rmdir("test")); // bool(true) 只有空的目录才可以被删除
4. 操作 URL
首先在本机获取一个地址地址的基本信息打印
$path = "http://localhost/PHPSample/dirManage%e7%9b%ae%e5%bd%95%e6%93%8d%e4%bd%9c.php"; // 文件路径
$str = basename($path); // 文件名
$str = dirname($path); // 所在文件夹的名字
$newPath = $str."/login.html"; // 利用 php echo 的特点,我们可以将获取的地址拼接为新的地址进行操作
$arr = pathinfo($path); // 将相关信息一次性打印

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

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.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
