PHP Conference Japan 2024

範例

目錄

範例 #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
/* 向 https://secure.example.com/form_action.php 發送 POST 請求
* 包含名為 "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("無法建立檔案。");

fwrite($fp, "這是一個測試。\n");

fclose($fp);
?>

新增註解

使用者貢獻的註解

此頁面沒有使用者貢獻的註解。
To Top