PHP の file_put_contents

WBOY
リリース: 2024-08-29 12:52:22
オリジナル
679 人が閲覧しました

file_put_contents は、指定されたデータ文字列をファイルに書き込む PHP 関数です。該当するファイルが存在しない場合は作成されます。逆に、ファイルが存在する場合、その内容は指定されたデータで上書きされます。この関数は実装が簡単で、ファイル名とデータをパラメータとして書き込むだけです。さらに、URL を指定するか、フラグを使用して関数の動作を変更することにより、リモート ファイルにデータを書き込むことができます。 file_put_contents は、フォーム データの保存、ログ ファイルの生成、書き込まれたレコードの作成によるデバッグなど、さまざまな目的に役立つツールです。

PHP の file_put_contents

広告 このカテゴリーの人気コース コンテンツ マーケティングの習得: 成功のための戦略 - 専門分野 | 4コースシリーズ

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

構文とパラメータ

file_put_contents 関数の構文とパラメーターは、関数を正しく使用し動作させるために非常に重要です。構文は、関数の構造とパラメーターの必要な順序を定義します。パラメーター自体により、ターゲット ファイル、書き込まれるデータ、および関数の動作を変更するオプションを指定できます。 file_put_contents 関数の構文とパラメーターを明確に理解することは、関数を正確かつ効果的に使用するために重要です。

構文:

file_put_contents(filename, data, [flags, context]);
ログイン後にコピー

パラメータ:

パラメータ 説明
$filename (必須) 「$filename」は、データが書き込まれるファイルの名前と場所を指定する file_put_contents 関数のパラメーターです。 $filename パラメータは必須であり、データが書き込まれるターゲット ファイルを指定します。
$data (必須) $data は、PHP の file_put_contents() 関数を使用してファイルに書き込まれるコンテンツを保持する変数です。文字列、配列、またはその他の PHP データ型を使用できます。データはファイルに書き込まれる前に文字列に変換されます。 「$data」パラメータで渡されたデータは、「$filename」で指定されたファイルに書き込まれます。
$flags (オプション) $flags は、ファイル書き込み操作の実行方法を制御する特定のフラグを設定する、PHP の file_put_contents() のオプションのパラメーターです。これを使用して、ファイルへの書き込みに関して file_put_contents() 関数の動作を変更できます。 $flags パラメータは、書き込みモードを制御する値として 1 つ以上の事前定義された定数を受け取ります。一般的に使用される定数には次のようなものがあります:

FILE_USE_INCLUDE_PATH – このフラグを使用すると、include_path 内のファイルを検索できます。現在のディレクトリにファイルが見つからない場合は、含まれているパスが検索されます。

FILE_APPEND – このフラグは、ファイルを追加モードで開き、ファイルの末尾にデータを書き込みます。ファイルが存在しない場合は作成されます。

LOCK_EX – このフラグにより​​、ファイルは排他的書き込みアクセス用にロックされます。これは、ファイルのロックが解除されるまで、他のプロセスはそのファイルに書き込むことができないことを意味します。

FILE_TEXT – このフラグはファイル モードをテキストに設定します。これはテキスト ファイルに使用され、行末はシステムのデフォルトに変換されます。

FILE_BINARY – このフラグはファイル モードをバイナリに設定します。これはバイナリ ファイルに使用され、行末は変換されません。

The default value of the $flags parameter in the file_put_contents function is 0.

$context (optional) The context parameter in the file_put_contents function in PHP allows the user to specify a set of options that modify the behavior of the function when it writes data to a file or a remote server. The context is specified as an associative array that defines options for a stream, such as headers to be sent along with a request, timeout values, encryption method, etc. It allows the user to control the way data is sent and received through a stream in PHP.
$mode (optional) The $mode parameter is an optional parameter and is not typically used in the file_put_contents function. $mode is a parameter in the file_put_contents function in PHP that specifies the access mode when opening the file. The value of $mode determines what kind of access the function has to the file, such as read-only or write-only access. By default, file_put_contents opens the file with write-only access. This means that the function can only write data to the file and cannot read the existing data in the file.

Examples

Here an array of data is converted to a JSON string and written to a remote URL using an HTTP POST request. The stream_context_create function is used to create a stream context resource that specifies the HTTP method, header information, and timeout for the request. The file_put_contents function is then used to send the JSON data to the specified URL using the specified context. The function then returns the number of bytes written to the file, or false if there is any error. The response is checked to determine if the data was sent successfully, and a message is displayed accordingly.

Example #1

Code:

<?php
$data = array("name" => "John Doe", "email" => "[email protected]", "phone" => "555-555-1212");
$json = json_encode($data);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/json\r\n".
"Accept: application/json\r\n".
"User-Agent: My PHP Script",
'content' => $json,
'timeout' => 60
)
));
$response = file_put_contents("https://www.example.com/api/create_user", $json, 0, $context);
if ($response === false) {
echo "Error: Could not send data to remote server.";
} else {
echo "Data successfully sent to remote server. Response: $response";
}
?>
ログイン後にコピー

Output:

The output in the above example would be a message indicating the success or failure of the data being sent to the remote server. If the data is sent successfully, the output would be:

PHP の file_put_contents

If an error occurs, the output would be:

PHP の file_put_contents

Example #2

Code:

<?php
$file = "https://cdn.educba.com/var/www/html/students.txt";
$data = "1, Alice, 23, History, 3.7\n2, Bob, 25, Mathematics, 3.9\n3, Charlie, 22, English, 3.5\n4, Dave, 24, Computer Science, 4.0\n";
// Writing data to the file
file_put_contents($file, $data);
// Check if the file was written successfully
if (file_exists($file)) {
echo "Data was successfully written to the file.";
} else {
echo "An error occurred while writing data to the file.";
}
?>
ログイン後にコピー

Output:

The output for the code would depend on the server’s response to the request. If the request was successful, the output would be:

PHP の file_put_contents

If the request was unsuccessful, the output would be:

PHP の file_put_contents

Conclusion

file_put_contents is a useful PHP function for writing data to a file. It has several parameters that allow you to control the behavior of the function, such as the file path, data to be written, and the mode in which the file is opened. With the help of the optional stream context, file_put_contents can even write data to remote servers. This function is a simple and efficient way to write data to a file, making it a popular choice among PHP developers.

Recommended Article

In this article, you learned about file_put_contents in PHP. To know more about the topic, you can refer to these articles.

  1. PHP 7 MySQL
  2. PHP 7 mysql_connect 
  3. PHP Timestamp
  4. PHP urlencode

以上がPHP の file_put_contentsの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
php
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!