session gets lost after form submit - php

When a user links to link it redirects to edit.php - here's an example: www.cars.com/edit.php?id=23
In edit.php, I use _GET to store the value in a session. The value is stored in $_session['user'] but when the form on the same page is submitted echo $_session['user'] displays nothing - how can I make it display the value?.
<?php
session_start();
$_session['user']=$_GET['id']; // I use _GET to store the value in session
if( isset($_POST['submit'])) {
echo $_session['user'];
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="formI2D" enctype="multipart/form-data" id="formI2D" />

It's because you're redeclaring your $_SESSION['user'] even when it's a POST (I think).
You can fix this by adding ?id=$_GET['id'] in you form's action, or by wrapping your $_SESSION initialisation like that:
if (isset($_GET['id'])) {
$_SESSION['user']=$_GET['id'];
}
Also, you should use uppercase for php global arrays ($_POST, $_COOKIE, $_SESSION etc)

Related

HTML form: action clarification

Hello I am currently making a registration page,
I'm new to php, and was wondering if this would work when I use the action part in form
<form method="post" id="formArea" action="action.php">
action.php is a file that contains
redirect.html
<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>
would this work? or is there a way where I can have both in the action section without the need for having to make a new file?
You Could Just Do This From The Form. If This is what your looking for:
<form method="post" id="formArea" action="<?PHP $_SERVER['PHP_SELF'];?>">
//this will make the form post to same page as the form
if your wanting to send this to both you can save the $_POST Data In A Variable and Use It Later.
EX:
<?PHP
//your form submit code might look something like this same file as your form
if(isset($_POST['submit']))
{
foreach($_POST as $key -> $value)
{
//echo or show your values or store your values in database or w/e
$_SESSION['post'][$key] = $value;
//this will make a session variable to be used again later each session array is marked with post identified by $key and stored a $value
}
//you can call your other page here this will only run after this page runs and loads your information above and then redirect with a session variable.
header("Location: redirect.html");
}
else
{
echo "<form method=\"post\" id=\"formArea\" action=\"".$_SERVER['PHP_SELF']."\">";
}
This Code Is Not Tested But It Would Work the redirect.html will process code from $_SESSION['post']

How can i get the value of previous url in php code?

How can i get the value of previous url in php code?
Here is the url page1.php
http://localhost/spk/kelulusan_process.php?lulus=10003
page2.php:
I want to get the parameter from the previous url in page1.php. I use
<?php
$_GET['lulus'];
?>
But the value is null.
For $_GET to work you have to redirect user using form action
Or you can do that by setting session variables and access them any page
You can try $_SERVER["HTTP_REFERER"]
But don't forget to escape $_SERVER["HTTP_REFERER"] since it's common for attacks.
Better is to store the current page in a $_SESSION var.
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['lastpage'] = $_SERVER['REQUEST_URI'];
Then when loading the next page:
if (!isset($_SESSION)) {
session_start();
}
// now you can access the last page
$lastpage = $_SESSION['lastpage'];
page2.php
<?php
echo htmlspecialchars($_GET["lulus"]);
?>
how are you trying to pass from page 1?
if through a form set the method to get and action to page2.php
in page1.php make sure you set the name
<form method="get" action="page2.php">
<input type="text" name="lulus">
<input id="submit" name="submit" type="submit" value="Send">
You cannot display $_GET['lulus']; in page2.php unless you write get parameter in page2.php.
Your code is redirect from page1.php to page2.php, You must set $_GET['lulus']; into one session and echo in page2.php
Page1.php
<?
$_SESSION['GET'] = $_GET['lulus'];
?>
Page2.php
<?
echo $_SESSION['GET'];
?>
Instead, echo $_GET['lulus'], you should echo in page2.php $_SESSION. Because $_SESSION variable was overrode by $_GET itself.
Use $_SERVER['HTTP_REFERER'] ... hopefully this will help you. And parse url something like below:
$url = $_SERVER['HTTP_REFERER'] ; //http://localhost/spk/kelulusan_process.php?lulus=10003
$array = explode("?lulus=",$url);
echo $array[1];

Session variable persist through POST

Can anyone see a bug in my code here?
Two files, one variable is set on the first page using JS and I want to pass it to the next page.
username variable is set here, first in variable then in session
username = wordOne + wordTwo + wordThree;
<?php $_SESSION['username'] = $username; ?>
then I submit the form which takes user to register-form.php
<form method="POST" action="register-form.php">
<button>I like it! Make it my username.</button>
</form>
when that page loads, username is grabbed and output into the input as a value
<body onload="inputUsername()">
function inputUsername(){
var username = "<?php echo isset($_POST[username])?$_POST[username]:''; ?>";
console.log("I'm running " + username);
document.getElementById('inputUsername').value = username;
}
But this doesn't work as the variable username is not persisting across the pages.
What I see is that you are asking for $_POST[username] but from the form you're not passing it.I mean something like this:
<form method="POST" action="register-form.php">
<input type="hidden" name="username" value="<?php echo $_SESSION['username']; ?>">
<button>I like it! Make it my username.</button>
In your current code, You are accessing _POST variable, however you are setting _SESSION variable in your code. Therefore, the possible fix is :
1. check for _SESSION variable in inputUsername() function OR
2. Set username in your form, so that when you submit it, it post to new page.

Get the value of a variable in page1.php in page2.php

I have a question about how I can access the value from a variable from one page on another one.
I have a registration script and the registration form is on my homepage. I want to dynamically create a random name for every input field (change the value of the name attribute). The current name attribute for the input is just firstName, but I want it to be like firstName_345635. The 345635 is a randomly generated number and will change everytime the page refreshes.
Here is my random number variable:
$firstNameInputName = 'firstName_' . rand(10000, 50000);
The output becomes: firstName_[randomNumer].
The problem is, the register.php has all the post variables to get the form data. What I have now is this:
$firstName = $_POST["firstName"]);
I need to get the value from the random number variables from the homepage and instead of giving the $firstname variable the name firstName, it should get the name that the random number generating variable has produced on the homepage.
How can I achieve this?
You should use a session (or cookies) var to save this dynamic name.
Approach 1. Session (or cookies)
page1.php
<?php
session_start();
$customCode = rand(5, 15);
$_SESSION['customCode'] = $customCode; ?>
<form action="page2.php" method="post">
<input type="text" name="firstName_<?php echo $customCode; ?>" />
</form>
page2.php
<?php
session_start();
$customCode = $_SESSION['customCode']; ?>
$firstName = $_POST['firstName_'.$customCode];
Approach 2. You can put a input hidden field in your form like:
<input type="hidden" name="customCode" value="345635" />
And get it in second page like:
$firstName = $_POST['firstName_'.$_POST['customCode']];
Approach 3. You can iterate over your $_POST array to get firstName like:
foreach($_POST in $key => $value) {
if(strpos($key, "firstName")) {
$firstName = $value;
}
}
The solution is sessions, session variables are superglobal variables which means you can use them in different files as long as its the same session, to use them you need to start the session at every page you'll use them in, also, starting the session has to be done before any output is shown.
Ex (registeration page):
<?php
session_start();
/**
** HTML AND FORM HERE WHATEVER ELSE YOU NEED TO DISPLAY
**/
$_SESSION['FirstName'] = $firstNameInputName;
?>
Ex (processing page):
<?php
session_start();
echo $_POST[$_SESSION['FirstName']]; // Output: Whatever was entered inside the field
?>

Possible to manipulate $_POST variable in php script and express it in another php script?

I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();

Categories