Friday 16 June 2017

PHP header() will not redirect issue



I'm having an issue with the header("Location: index.php?action=messagesent") it will not redirect after The user presses submit and the php is ran. Normally it will redirect but for some reason it's not working, It just reloads the page after they hit submit. But it does echo "Message Sent" right under the header code. Any ideas on why it is not redirecting? Thank You in advance.




Heres my Code:



        












$servername = "localhost";
$username = "myusername";
$password = 'password';
$dbname = "database";

try {


$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO messaging
(fromid, toid, message, tousername,
fromusername,userprofile, sentdate, messagebefore)
VALUES (:fromid, :toid, :message, :tousername,

:fromusername, :userprofile, :sentdate, :messagebefore)");

// insert a row
$toid = $fromid;
$fromid = $_SESSION['user']['id'];
$messagebefore = $message;
$message = $_POST['message'];
$tousername = $row['fromusername'];
$fromusername = $_SESSION['user']['username'];
$userprofile = $row['userprofile'];

$sentdate = $date = date('H:i, jS F Y');

//Bind Inputs
$stmt->bindParam(':fromid', $fromid);
$stmt->bindParam(':toid', $toid);
$stmt->bindParam(':message', $message);
$stmt->bindParam(':tousername', $tousername);
$stmt->bindParam(':fromusername', $fromusername);
$stmt->bindParam(':userprofile', $userprofile);
$stmt->bindParam(':sentdate', $sentdate);

$stmt->bindParam(':messagebefore', $messagebefore);

$stmt->execute();

echo "Message Sent. ";
header("Location: inbox.php?action=messagesent");
}
catch(PDOException $e){
}
$conn = null;

?>

Answer



A header(Location: ...) will only work if you have not already sent output to the browser.



Earlier in your script you output the form, hence header() fails with an error message.



If you look in your error log, you will see the error message.



Add error reporting to the

top of your file(s) while testing right after your opening PHP tag for example



error_reporting(E_ALL); 
ini_set('display_errors', 1);


Now you will see the errors on the browser page.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...