I’m moving a website to cPanel hosting and from php 5.1 to 5.4. The only thing that is not working with the move is the return to the index.php page after the MySql data insertion. The data is inserted OK, but I get a blank page instead of the index.php page refreshing.
I have studied the forum and and using ideas I observed: removed spaces in the php code; moved the header(Location:index.php) around in the script; took a space out between Location: and index.php, but can’t get the index.php page to display after the insertion. The url is in the browser line and if I click on it, the page is refreshed. This happened automatically in the past.
Here is the code:
<?php
function renderForm($mscdate, $mscname, $mscaffirm, $mscstatus, $error)
{
?>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script type="text/javascript">
$(function() {
$('#datepicker').datepicker({dateFormat: 'MM d, yy', altField: '#dbDate', altFormat: 'yy-mm-dd'});
});
</script>
<?php
}
include('connect to database');
if (isset($_POST['submit']))
{
$mscdate = mysqli_real_escape_string(htmlspecialchars($_POST['mscdate']));
$mscname = mysqli_real_escape_string(htmlspecialchars($_POST['mscname']));
$mscaffirm = mysqli_real_escape_string(htmlspecialchars($_POST['mscaffirm']));
$mscstatus = mysqli_real_escape_string(htmlspecialchars($_POST['mscstatus']));
if ($mscdate == '' || $mscname == '' || $mscaffirm == '')
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($mscdate, $mscname, $mscaffirm, $mscstatus, $error);
} else {
mysqli_query("INSERT mscrides SET mscdate='$mscdate', mscname='$mscname', mscaffirm='$mscaffirm', mscstatus='$mscstatus'")
or die(mysqli_error());
header("Location:index.php");
}
}else { // if the form hasn't been submitted, display the form
renderForm('','','','','');
}
?>
2
Answers
Try Adding
ob_start()
at the top of your code.You are sending a
Location
HTTP redirect to the browser without also telling PHP to stop execution, which would usually be done withexit()
. In PHP applications, that will usually give rise to a race condition that depends on a wide array of factors, mainly internet/network speed, as to whether the redirect works.The race specifically is which of these occurs first, after the
Location
header:Having an explicit
exit()
is a good practice even if you think your script will end naturally, in case you have an append handler or shutdown handler active.