PHP 的基本操作
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. 变量
- 变量的声明形式为:输出变量的值,可以使用: echo 进行输出查询.同时,变量声明时允许互相进行嵌套, 如:
$a = 10;$b = "aaa";
Copy after login
$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); //显示为5
如判断 "bc" 在 "aabBcbc" 中出现的位置
echo strpos("aabBcbc", "bc"); // 输出为 5
如果不区分大小写
echo stripos("aabBcbc", "bc"); // 输出为 3
_*概念 :*_ 对字符串做操作时,是否代表字符串结束的"\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.com
这里我们使用两种方法:
1) substr(要做处理的字符串, 从第几个开始截取, 截取几个字符)echo substr("hello world", 3, 4); // 输出为: lo w
echo strstr("hello world", "lo"); // 输出结果为: lo world
$strT = " hello world!!! "; echo trim($strT);// 输出结果为: hello world!!!
小转大
$strA = "FGJHGkbadkahd";echo strtolower($strA); // 输出结果为: fgjhgkbadkahdecho strtoupper($strA); // 输出结果为: FGJHGKBADKAHD
echo strrev("hello PHP"); // 输出结果为: PHP olleh
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) }
echo $arr[2]; // 输出元素为: 6
$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 ) )
$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 )
接4代码
foreach ($arrK as $key => $value) { echo $key."的值是:".$value."<br>";};
输出结果为:
user的值是:TOMpassword的值是:123456sex的值是:male0的值是:aaa
假设有这样的一个数组
$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 )
echo count($arr);
注意:这里的有没有,指的是值,"1"和1是等价的. 这个函数会有一个布尔返回值.
$arr1 = array(3,6,9,5,33,"10");var_dump(in_array(33, $arr1)); // true
$arrT = array(array(11,22,33),array(44,55,66));echo $arrT[1][2]; // 打印结果为: 66
$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();
不加 & 的时候,只是将 $a = 20;的那个20的值赋值给函数,在函数中改了参数值,$a的值不变加了 & 的时候,是将$a = 20;的地址赋给函数的参数,在函数中改了参数值,$a的值变化
function varOp(&$c) { $c =40; echo $c;}$a = 20;varOp($a);echo $a;
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"));
$str = fgets($f); // 这是一行 echo $str;
按行遍历文件
while ($str=fgets($f)) { echo $str."<br>";}
$arr = file("11.txt");print_r($arr);
$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>";}
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); // 将相关信息一次性打印

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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 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.

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

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
