PHP fwrite();创建额外字符

时间:2014-07-30 06:53:49

标签: php mysql

我正在尝试创建一个PHP脚本,通过$_POST检索变量,并使用所述变量修改另一个PHP文件。但是,无论何时运行脚本,都要复制要修改的文件的最后12个字符并将其连接到文件的末尾。

我想修改的文件名为 database_info.php ,如下所示;

<?php
/**
 * These are the database login details
 */  
define("HOST", "{HOST}");     // The host you want to connect to.
define("USER", "{USER}");    // The database username. 
define("PASSWORD", "{PASSWORD}");    // The database password. 
define("DATABASE", "{DATABASE}");    // The database name.

ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);

这是我修改database_info.php的PHP脚本

<?php

$host = $_POST['DBhost'];
$name = $_POST['DBname'];
$user = $_POST['DBuser'];
$pass = $_POST['DBpassword'];

echo "<p> Hostname: ", $host ,"</p></br>";
echo "<p> Database: ",$name, "</p></br>";
echo "<p> User: ", $user, "</p></br>";
echo "<p> User: ", $pass , "</p></br>";

$search = array('{HOST}','{USER}','{PASSWORD}','{DATABASE}');
$replace = array($host,  $user, $pass, $name);
$file = file_get_contents("database_info.php");
$fh = fopen("database_info.php", 'c');
$file = str_replace($search, $replace, $file);
fwrite($fh, $file);
fclose($fh);

include 'functions.php';
$con = mysqli_connect(HOST, USER, PASSWORD, DATABASE); //create connection, store to variable "con"

// Check connection
if (mysqli_connect_errno($con)) 
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create a table
$sql="CREATE TABLE canvas(name CHAR(30),content CHAR(30))";

// Check if table was created
if (mysqli_query($con,$sql)) 
{
    echo "Table created successfully";
} 

else 
{
    echo "Error creating table: " . mysqli_error($con);
}
?>

使用$_POST变量

运行PHP脚本时
$host = localhost;
$name = CMS;
$user = root;
$pass = root;

database_info.php变为

<?php
/**
 * These are the database login details
 */  
define("HOST", "localhost");     // The host you want to connect to.
define("USER", "root");    // The database username. 
define("PASSWORD", "root");    // The database password. 
define("DATABASE", "CMS");    // The database name.

ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);| E_STRICT);

问题出在最后一行,error_reporting(E_ALL | E_STRICT);| E_STRICT);最后12个字符(| E_STRICT);)已连接到结尾导致语法错误。我可以通过在文件的末尾添加12个额外的注释字符来解决问题,因此它只复制注释的字符,但这是一个不优雅的解决方案,并没有解决问题。

我注意到添加到database_info.php的变量使它比原来的短12个字符,这是问题吗?我认为问题源于fwrite(),但我并不完全确定。有谁知道为什么我的脚本会添加这些额外的字符?

1 个答案:

答案 0 :(得分:1)

您的问题在声明fopen()

如果你阅读了fopen的文档,你正在使用参数c来打开文件,它不会截断现有文件,只是将文件指针放在文件的开头。现在,由于您的POST值与您的{..}值相差12个字符,因此不会覆盖&#34;#34;覆盖&#34;最后12个字符,但只是用新字符串替换所有字符。

简单的解决方案是始终在w使用fopen。所以

$fh = fopen("database_info.php", 'c');
$file = file_get_contents("database_info.php");

将成为

$file = file_get_contents("database_info.php");
$fh = fopen("database_info.php", 'w');

如果在打开文件后使用file_get_contents进行写入,则会得到空文件以供阅读