#4 PHP 文件操作

2011-05-03
// 创建目录
if (!is_dir("mydirectory")) {
    mkdir("mydirectory");
} else {
    die("目录已存在");
}
// 创建多级目录
mkdir("path/to/my/directory", 0777, true);

// 删除目录
rmdir("newdir");

// 打开目录
$dir = opendir(".");

// 读目录
while($file = readdir($dir)) {
    echo $file . "<br />";
}

// 读目录 2
$directory = '/path/to/dir';
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($directory,
        RecursiveDirectoryIterator::SKIP_DOTS), // 忽略 . / ..
    RecursiveIteratorIterator::SELF_FIRST); // 深度优先
foreach ($iterator as $item) {
    if ($item->isDir()) {
        echo "目录: " . $item->getPath() . "\n";
    } else {
        echo "文件: " . $item->getPathname() . "\n";
    }
}

// 关闭目录
closedir($dir);

// 打开文件
$myfile = fopen("example.txt", "r");

// 读文件
$data = fread($myfile, filesize("example.txt"));

// 写文件
fwrite($myfile, "This is some text");

fclose($myfile);

// 读文件
$data = file_get_contents("example.txt");

// 写文件
file_put_contents("example.txt", "This is some text");

// 删除文件
unlink("example.txt");

#3 PHP 时间处理

2011-05-02

date/time/strtotime

time()  # 获得当前时间戳
date(fmtStr, timestamp)

strtotime("+1 day")
strtotime("next Thursday")
strtotime("last Thursday")
# 字符串 => 时间戳
php -r 'var_dump(strtotime("today"));' # 零点
php -r 'var_dump(strtotime("2011"));'
php -r 'var_dump(strtotime("2011-12"));'
php -r 'var_dump(strtotime("2011-12-13"));'
php -r 'var_dump(strtotime("2011-12-13 06:00:00"));'

# 时间戳 => 字符串
php -r 'var_dump(date("Y-m-d H:i:s", 0));'

DateTime

  • DateTimeInterface
  • DateTime
  • DateTimeImmutable
  • DateTimeZone
  • DateInterval
  • DatePeriod 实现 Traversable 接口
// DateTimeInterface::ATOM = "Y-m-d\TH:i:sP";
// DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T";
// DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO";
// DateTimeInterface::RFC822 = "D, d M y H:i:s O";
// DateTimeInterface::RFC850 = "l, d-M-y H:i:s T";
// DateTimeInterface::RFC1036 = "D, d M y H:i:s O";
// DateTimeInterface::RFC1123 = "D, d M Y H:i:s O";
// DateTimeInterface::RFC7231 = "D, d M Y H:i:s \G\M\T";
// DateTimeInterface::RFC2822 = "D, d M Y H:i:s O";
// DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP";
// DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP";
// DateTimeInterface::RSS = "D, d M Y H:i:s O";
// DateTimeInterface::W3C = "Y-m-d\TH:i:sP";

$dateTime = new DateTime();

foreach ([
    'ATOM',
    'COOKIE',
    'ISO8601',
    'RFC822',
    'RFC850',
    'RFC1036',
    'RFC1123',
    'RFC2822',
    'RFC3339',
    'RFC3339_EXTENDED',
    'RSS',
    'W3C',
] as $format) {
    eval("print 'DateTimeInterface::$format\t'.\$dateTime->format(DateTimeInterface::$format).\"\n\";");
}
  • public static createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false

  • public format(string $format): string

  • public modify(string $modifier): DateTime|false

  • public add(DateInterval $interval): DateTime
  • public sub(DateInterval $interval): DateTime

  • public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval

  • public getOffset(): int

  • public getTimestamp(): int
  • public setTimestamp(int $timestamp): DateTime
  • public getTimezone(): DateTimeZone|false
  • public setTimezone(DateTimeZone $timezone): DateTime
  • public setDate(int $year, int $month, int $day): DateTime
  • public setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime
  • public setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): DateTime
