0

I'm trying to allow a user to delete a something they uploaded and then get redirected to the homepage. The delete SQL is working fine, the issue is that I can't get it to run header("Location: index.php"). I don't know what could be causing this.

This is my code:

public function deletePage ($session_id, $page_id, $url) {
    //Database Connection
    $db = Database::getInstance();

    //Validate page belongs to current user. 
    if ($this->checkpageOwner($session_id, $page_id)) {
        //Delete page
        $query = $db->getConnection()->prepare("DELETE FROM pages WHERE page_id = :page_id; 
                                                DELETE FROM ratings WHERE page_id = :page_id; 
                                                DELETE FROM comments WHERE page_id = :page_id; 
                                                DELETE FROM views WHERE page_id = :page_id");
        $query->execute(array(
            ':page_id' => $page_id
        ));

        //Redirect
        header("Location: index.php");
    } else {
        //Set error message
        setcookie("sessionPersist", 1);
        $_SESSION['message'] = "You don't own this page.";

        //Redirect
        header("Location: " . $url);
    }
}
Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
  • almost certainly a dupe: http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php – Marc B May 27 '16 at 19:17
  • you can't send headers after sending any other content to the client. it's not clear from the posted code if that's happening, but if you send one character to the browser, then your headers won't work. [error reporting might help](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php) – Jeff Puckett May 27 '16 at 19:18
  • @MarcB I'm not getting any errors. – Joe Scotto May 27 '16 at 19:18
  • are errors enabled? display_errors/error_reporting? – Marc B May 27 '16 at 19:19
  • I was able to fix it by adding `exit()` after `header` – Joe Scotto May 27 '16 at 19:21

2 Answers2

1

I was able to get the code working by adding exit after header

//Redirect
header("Location: index.php");
exit();
Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
-1

At the very top of your php script. Just after the opening tag, add

 ob_start();

Should resolve the header already sent error. It a hack FYI. This function will turn output buffering on.

Mueyiwa Moses Ikomi
  • 1,069
  • 2
  • 12
  • 26