Casey
Casey

Reputation: 1981

using session_start with header redirect

User fills out a form on page 1. The form submits to page 2 with POST. page 2 makes the database insert but needs to insert the user id that is stored in a session variable so I need to do a session start that to get that session variable but that prevents me from using a header redirect at the end to stop re-submissions. I don't want to set the user id to a hidden input on page 1 because that would be fairly easy to spoof. I'm obviously doing something not in accord with best practices, what should I be doing?

    <?php
@session_start();
require_once '../Classes/Communication.php';
require_once '../Classes/Communication_db.php';
$noteDate=$_POST["noteDate"];
$noteContact = $_POST["noteContact"];
$note= $_POST["note"];
$custID = $_POST["custID"];

$comm = new Communication();
$comm->setCustomerID($custID);
$comm->setCommunicationDate(date("Y-m-d", strtotime($noteDate)));
$comm->setCustomerContactID($noteContact);
$comm->setNotes($note);
$comm->setUserID($_SESSION["userID"]);

Communication_db::saveCommunication($comm);

header("Location: ./index.php?action=newCustomer",303);

?>

Upvotes: 1

Views: 1659

Answers (2)

xception
xception

Reputation: 4297

session_start does not prevent you from setting any headers, however spitting out any output before the header declaration will, even if that's just a php warning or notice. Get rid of the space @Ray noticed and also fix any other things that might generate any kind of output before the header line.

Upvotes: 1

Ray
Ray

Reputation: 41508

Get rid of the whitespace before your <?php tag. That whitespace gets sent out and you can't then call header().

Also, you could be calling session_start in an earlier place (or a library is doing this). You can only call it once. Try this:

if (!isset($_SESSION)) {
   session_start();
}

Upvotes: 6

Related Questions