$d = new DateTime('2011-01-01T15:03:01.012345Z');
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345

$d->modify('+1 month');
$d->add(new DateInterval("P1M"));

$publishDate = DateTime::createFromFormat('m/d/Y', '1/10/2014');
echo $publishDate->getTimestamp();

#1 关于 PHP

2011-03-06

PHP 是互联网领域最主流的后端语言之一,主要用于 Web 开发,优点就是学习门槛低,部署也简单。
因此大量网站都基于 PHP 构建,包括:

  • 博客
  • 论坛
  • CMS
  • 商城
  • 企业官网

典型代表:

  • WordPress
  • Discuz!
  • Drupal

PHP 的本质

“嵌入 HTML 的服务器端脚本语言”

服务器收到请求后:

浏览器请求
    ↓
Web 服务器(Apache)
    ↓
PHP 解释执行
    ↓
生成 HTML
    ↓
返回浏览器

浏览器永远看不到 PHP 源码,只能看到 PHP 执行后的结果。

PHP 文件

  1. PHP 文件通常以 .php 结尾。
  2. PHP 代码写在 php 标签中,例如:

    <?php
    echo "Hello PHP";
    ?>
    

PHP 最核心的特点

  1. 解释执行,不需要编译。
  2. 面向 Web,内置大量 Web 能力:

  3. 表单处理

  4. Cookie
  5. Session
  6. 文件上传
  7. HTTP Header
  8. 数据库访问

  9. HTML 混编,例如:

    <html>
    <body>
    
    <h1>用户列表</h1>
    
    <?php
    echo "<p>Tom</p>";
    echo "<p>Jerry</p>";
    ?>
    
    </body>
    </html>
    

PHP 基础语法

1. 输出

<?php
echo "Hello";
print "World";
?>

2. 变量

PHP 变量以 $ 开头。

<?php

$name = "Tom";
$age = 18;

echo $name;
echo $age;

?>

特点:

  • 不需要声明类型
  • 自动推断类型

3. 数据类型

常见类型:

$string = "abc";
$int = 123;
$float = 3.14;
$bool = true;
$array = array();

PHP 属于弱类型语言。

数组(非常重要)

PHP 的数组功能极强,可以实现列表、字典(HashMap)。

<?php

# 普通数组
$names = array("Tom", "Jerry");
echo $names[0];

# 关联数组
$user = array(
    "name" => "Tom",
    "age" => 18
);
echo $user["name"];
?>

流程控制

if 判断

<?php

$age = 20;

if ($age >= 18) {
    echo "成人";
} else {
    echo "未成年";
}

?>

for 循环

<?php

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

?>

foreach(高频)

<?php

$names = array("Tom", "Jerry");

foreach ($names as $name) {
    echo $name;
}

?>

PHP 中大量数据遍历都依赖 foreach

函数

定义函数:

<?php

function add($a, $b) {
    return $a + $b;
}

echo add(1, 2);

?>

特点:

  • 参数无需声明类型
  • 返回值无需声明类型

表单处理

<form method="post">
  <input name="username" />
  <input type="submit" />
</form>
<?php

$username = $_POST['username'];

echo $username;

?>

PHP 提供超级全局变量:

  • $_GET
  • $_POST
  • $_COOKIE
  • $_SESSION
  • $_FILES

这是 Web 编程基础。

数据库操作(MySQL)

<?php

mysql_connect("localhost", "root", "123456");

$result = mysql_query("SELECT * FROM users");

?>

mysqli
pdo

Session 与 Cookie

Cookie 在浏览器中保存会话数据。

<?php

setcookie("username", "Tom");

?>

Session 在服务器保存会话数据。

<?php

session_start();

$_SESSION['user_id'] = 1;

?>

登录系统大量依赖 Session。

PHP 的运行环境

Linux 下的 LAMP 组合:Linux + Apache + MySQL + PHP
Windows 下反正我都是选择 XAMPP 套件,也是包含 Apache + MySQL + PHP。