-3

Possible Duplicate:
Headers already sent by PHP

I have a function to create a file. If successful, I want it to redirect the user to X page.. in this case 1.php.... but it's not working. The PHP script is on the top... so technicaly speaking it should work

It works if i put the header () inside the createFile () function but not if i put it inside the if statement....

<?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>
Community
  • 1
  • 1
Jonathan Thurft
  • 4,087
  • 7
  • 47
  • 78

2 Answers2

7

It is not working because you have already output headers and HTML to the browser, by having that HTML content above your header() function call.

You need to either output your HTML into an output buffer, or move you header call to near the beginning of your script before any output is sent to the browser.

It seems to me that there is no reason you can't simply move your initial HTML content down in your script to where it is after the bulk of your PHP code.

<?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>
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • I moved the PHP all the way up, but is still not working – Jonathan Thurft Aug 01 '12 at 15:40
  • @JonathanThurft See the code in the edits to my original answer. – Mike Brant Aug 01 '12 at 15:43
  • @Mike Brant Do you have any space or other "invisible" symbols in this file or dbconfig.php? – Andrey Vorobyev Aug 01 '12 at 15:44
  • @Mike I copied and pasted that and It doesnt redirect for some reason :S – Jonathan Thurft Aug 01 '12 at 15:44
  • @JonathanThurft It sounds like there may be some other issues with your script then to where you are not getting to the part of the script execution. Also is this script included from another script (i.e. is there anything else that could have produced output to the browser)? – Mike Brant Aug 01 '12 at 15:46
  • @Mike, There is only 1 page of scrip, there is the config.php file that is created but u can see there what it has inside :P... In theory it should work... I dont know why is not working – Jonathan Thurft Aug 01 '12 at 15:47
  • @JonathanThurft THere are a number of different conditionals in there. That could prevent the running script from ever getting the header call. You should verify these are working as expected (i.e. is DB connection made, is config file writable, etc.) – Mike Brant Aug 01 '12 at 15:50
  • @MikeBrant Everything has been tested and works perfect. I tried it now putting the header in the createFile () function and it redirects if is inside there... but somehow is doesnt work in the IF statement inside the code :S. Ok now it works... but i had to write `return true;` at the end of the function – Jonathan Thurft Aug 01 '12 at 15:54
  • @JonathanThurft I don't think you are getting to the righ place in your conditional logic. Look at at you first header call for example. It is supposed to do the redirect if the createFile function returns a value of true, yet your createFile function doesn't return any value at all. This conditional will ALWAYS fail. Sorry just saw your last comment that you found the problem. – Mike Brant Aug 01 '12 at 15:57
2

Redirect must happens before you send any data to client

Andrey Vorobyev
  • 896
  • 1
  • 10
  • 37