I am trying to create a session for each field of a form so that I can call it back in on the additional information form on the next page.
<?php
session_start(); // starting the session
if (isset($_POST['Submit'])) {
$_SESSION['breakdowndate'] = $_POST['breakdowndate'];
$_SESSION['policyinception'] = $_POST['policyinception'];
$_SESSION['customername'] = $_GET['customername'];
$_SESSION['customersurname'] = $_GET['customersurname'];
$_SESSION['covertype'] = $_POST['covertype'];
$_SESSION['vehiclemake'] = $_POST['vehiclemake'];
$_SESSION['vehiclemodel'] = $_POST['vehiclemodel'];
$_SESSION['vehiclereg'] = $_POST['vehiclereg'];
$_SESSION['vehicleage'] = $_POST['vehicleage'];
$_SESSION['excess'] = $_POST['excess'];
$_SESSION['mileage'] = $_POST['mileage'];
$_SESSION['paid'] = $_POST['paid'];
$_SESSION['HSRS'] = $_POST['HSRS'];
$_SESSION['fault'] = $_POST['fault'];
$_SESSION['garage'] = $_POST['garage'];
$_SESSION['telephone'] = $_POST['telephone'];
}
?>
Using some code and after a few modifications I have the code above trying to store data that has been submitted in the form..
How can I improve this code to make it work?
If it is not working, try debugging.
If it is saving the POST, then there is not much left to do.
Set session.cookie.secure to true. You may want to set session.cookie_lifetime.
As far as security, consider if you have something worth protecting. Does it matter if someone gets a visitor's session cookie? If not, forget it.
session_set_cookie_params(0, '/', '', true, false);
session_start();
error_reporting(E_ALL); // debug
if (isset($_POST['Submit'])) {
$_SESSION['breakdowndate'] = $_POST['breakdowndate'];
$_SESSION['policyinception'] = $_POST['policyinception'];
$_SESSION['customername'] = $_GET['customername'];
$_SESSION['customersurname'] = $_GET['customersurname'];
$_SESSION['covertype'] = $_POST['covertype'];
$_SESSION['vehiclemake'] = $_POST['vehiclemake'];
$_SESSION['vehiclemodel'] = $_POST['vehiclemodel'];
$_SESSION['vehiclereg'] = $_POST['vehiclereg'];
$_SESSION['vehicleage'] = $_POST['vehicleage'];
$_SESSION['excess'] = $_POST['excess'];
$_SESSION['mileage'] = $_POST['mileage'];
$_SESSION['paid'] = $_POST['paid'];
$_SESSION['HSRS'] = $_POST['HSRS'];
$_SESSION['fault'] = $_POST['fault'];
$_SESSION['garage'] = $_POST['garage'];
$_SESSION['telephone'] = $_POST['telephone'];
} else {
echo '<h3>Session Not Saved</h3>';
}
echo htmlentities(var_export($_REQUEST, true)); // debug
echo htmlentities(var_export($_SESSION, true)); // debug
DEBUG
It should work - if not, test and debug.
Show all Warnings.
Check $_SESSION after setting.
Check Request.
$_REQUEST includes $_COOKIE which should contain a SESSION cookie.
We need to regenerate id. Try this. (Sorry for bad english)
<?php
session_start(); // starting the session
if (isset($_POST['Submit'])) {
session_regenerate_id();
$_SESSION['breakdowndate'] = $_POST['breakdowndate'];
$_SESSION['policyinception'] = $_POST['policyinception'];
$_SESSION['customername'] = $_GET['customername'];
$_SESSION['customersurname'] = $_GET['customersurname'];
$_SESSION['covertype'] = $_POST['covertype'];
$_SESSION['vehiclemake'] = $_POST['vehiclemake'];
$_SESSION['vehiclemodel'] = $_POST['vehiclemodel'];
$_SESSION['vehiclereg'] = $_POST['vehiclereg'];
$_SESSION['vehicleage'] = $_POST['vehicleage'];
$_SESSION['excess'] = $_POST['excess'];
$_SESSION['mileage'] = $_POST['mileage'];
$_SESSION['paid'] = $_POST['paid'];
$_SESSION['HSRS'] = $_POST['HSRS'];
$_SESSION['fault'] = $_POST['fault'];
$_SESSION['garage'] = $_POST['garage'];
$_SESSION['telephone'] = $_POST['telephone'];
session_write_close();
}
?>
Store your variables in an array and loop as shown below. You can use session_start(); on your next page and access them:
<?php
session_start(); // starting the session
$sessionItems = array('breakdowndate','policyinception','customername'...'telephone');
if (isset($_POST['Submit'])) {
foreach($sessionItems as $item) {
$_SESSION[$item] = $_POST[$item];
}
}
?>
Related
I've tried to use ob_start(); and exit(); ,both are not working, please advise, thank you very much
<?php
ob_start();
// connect to the database
include('connect-db.php');
// check if the form has been submitted.
// If it has, start to process the form and save it to the database
// once saved, redirect back to the view page
if (isset($_POST["submit"]))
{
foreach ($_POST['patientid'] as $index => $patientid)
{
$id = mysql_real_escape_string($_POST['id'][$index]);
$data1 = mysql_real_escape_string($patientid);
$data2 = mysql_real_escape_string($_POST['vaccineid'][$index]);
$data3 = mysql_real_escape_string($_POST['vaccinename1'][$index]);
$data4 = mysql_real_escape_string($_POST['vaccinename2'][$index]);
$data5 = mysql_real_escape_string($_POST['vaccinename3'][$index]);
$data6 = mysql_real_escape_string($_POST['totalnoofinjection'][$index]);
$data7 = mysql_real_escape_string($_POST['nthinjection'][$index]);
$data8 = mysql_real_escape_string($_POST['date'][$index]);
$data9 = mysql_real_escape_string($_POST['nextdate'][$index]);
$data10 = mysql_real_escape_string($_POST['skip'][$index]);
$data11 = mysql_real_escape_string($_POST['language'][$index]);
mysql_query("UPDATE patientvaccinedetail SET patientid = '$data1',
vaccineid = '$data2', vaccinename1 = '$data3',
vaccinename2 = '$data4', vaccinename3 = '$data5',
totalnoofinjection = '$data6', nthinjection = '$data7',
date = '$data8', nextdate = '$data9', skip = '$data10',
language = '$data11'
WHERE id=$id") or die(mysql_error());
header("Location: start.php");
exit;
}
}
Just updated and still cant't redirect to another pages
You are missing semi colon after exit
Corrected code:
exit;
use ob_end_clean(); before the header call and use exit; instead of exit
try like below
ob_end_clean();
header("Location: start.php");
exit;
I am having a bit of an issue passing array variables that are fetched from the database and stored in variables and passing them into session variables to use all over the site.
Code:
$rid=$_SESSION['SESS_MEMBER_ID'] ;
$recquery = 'SELECT * FROM clinic_receptionist,clinic_table where clinic_receptionist.recep_clinic_id = clinic_table.ID AND recep_id ='.$rid;
$recresult = mysqli_query($conn,$recquery);
if(mysqli_num_rows($recresult)>0)
{
while($row = mysqli_fetch_assoc($recresult))
{
$cid = $row['clinic_id'];
$cname = $row['clinic_name'];
$name = $row['recep_full_name'];
$phone = $row['recep_mobile'];
$email = $row['recep_email'];
$address = $row['recep_address'];
$gender = explode(",",$row['recep_gender']);
$dob = $row['recep_dob'];
$doj = $row['recep_doj'];
}
}
?>
The above code is where the select query is happening. I wanted to know how do I assign $cid and $cname to a $_SESSION variable in different pages. Any help would be much appreciated. Thanks
CODE:
<?php session_start();
include('header.php');
include('menu.php');
include('config.php');
$appquery = 'SELECT * FROM appointment_table,clinic_table where clinic_table.ID = appointment_table.clinic_id';
$appresult = mysqli_query($conn,$appquery);
if(mysqli_num_rows($appresult)>0)
{
while($row = mysqli_fetch_array($appresult))
{
$_SESSION['cid'] = $row['ID'];
$_SESSION['cname'] = $row['clinic_name'];
$ptdate = $row['date'];
$pttime = $row['time'];
$ptname = $row['pt_name'];
$ptphone = $row['pt_ph_num'];
$ptemail = $row['pt_email_id'];
}
}
?>
The above code is the place from where I want to receive the id and clinic name.
<?php
// Start the session
session_start();
//Assigning the values to $_SESSION
$_SESSION['cid'] = $row['clinic_id'];
$_SESSION['cname'] = $row['clinic_name'];;
?>
session_start
You need to call session_start() on each page to initialize the session, of course; after that you can just
$_SESSION['cid'] = $cid;
$_SESSION['cname'] = $cname;
to store those values in $_SESSION.
By the way, someone's going to tell you to use a prepared statement for that query, so it might as well be me.
Perhaps an illustration is in order.
page1.php:
<?php
session_start(); // find session, or create new one
include('header.php');
include('menu.php');
include('config.php');
$appquery = 'SELECT * FROM appointment_table,clinic_table where clinic_table.ID = appointment_table.clinic_id';
$appresult = $conn->query($appquery);
if(($rowcount = $appresult->num_rows()) > 0)
{
// create arrays to pass data
$cids = array($rowcount);
$cnames = array($rowcount);
$i = 0;
while($row = $appresult->fetch_array())
{
// add values to arrays
$cids[$i] = $row['ID'];
$cnames[$i] = $row['clinic_name'];
$i++;
}
// add arrays to session
$_SESSION['cids'] = $cids;
$_SESSION['cnames'] = $cnames;
}
page2.php:
<?php
session_start(); // find session, or create new one
include('header.php');
include('menu.php');
include('config.php');
// retrieve arrays from session
$cnames = $_SESSION['cnames'];
$cids = $_SESSION['cids'];
// ... and print them
$count = count($cids);
for ($i = 0; $i < $count; $i++)
{
echo "cid = " . $cid[$i] . "; cname = " . $cname[$i] . "<br>";
}
page1.php performs the query and stores cid and cname values in arrays which are then stored in $_SESSION. page2.php retrieves the arrays from $_SESSION and echoes them out. In production, of course, it would be considered more efficient to run the query on the page where it is displayed, and only pass key values between pages.
I've also used object syntax instead of procedural syntax for mysqli, just to show what it looks like. As usual, I leave error handling as an exercise for the reader.
I want to add a counter in my webpage which counts the number of visitors.
But my problem is that when i refresh my page ,counter increases by 1..i want that counter increases only when a new visitor with another ip reaches to my webpage.
here are my codes..
Sorry for my weak english
index.php
<?php
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$_SESSION['current_user'] = $ip;
if(isset($_SESSION['current_user']))
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
else
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
As database based solution is not preferred, You can try the following file based solution for counting unique visitor. You already have used counter.txt file in your code.
I tried to use the same file that you have used. In my case I am storing IP address in that file. I have used base64 encoding function just to hide the IP address. It is always good to keep that file in a safe place. If that file is lost then the unique visitor IPs will be lost. See the function below:
Function definition
function getUniqueVisitorCount($ip)
{
session_start();
if(!isset($_SESSION['current_user']))
{
$file = 'counter.txt';
if(!$data = #file_get_contents($file))
{
file_put_contents($file, base64_encode($ip));
$_SESSION['visitor_count'] = 1;
}
else{
$decodedData = base64_decode($data);
$ipList = explode(';', $decodedData);
if(!in_array($ip, $ipList)){
array_push($ipList, $ip);
file_put_contents($file, base64_encode(implode(';', $ipList)));
}
$_SESSION['visitor_count'] = count($ipList);
}
$_SESSION['current_user'] = $ip;
}
}
Function call
$ip = '192.168.1.210'; // $_SERVER['REMOTE_ADDR'];
getUniqueVisitorCount($ip);
echo 'Unique visitor count: ' . $_SESSION['visitor_count'];
Output
Unique visitor count: 2
Change:
if(isset($_SESSION['current_user']))
to:
if($_SERVER['REMOTE_ADDR'] == $_SESSION['current_user'])
And, surely you dont need to get $count from a file, and then write the same value back to the file...? If the $_SERVER['REMOTE_ADDR'] matches the SESSION['current_user'] then do nothing..
try to store the user IP in database and check for unique user,
<?php
session_start();
if (!$_SESSION['status']) {
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("ip_log", $connection);
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `database`.`table` (IP) VALUES ('$ip')");
mysql_close($connection);
$_SESSION['status'] = true;
}
?>
Best And Easy Code
Try to store the user IP in database and check for unique user
$`servername` = "";
$username = "";
$password = "";
$`dbname` = "";
$`conn` = new `mysqli`($`servername`, $username, $password, $`dbname`);
if ($`conn`->connect_error) {
die("Connection failed: " . $`conn`->connect_error);
}
$address = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$name = `gethostname`();
$re = "select * from visitor where name='$name'";
$call = `mysqli_fetch_array`($re);
$as = `mysqli_num_rows`($call);
if($as == 0){
$`sql` = "UPDATE visitor SET visits = visits+1 WHERE name = '$name'";
}else{
$`sql` = "INSERT INTO visitor(visits,name,address) VALUE(1,'$name','$address')";
}
$`conn`->query($`sql`);
$`sql` = "SELECT visits FROM visitor WHERE id = 1";
$result = $`conn`->query($`sql`);
if ($result->`num_rows` > 0) {
while($row = $result->fetch_assoc()) {
$visits = $row["visits"];
}
} else {
$visits = "";
//echo $visits;
}
`$conn`->close();
I can't seem to get my session variable to output. It works fine on the other one I'm using:
$_SESSION['status']['register']['username'] = $username;
header('Location: register-form.php');
When you are taken to register-form.php it should output the variable for you:
<?php
if(isset($_SESSION['status']['register']['username'])){
$username = $_SESSION['status']['register']['username'];
} else {
$username = '';
}
?>
Exact same code is used on email_address and works fine.
Here is the same code for the email
$_SESSION['status']['register']['email_address'] = $email_address;
And on the form page:
<?php
if(isset($_SESSION['status']['register']['email_address'])){
$ea_value = $_SESSION['status']['register']['email_address'];
} else {
$ea_value = '';
}
?>
You miss to initialize your session with
session_start();
at top of your register_form.php
I have a simple question,
I have a login and workspace area.
After the user logs in It shows the username of the logged in user at workplace as what I wanted. Now my problem is when user finish filling form available in his workspace the form is then stored in database also i need the username that is coming from session also get stored to the database.
here is code that is storing username and maintaining session after user reach at workspace after login:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/MainProject/connect/auth.php');
session_start();
?>
The final version of the updated insert file :
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
// session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>
In the logging in process, you must store your username in a session
$_SESSION['username'] = $username;
in the process of saving the form, you can call session_start(); and get the session using
$tobeinserted = $_SESSION['username'];
I believe
Remove comment in session start.
Use this.
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
//$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>