>  기사  >  백엔드 개발  >  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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.