This is my contact-form-handler.php file. After clicking submit button, I want an alert in PHP. I am receiving Mail successfully and redirect to my main page but without an alert message. How can I use the alert box in PHP?
My form is working fine, but this time I stucked in this simple task.
<?php
if(isset($_POST['submit'])){
//$companyMail = 'enesh#gmail.com';
$to = "eneshpal#gmail.com"; // this is your Email address
$customerMail = $_POST['formEmail']; // this is the sender's Email address
$first_name = $_POST['formFirstName'];
$last_name = $_POST['formLastName'];
$phone = $_POST['formPhone'];
$text = $_POST['formText'];
/* foreach($_POST['project_type'] as $project_type_value){} */
$projectType = implode(', ',$_POST['project_type']);
$scopeProject = implode(', ',$_POST['scope_project']);
$project_type_Str = 'Project Type : '.$projectType;
$scope_project_Str = 'Scope of Project : '.$scopeProject;
$subject = "Form Submission";
$message = "Hi, \n\n";
$message .= "First Name: ".$first_name . "\nLast Name: " . $last_name . " \nEmail: " . $customerMail . " \nPhone : " . $phone . "\nDescription: " . $text . "\n";
$message .= $project_type_Str."\n";
$message .= $scope_project_Str;
//$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
//$headers = "From:" . $companyMail;
//$headers2 = "From:" . $to;
if(mail($to,$subject,$message)){
//echo 'Mail Sent';
//$message = "Thanks, We Will Contact you Shortly";
//echo "<script type='text/javascript'>alert('$message');</script>";
echo "<script>alert('Thanks, We Will Contact you Shortly');</script>";
header('Location:get_estimation.php');
}else{
echo 'Mail Not Sent';
}
//mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
/*if( "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.")
else die; */
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
In your case it would be better to redirect the user
header('Location:get_estimation.php?success=true');
and pass a GET-parameter.
When the GET-Parameter is set it will display what you want on your get_estimation.php-page
There are many problems with your script, but to answer your key question... you are echo'ing out the javascript code for an alert(), which will in turn prevent your php header('Location:get_estimation.php'); from executing because there has already been output sent to the browser before header was called. See here for more info.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
As per your comment above...
Yes Sir I want just just wish to render a success message after the form has been submitted?
To give you an example of how to achieve what you need for this...
<?php
if (!empty($_GET['success'])) {
echo 'Thanks, we will contact you shortly';
exit;
}
if (isset($_POST['submit'])) {
$to = "eneshpal#gmail.com";
$customerMail = $_POST['formEmail'];
$first_name = $_POST['formFirstName'];
$last_name = $_POST['formLastName'];
$phone = $_POST['formPhone'];
$text = $_POST['formText'];
$projectType = implode(', ', $_POST['project_type']);
$scopeProject = implode(', ', $_POST['scope_project']);
$project_type_Str = 'Project Type : ' . $projectType;
$scope_project_Str = 'Scope of Project : ' . $scopeProject;
$subject = "Form Submission";
$message = "Hi, \n\n";
$message .= "First Name: " . $first_name . "\nLast Name: " . $last_name . " \nEmail: " . $customerMail . " \nPhone : " . $phone . "\nDescription: " . $text . "\n";
$message .= $project_type_Str . "\n";
$message .= $scope_project_Str;
if (mail($to, $subject, $message)) {
header('Location: get_estimation.php?success=1');
exit;
} else {
echo 'Mail Not Sent';
exit;
}
}
To explain, you should not be using a browser-native javascript alert rendered from php to pop-up and notify the user of a form submission success, especially immediately after a redirect. It's just a bad user experience, it hijacks the browser window until they click ok on it and you cannot really style native alert windows etc.
Instead you should redirect with a success GET variable after the mail is sent successfully (back to the original page, presuming that is get_estimation.php in my example - but you can redirect elsewhere to another script). Then you can detect the presence of this variable in the script redirected to and show an appropriate message etc.
echo "Thank You,will contact you soon";
echo "<script>setTimeout(\"location.href = 'get_estimation.php';\",3000); </script>";
Related
I've tried so many variables and been at this for hours and hours for something I know will be so simple haha, but I cannot get this to work... All I need to do, is... when the form is completed I have it redirected to a page instead of the normal error message.
Your help is appreciated.
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ? $_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$phone) $errors[count($errors)] = 'Please enter your contact number.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'me#myemail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Phone: ' . $phone . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result)
echo 'Thank you! We have received your message.';
else
echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result)
return 1;
else
return 0;
}
So I submit my form and and every time I click ctrl-r it refreshes the page without alerting me it will resubmit the form. Every time I click the reload button on browser it asks me that it will reload but I already submitted the form so now I am getting a new submit every time and creating a new item in my sqlDB. I refresh and I do not know what I have to do to automatically refresh the page to where it wont save the form resubmit and is like a new page again.
where the //end else is at is where I have tried adding a header(Location:) but I get an error. I posted the error more to the bottom of the question.
footer.php
<?php
if(isset($_POST['submit-story'])){
$answer = $_POST['human-story'];
if (!ctype_digit($answer) == 8) {
echo "Cannot store event. wrong answer";
die();
} else {
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 1000000; // size in KB
$allowed_extensions = array("jpg","jpeg","gif","bmp","mp4", "mov");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors = "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors = "\n The uploaded file is not supported file type. ".
"Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder
$upload_folder = 'uploads/';
$to = "example#gmail.com"; // this is your Email address
$first_name = filter_var($_POST['first_name']. $schoolOfficialShortName, FILTER_SANITIZE_STRING);
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$eventDate = filter_var($_POST['eventDate'],FILTER_SANITIZE_STRING);
$eventLocation = filter_var($_POST['eventLocation'],FILTER_SANITIZE_STRING);
$subject = "blah-" . $schoolOfficialShortName . "Event";
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$message = $first_name . " wrote the following:" . "\n\n" . $title ."<br>". $story;
$headers = "From: $first_name";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
$content = '';
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if($tmp_path) {
$filename = $_FILES["uploaded_file"]["name"];
$path_of_uploaded_file = $upload_folder . $filename;
if(!copy($tmp_path, $path_of_uploaded_file))
{
$errors = '\n error while copying the uploaded file';
}
$file_size = filesize($path_of_uploaded_file);
$handle = fopen($path_of_uploaded_file, "rb");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
}
// if attachment has successfully encoded
if ($content) {
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$headers2 = "From:" . $to;
mail($to, $subject, $message, $headers);
//send items to S3 bucket
move_uploaded_file($upload_folder, $filename);
//store image to s3 bucket
try {
$result = $s3->putObject([
'Bucket' => $config['s3']['bucket'],
'Key' => "uploads/{$name_of_uploaded_file}",
'Body' => fopen($path_of_uploaded_file, 'rb'),
'ACL' => 'public-read'
]);
$results = $result['ObjectURL'];
if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
//inserts in pending table
$sql = "INSERT INTO items (photo,title,eventDate,description,name,pLike,pDislike,address) VALUES ( :photo, :title, :eventDate, :description, :name, :pLike, :pDislike, :address)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':photo', $results);
$stmt->bindParam(':description', $story);
$stmt->bindParam(':eventDate', $eventDate);
$stmt->bindParam(':address', $eventLocation);
$stmt->bindParam(':name', $first_name);
$stmt->bindValue(':pLike', 0, PDO::PARAM_INT);
$stmt->bindValue(':pDislike', 0, PDO::PARAM_INT);
$stmt->execute();
}else {
die("<h1>There was an error. Please go back and retry.</h1>");
}
//remove the pending file in uploads folder
unlink($path_of_uploaded_file);
} catch(PDOException $e){
echo 'error in query: '.$e->getMessage();
}
};// end else
};// end isset final
?>
I have tried adding a header(Location: index.php) But i get a weird error saying
Cannot modify header information - headers already sent by (output started at /Users/mine/Documents/www/website/schools/inc/header.php:67) in /Users/mine/Documents/www/website/schools/inc/footer.php on line 127
Unset $_POST variable after proccessing data in your footer.php
your header already send problem : It means some text was already outputted. Place your header() on top of your script. Or look at the ob_start and ob_end_clean() functions.
You can not use header() once text has been output to the browser. As your header file include presumably outputs HTML, header() cannot be used.
You can solve this in flowing ways:
Move the if statement above the header file include.
ob_start() at the top of the script to buffer the output.
I am trying to make a plugin which lists all users from a database with for each user a button to send an email to them. So the only way I can get with their username their email adress is to use the $POST which is given after the button is clicked. With their username I can search the db table to retreive the email. The problem here is that the page will reload and the function wp_mail is called before the pluggable.php has loaded its functions.
Here is the post:
if ($_POST) {
sendEmail(current(array_keys($_POST)));
echo "<script type='text/javascript'>alert('Email is sent!')</script>";
}
And here is the function:
function sendEmail($username) {
global $wpdb;
$user = $wpdb->get_row("SELECT email, firstname from wp_site_users WHERE username ='" . $username ."'" , ARRAY_A);
$mail = $wpdb->get_row("SELECT * from wp_send_email WHERE id='1'", ARRAY_A);
$to = $user['email'];
$subject = 'Hello!';
$message = $mail['header'] . $user['firstname'] ."\n";
$message .= $mail['content'] . $username . "\n";
$message .= $mail['footer'];
$headers = 'From: '.'test#test.com'."\r\n";
echo $to . "<br>" . $subject . "<br>" . $message . "<br>" . $headers;
wp_mail($to, $subject, $message, $headers);
}
I've tried to add add_action( 'plugins_loaded', 'sendEmail' ); at the header but that doesn't seem to work.
Any ideas?
You are calling wp_mail before it's loaded..
Just include wp-load.php and go ahead!
require('../../../wp-load.php');
or
require('wp-load.php');
Depending how your script are loaded.
Call wp_mail after all of the necessary files are loaded:
add_action( 'plugins_loaded', 'plugins_load' );
function plugins_load() {
require MY_PLUGIN_PATH . '/includes/main.php';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail('youremail#gmail.com', 'Thank you', 'Message', $headers);
}
This script is driving me up the wall. It's a simple submission form. I click the "submit" button and the email with all the submitted information is generated perfectly fine.
But I can't get the button to then redirect me to the "Thank You" page.
I've tried PHP, I've tried Javascript, I've even tried good old fashioned Meta Redirect. Nothing works.
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
header("location:http://amvleague.vitaminh.info/thankyou.html")
}
die();
?>
I've tried putting the "header" part at the top of the document. I've tried changing it to:
echo '<script>document.location="page2.html"; </script>';
I've generated so many emails with this script that gmail is now sending them all to spam. And I can't get the damn thing to redirect.
If anyone can help before I claw my eyes out, it would be much obliged. ^_^;;
EDIT: I've tried everything you've all suggested. It's as if the script just flat-out refuses to execute anything that comes after the mail command. Could there be a reason for this?
EDIT 2: Still nothing's working.
Here's the entire script (with Rolen Koh's modifications). Is there something hidden in here that is preventing the script from accessing anything that comes after the mail tag?
<?php
if(isset($_POST['email'])) {
$email_to = "pathos#vitaminh.info";
$email_subject = "BelleCON 2014 - AMV League Submission";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['handle']) ||
!isset($_POST['amv_title']) ||
!isset($_POST['amv_song']) ||
!isset($_POST['amv_artist']) ||
!isset($_POST['amv_anime']) ||
!isset($_POST['amv_link']) ||
!isset($_POST['amv_category']) ||
!isset($_POST['email'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$handle = $_POST['handle']; // not required
$amv_title = $_POST['amv_title']; // required
$amv_song = $_POST['amv_song']; // required
$amv_artist = $_POST['amv_artist']; // required
$amv_anime = $_POST['amv_anime']; // required
$amv_link = $_POST['amv_link']; // required
$amv_category = $_POST['amv_category']; // required
$email_from = $_POST['email']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($first_name).clean_string($last_name)."\n";
$email_message .= "Handle: ".clean_string($handle)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Title of AMV: ".clean_string($amv_title)."\n";
$email_message .= "Category: ".clean_string($amv_category)."\n";
$email_message .= "Song: ".clean_string($amv_song)." by ".clean_string($amv_artist)."\n";
$email_message .= "Anime Used: ".clean_string($amv_anime)."\n\n";
$email_message .= clean_string($amv_link)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
}
}
?>
You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).
try this,this is what I am using
function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
}else{
header('Location: ' . $url);
die();
}
}
Try this:
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
Also semi-colon is missing in your header("location:http://amvleague.vitaminh.info/thankyou.html") line but i guess it is typo error.
use location.href
echo '<script>window.location.href="page2.html"; </script>';
The window.location object can be written without the window prefix.
The line
header("location:http://amvleague.vitaminh.info/thankyou.html")
Needs to be
header("Location: http://amvleague.vitaminh.info/thankyou.html");
Note the capital "L", the space after the colon, and the semicolon at the end.
If this does not resolve your issue, then you have an issue in some other piece of code. To find it, you might try looking at the php error log. If you have access to the server, you can find this by using any of the following resources for your particular server.
http://www.cyberciti.biz/faq/error_log-defines-file-where-script-errors-logged/
Where does PHP store the error log? (php5, apache, fastcgi, cpanel)
Where can I find error log files?
If you are on a shared host, they might have some non-standard location for this file, in which case, it might be easiest to contact them and ask where their standard location of the php error log is.
I am trying to pass $email field to thank you page which appears after redirection once user submits the enquiry form.
Its a 2 step enquiry form with thank you page being last.
It seems like the SESSION is live on thank you page however the values are lost. I'd like to get $email field posted on the thank you page to an iframe. Please let me know where exactly the session id is going wrong?
Here are the codes:
Step 1: Small Enquiry form
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
if(isset($_REQUEST['btnSubmit']) == 'Next'){
$obj = new validation();
$obj->add_fields(trim($_POST['txt_fname']), 'req', 'Enter your first name.');
$obj->add_fields(trim($_POST['txt_contact']), 'req', 'Enter phone number.');
$obj->add_fields(trim($_POST['txt_finamount']), 'req', 'Enter the amount.');
$obj->add_fields(trim($_POST['sel_loantype']), 'req', 'Please select vehicle type.');
$error = $obj->validate();
if($error){
$error_msg = "".$error."";
$_SESSION['error_msgs'] = $error_msg;
header("location:".$_SERVER['HTTP_REFERER']."");
exit();
}else{
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit();
/*$fname = trim($_REQUEST["txt_fname"]);
$surname = trim($_REQUEST["txt_surname"]);
$phone = trim($_REQUEST["txt_contact"]);
$finamount = trim($_REQUEST['txt_finamount']);
$sel_loantype = trim($_REQUEST['sel_loantype']);
$message = '<html><body>';
$message .= '<table rules="all" width="100%" style="border:1px solid #666;" cellpadding="10">';
$message .= "<tr><td><strong>First Name:</strong> </td><td>" . strip_tags($fname) . "</td></tr>";
if($surname != ''){
$message .= "<tr><td><strong>Surname:</strong> </td><td>" . strip_tags($surname) . "</td></tr>";
}
$message .= "<tr><td><strong>Phone:</strong> </td><td>" . strip_tags($phone) . "</td></tr>";
$message .= "<tr><td><strong>Amount to Finance:</strong> </td><td>" . strip_tags($finamount) . "</td></tr>";
$message .= "<tr><td><strong>Loan Type:</strong> </td><td>" . strip_tags($sel_loantype) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$ToEmail = 'testemail#gmail.com';
$EmailSubject = "GET A QUICK QUOTE from ".strip_tags($fname);
$mailheader = "From: ".strip_tags($fname)."\r\n";
//$mailheader .= "Reply-To: ".$_REQUEST["txt_email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = $message;
if(#mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)){
$_SESSION['sucess'] = "Your message has been sent successfully.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}else{
$_SESSION['sucess'] = "Sorry! Your message has not been sent.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}*/
}
}
?>
Step 2 Code:
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
?>
<script type="text/javascript">
function submitToCRM()
{
$.ajax({
type: 'POST',
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php',
data: $("#applynowform").serialize(),
beforeSend: function () {
$("#loadingimg").show();
},
success: function (){
//alert(data);
window.location.href = "http://www.test.com.au/thank-you";
}
});
Step 3: The above page sends data to quickquote-one.php form processing script which has below code.
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user_email'] = $_POST['email'];
Step 4: thank you page (this page has below code)
<?php
if(!isset($_SESSION))
{
session_start();
$_SESSION['user_email'] = $_POST['email'];
echo $_SESSION['user_email'];
}
?>
Add
session_set_cookie_params(0);
before your
session_start();
You can also pass the SID (session ID) between the pages using the URL to make sure it isn't lost in transition.
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php?<?php echo htmlspecialchars(SID); ?>',
and
window.location.href = "http://www.test.com.au/thank-you?<?php echo htmlspecialchars(SID); ?>";
You're losing the session because you're sending the browser to the next URL without a relative path but instead a fully-qualified domain. This is a security measure to prevent session IDs from being inadvertently sent to the wrong server.
Another small solution would be to use relative paths like /page.php instead of http://www.domain.com/page.php
Read more here (PHP Manual)
In step 4 your setting
$_SESSION['user_email']
again. If the form has refreshed then your post is empty and you are overwriting the session with an empty value. Try removing it from step 4 and just leave.
<?php
if(isset($_SESSION['user_email']) && !empty($_SESSION['user_email']))
{
echo $_SESSION['user_email'];
}
?>
Also you are trying to echo your session email value IF the session is NOT set. I don't think that will work if the session is actually set..
i think it is better to start a session in one page and access all the session variables throghout if all the pages are connected to eachother. it will be some thing like we create login page. When user logs in capture alll the required values in a session and can be accessed through out the application even after refresh.
$query = "SELECT Useid,UserName,AccountStatus, FullName FROM Users WHERE UserName = :UserName";
from this query we can get the session variables easily.
if($login_ok)
{
//for last visit
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(AboutVisit, date("F jS - g:i a"), $Month);
//last visit ends here.
$_SESSION['user'] = $row['UserName'];
$_SESSION['userid'] = $row['Useid'];
$_SESSION['fullname'] = $row['FullName'];
}
where ever you need th variable you can use like this
$username=$_SESION['user'];
I think this will work instead of startign session every time in each page.
Hope it helps