ホームページ  >  記事  >  バックエンド開発  >  PHP スクリプトに config.php ファイルをインポートするにはどうすればよいですか?

PHP スクリプトに config.php ファイルをインポートするにはどうすればよいですか?

PHP中文网
PHP中文网オリジナル
2024-10-15 11:53:15371ブラウズ

The include() function in PHP copies the code from the specified file into the file that uses the include statement. It directs the preprocessor to insert the content of the specified file into the current program. The name of the file to be included is written in double quotes. It is good practice to write basic database and user details in a file named “config.php”. You can also include connection-building statements in the “config.php” file to automatically establish a database connection for every page that includes “config.php”. Including files allows you to create a template of code that can be reused by multiple pages of a website.

屏幕截图 2024-10-15 104902.png

Syntax

<?php     include(&#39;config.php&#39;);
?>

Example 1: This shows the creation and including of the config.php file.

Code 1: Create a PHP file and save it with the name ‘config.php’.

<?php $host = "localhost";
$database = "GeeksForGeeks";
$username = "admin";
$password = "";
?>

Code 2: Create a PHP file and save it with the name ‘try.php’ in the same folder as ‘config.php’ file. Copy the below code to include the ‘config.php’ file and get a print the name of the database and username.

<?php include "config.php";
echo "Host: " . $host . " Database: " . $database;
?>


Output:PHP スクリプトに config.php ファイルをインポートするにはどうすればよいですか?

Example 2: If you want to save the contents of the config.php file into a variable, then the following code does that work.

Code 1: Simply return the contents of the ‘config.php’ file.

<?php return [
    "host" => "localhost2",
    "database" => "GeeksForGeeks2",
    "username" => "admin",
    "password" => "",];
?>

Code 2: Accept the returning array in a variable.

<?php $details = include "config.php";
echo "Host: " . $details["host"] . 
      " Database: " . $details["database"];
?>


Output:PHP スクリプトに config.php ファイルをインポートするにはどうすればよいですか?

Want to be a Software Developer or a Working Professional looking to enhance your Software Development Skills? Then, master the concepts of Full-Stack Development. Our Full Stack Development - React and Node.js Course will help you achieve this quickly. Learn everything from Front-End to Back-End Development with hands-on Projects and real-world examples. This course enables you to build scalable, efficient, dynamic web applications that stand out. Ready to become an expert in Full-Stack? Enroll Now and Start Creating the Future!

以上がPHP スクリプトに config.php ファイルをインポートするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。