可能重复:
PHP 已发送的标头
我有一个创建文件的功能。如果成功,我希望它将用户重定向到 X 页面.. 在这种情况下为 1.php.... 但它不起作用。PHP 脚本在顶部......所以从技术上讲它应该可以工作
如果我把它放在header ()
createFile () 函数里面,它就可以工作,但如果我把它放在 if 语句里面,它就不行....
<?php
//DB Config File
$dbFile = 'dbconfig.php';
function createfile ($dbFile) {
//Creates File and populates it.
$fOpen = fopen($dbFile, 'w');
$fString .= "<?php\n";
$fString .= "// Database Constants\n";
$fString .= "define(\"DB_SERVER\", \"$server\");\n";
$fString .= "define(\"DB_USER\", \"$username\");\n";
$fString .= "define(\"DB_PASS\", \"$password\");\n";
$fString .= "define(\"DB_NAME\", \"$dbname\");\n";
$fString .= "?>";
fwrite($fOpen, $fString);
fclose($fOpen);
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$server = $_POST['server'];
$dbname = $_POST['dbname'];
try {
$db = new PDO ('mysql:host=' .$server.';dbname='.$dbname,$username,$password);
if ($db) { //if succesful at connecting to the DB
if (file_exists($dbFile)){
if (is_readable($dbFile) && is_writable($dbFile)){
//Creates File, populates it and redirects the user
if (createfile($dbFile)) {
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = '1.php';
header("Location: http://$host$uri/$extra");
exit ();
}
} else {
$msg = "2The file {$dbFile} cannot be accessed. Please configure the file manualy or grant Write and Read permission."; }
} else {
//Creates File, populates it and redirects the user
if (createfile($dbFile)) {
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = '1.php';
header("Location: http://$host$uri/$extra");
exit ();
}
}
}
} catch (PDOException $e) { //Catchs error if can't connect to the db.
$msg = 'Connection failed: ' . $e->getMessage();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="iForm" method="post" action="install.php">
<label id="username" name="username">Username</label>
<input id="username" name="username"/>
<label id="password" name="password">Password</label>
<input id="password" name="password" />
<label id="server" name="server">Server</label>
<input id="server" name="server"/>
<label id="dbName" name="dbname">dbName</label>
<input id="dbName" name="dbname"/>
<input type="submit" name="submit" value="submit" />
</form>
<p id="error"><?php echo $msg ?></p>
</body>
</html>