例
目次
例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%22);/* HTTPS を利用し、www.example.com にあるリモートのファイルを読み出す */$httpsfile = file_get_contents("https://www.example.com/foo.txt%22);/* FTP を利用し、ftp.example.com にあるリモートのファイルを読み出す */$ftpfile = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt%22);/* FTPS を利用し、ftp.example.com にあるリモートのファイルを読み出す */$ftpsfile = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt%22);?>
例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("Fooの値") . "&bar=" . urlencode("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);?>