CakeFest 2024: The Official CakePHP Conference

示例

目录

示例 #1 使用 file_get_contents() 从多个来源检索数据

<?php
/* 从 /home/bar 读取本地文件 */
$localfile = file_get_contents("/home/bar/foo.txt");

/* 与上面相同,显式命名 FILE 方案 */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* 使用 HTTP 从 www.example.com 读取远程文件 */
$httpfile = file_get_contents("http://www.example.com/foo.txt");

/* 使用 HTTPS 从 www.example.com 读取远程文件 */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* 使用 FTP 从 ftp.example.com 读取远程文件 */
$ftpfile = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* 使用 FTPS 从 ftp.example.com 读取远程文件 */
$ftpsfile = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>

示例 #2 向 https 服务器发出 POST 请求

<?php
/* 发送 POST 请求到 https://secure.example.com/form_action.php
* 包含了名为 "foo" 和 "bar" 及其虚拟值的表单元素
*/

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!
$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, $data);

$headers = "";
while (
$str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

echo
"\n";

$body = "";
while (!
feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>

示例 #3 将数据写入压缩文件

<?php
/* 创建一个包含任意字符串的压缩文件
* 文件可以使用 compress.zlib 流读取,
* 也可以使用 “gzip -d foo-bar.txt.gz” 从命令行解压缩文件
*/
$fp = fopen("compress.zlib://foo-bar.txt.gz", "wb");
if (!
$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);
?>

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top