我要做的是制作一个安装文件,用户输入数据库,用户名,密码和主机作为php系统安装的第一步。
答案 0 :(得分:15)
与创建其他文件相同,只需添加扩展程序.php
$fp=fopen('filename.php','w');
fwrite($fp, 'data to be written');
fclose($fp);
答案 1 :(得分:10)
这很容易。只需像其他人提到的那样用php扩展名编写一个文件。
但我宁愿为配置数据写一个ini文件,稍后用parse_ini_file
加载它们。
更新:以下是一个示例:
<?php
$config = array(
"database" => "test",
"user" => "testUser"
);
function writeConfig( $filename, $config ) {
$fh = fopen($filename, "w");
if (!is_resource($fh)) {
return false;
}
foreach ($config as $key => $value) {
fwrite($fh, sprintf("%s = %s\n", $key, $value));
}
fclose($fh);
return true;
}
function readConfig( $filename ) {
return parse_ini_file($filename, false, INI_SCANNER_NORMAL);
}
var_dump(writeConfig("test.ini", $config));
var_dump(readConfig("test.ini"));
答案 2 :(得分:0)
我知道这是一个老话题,但我有一个解决方案:
installer.php:
<?php
class Installer {
public $options;
public function __construct( $arr=array() ){
$this->options = $arr;
}
public function put( $key, $value ){
$this->options[$key] = $value;
}
public function convertOptions(){
$arr = $this->options;
$data = "<?php\n\n";
foreach( $arr as $key => $value ){
$data .= "define( '" . $key . "', '" . $value . "' );";
$data .= "\n\n";
}
return $data;
}
public function install( $filename, $dir='' ){
if( file_put_contents( $dir . $filename, $this->convertOptions() ) ){
return true;
}
return false;
}
}
anotherFile.php:
require_once installer.php;
$installer = new Installer();
$installer->put( 'DB_NAME', 'example' );
$installer->put( 'DB_USER', 'root' );
$installer->put( 'DB_PASS', '' );
$installer->install( 'config.php' );
创建config.php:
<?php
define( 'DB_NAME', 'example' );
define( 'DB_USER', 'root' );
define( 'DB_PASS', '' );