PHP:my session_variables shows when the page refresh - php

I know this is very simple thing but i am not aware of this. I have php code on same page for a signup form which have some session variables to be shown when any condition matches with the code.
The code structure is like this:
<?php
session_start();
if(isset($_POST['signup'])
{
if(condition)
{
$_SESSION['err1']="string";
}
else
{
$_SESSION['err2']="string";
}
}
?>
//HTML form
<?php if(isset($_SESSION['err1']) {?>
<li><?php echo $_SESSION['err1'];}?></li>
<?php if(isset($_SESSION['err2']) {?>
<li><?php echo $_SESSION['err2'];}?></li>
//rest of the form
I have more block of if-else in my code. Initially, when an condition is matched, the session message is shown. But as soon as the page refresh an another session message is shown along with previous session message.
Is this correct way of coding with forms? Because i want to show error messages inside the html form.

That's maybe because you do not empty your session variable.
Between 2 HTTP request, the session is kept on the server (juste reloading at each request).
So, if you are putting a message on $_SESSION['error1'] for the first call, it will show it. Then, on the second load, if you are putting a message on $_SESSION['error2'], you will also have the message of error1 because the session keep your data.
After showing the form, you should empty all your session messages

Simply unset your session variable after you echo.
<li><?php echo $_SESSION['err1'];} unset($_SESSION['err1']); ?></li>

This is really a bad example that use session to echo errors.
what i do many times at the starting of my php.
$errors = array(); // make a empty array errors before the conditional statements
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Submit'])) {
//handle your POST variable
if(condition1){
$errors[] = "some error";
}
if(condition2) {
$errors[] = "some another error";
}
//more conditions
if (!empty($errors)) {
//process your form data if there is no errro
} else {
//display back your form along with Errors
if(isset($errors) && !empty($errors)) {
foreach($errors as $error) {
echo "<p class = 'error'>" . $error . "</p>";
}
}
<form action = "" method = "POST">
//your form elements
</form>
}
}

in first line of the php page, u can write
you can try any of the three lines between if condition
if(isset($_SESSION))
{
unset($_SESSION);
unregister($_SESSION['variable-name']) // try this also
session_destroy(); //try this also
}

Related

Redirecting to same page along with Success Message with Php [duplicate]

This question already has answers here:
Redirect to another page with a message
(6 answers)
Closed 8 months ago.
What's the best way to display a success message after redirecting to same page? I've been thinking about doing that with javascript but maybe there's a way to do this with Php? The user submit from profile.php and gets redirected to same page. I'd like to grab a variable... Can I concatenate after $_SERVER['HTTP_REFERER']? Whats the best approach?
here a snippet of code: query.php
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$stmt->close();
$db->close();
}
You could skip the session, and pass a url query parameter as a code or the message.
$stmt->execute() or die(mysqli_error($db));
if($stmt){
// echo "Data Submitted succesfully";
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?message=success1');
exit;
}
$stmt->close();
$db->close();
}
Then have code that checks for $_GET['message] ...etc
You can use sessions. Just start session, save message in global array $_SESSION, then in profile.php check if $_SESSION with your key is set and it isn't empty show it. After it you can unset your key in $_SESSION.
query.php
<?php
session_start();
//your code
if($stmt) {
$_SESSION['myMessage'] = 'Some message';
//your code
}
//rest of your code
profile.php
<?php
session_start();
//your code
if(isset($_SESSION['myMessage']) && $_SESSION['myMessage'] !== '') {
//display message or do with it what you want
}
//rest of code
If you're processing your form in the same page, then you don't have to do any redirection. The solution to achieve the desired result would be like this:
Put your form processing code at the very top of your PHP script i.e. profile.php page.
Use a boolean variable to hold the status of ->execute() statement, and use that same variable at later point of your code.
So the code would be like this:
// Declare a boolean variable at the beginning
$status = false;
// your code
$status = $stmt->execute();
$stmt->close();
$db->close();
}
if($status){
// Data submitted succesfully
}else{
// Data couldn't get submitted
}
If you want to process the form at the same file, you don't need to redirect again to the same page.
As mention by the other answer, you process the form at the top of the page.
To display a message after success or failure, you store the message in a variable. Later with the from you echo the message variable if it is set.
// Check if form was submitted
if(isset($_POST['submit'])) { // I name the submit button "submit"
// process the form
if ($stmt->execute()) {
$message = "<div> Success </div>";
} else {
$message = "<div> Failed </div>";
}
}
// Display The form and the message if not empty
if (! empty($message)) {
echo $message;
}
// Form

How to condition a user to fill the form than to oppen an specific site up

i have a multi step form and want to condition users on specific sites on my web .
This mean i want that only after submitting my form a client in my case can see the redirected page ,
And that with a kinda tim-out for that page to . this redirected page need to show only to those people who fill the form first even when users copy the link and give that link to somebody else the link should not work or should direction in a error. i have archived the last part partly
Here is all my code :
On the form.php i have this :
<?php
session_start(); $_SESSION['form_finished'] = true;
?>
On the proces.php i have this :
$emotion = $_POST['emotion'];
if($emotion == 'Basic Pack') {
session_start();
$_SESSION['form_finished'] = true;
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
and destination site in this case basicc.php' this :
<?php
session_start();
if(!$_SESSION['form_finished']) {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
This code is working partly because if the user on the form.php site if he just copy the basicc.php link on the address bar he can see the basic.php site imadtitly without having to fill the form , and i want that to condition him to do that and than the page to show up .
I hope i was clear thanks in advance
If proces.php is where submitting the form redirects then remove $_SESSION['form_finished'] = true; from form.php and keep it in proces.php only.
ETA: For the timer:
<script>
var remainingSeconds = 600; // how many second before redirect
function counter() {
if (remainingSeconds == 0) { clearInterval(countdownTimer); window.open('form.php', '_SELF'); // return to form page
} else { remainingSeconds--; }
}
var countdownTimer = setInterval('counter()', 1000); // 1000 is the interval for counting down, in this case 1 second
</script>
In this case, you will have to add back the statement in form.php but set it to false $_SESSION['form_finished'] = false;
ETA2: Forgot to mention that you should also add $_SESSION['form_finished'] = false; in basicc.php.
Yes you could just use a simple session for this case. Example:
If in your form action, if the form processing is in process.php. You could initialize there the session.
session_start();
$emotion = $_POST['emotion'];
$_SESSION['form_finished'] = true; // set session
// then your other process etc. etc.
if($emotion == 'Basic Pack') {
header('Location: /new/basicc.php');
} elseif($emotion == 'Deluxe Pack') {
header('Location: html6.php');
} elseif($emotion == 'Premium Pack') {
header('Location: html7.php');
}
And then on the destination files: /new/basicc.php and others, check that session existence:
/new/basicc.php and others:
if(isset($_SESSION['form_finished'])) { // so after redirection check this
//
// hello, i came from process.php
unset($_SESSION['form_finished']); // and then UNSET it! this is important
} else {
echo 'not allowed'; // if this is not set, the page is directly accessed, not allowed
exit;
}
I think the best solution is that you should only use one page, no need for sessions ;)
Try to have a particular variable set to false, send your form to the server using a POST method <form method=post> and on your server, change this variable to true and render the same page again.
In the example below, I'm checking if the user has entered his name in the form. ;)
<!-- In form.php -->
<?php
$formSubmitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["name"])) {
//Do what you need to do with form data, for example:
$name = filter_var($_POST["name"],FILTER_SANITIZE_STRING);
//Maybe do some checks on the data (or add to database) and when successful:
if($name != '')
{
$formSubmitted = true; // Set variable to true
}
}
?>
<?php if($formSubmitted): ?>
Hello <?php echo $name; ?>! <!-- Show all other HTML things you want to show -->
<p> This is a message only for people who submitted the form! </p>
<?php else: ?>
<form action='form.php' method='POST'>
<input name='name' type='text'>
</form>
<?php endif; ?>
I hope it'll be useful and hopefully a different way to look at the problem. For multi-step, this could easily accommodate more variables to see which step the user is on ;)
Good luck :)

redirecting back message

I have a document called editprofile.php and I have another one that is called action.php. when the user submits their info using editprofile.php. the information get POSTed to action.php where I process the information and send it to mysql. After sending it I want to show a message that everything has been successfully changed. I used this :
if $everythingisdone{
$smarty->assign('sucess', 'Your changes have been made');
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
I get redirected to the previous page, but there is no message even though I have this in my editprofile.tpl
{if $sucess}
<div class="sucess">
{$sucess}
</div>
{/if}
how can I assign the message when I redirect back?
you could do:
//custom smarty function to set session flash messages
function smarty_function_set_flash($params, $smarty) {
$flash = "";
if (isset($_SESSION['success'])) {
$flash = $_SESSION['success'];
$_SESSION['success'] = ""; //unset the session
}
return $flash; //return flash message
}
your code
....
if($everythingisdone) {
$_SESSION['success'] = 'Your changes have been made';
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
and view:
{if isset($smarty.session.flash) && $smarty.session.flash != ''}
<div class="sucess">{set_flash}</div>
{/if}
You can't redirect to another page and expect variables to persist. When you call $smarty->assign() that change will persist only for that specific page request and no more, once you redirect its all gone.
You could do this with a GET parameter:
<?php
// action.php
if ($something) {
header ("Location: " . $_SERVER['HTTP_REFERER'] . "?success=1");
die;
}
else {
header ("Location: " . $_SERVER['HTTP_REFERER'] . "?success=0");
die;
}
Then in editprofile.php you could check for that value:
<?php
// editprofile.php
if ($_GET['success'] == '1') {
// yes!
}
else {
// aww :(
}
This would not be necessary if you wouldn't redirect like that. Why not have the form on the editprofile.php and submit it to the same page and check for errors there? Set a flag variable and show an error message if the form did not submit:
<?php
if ($ok) {
$smarty->assign ('form_processed', true);
}
else {
$smarty->assign ('form_processed', false);
}
Then simply use that in your form to check for an error.
Hope this helps

How to prevent variables showing in URL?

<?php
if(isset($_POST['chgPwd']))
{
$oldpwd=$_POST["txtOldPassword"];
$newpwd=$_POST["txtNewPassword"];
$cnewpwd=$_POST["txtConfirmNewPassword"];
//did stuff to get in the text fields
$oldpass = oci_result($new1,"OLDPASS");
if($oldpwd!=$oldpass)
{
$msg = "The old password does not match with the one in the records";
header("Location:ErrorPage.php?abc=".$msg);
}
}
?>
My question here is that when i redirecting my page to the ErrorPage.php, I am able to see the entire page in the URL, which i do not want it to. Is there anyway around this. I am thinking of binding sessions, but i am unable to get it right. Could you please show me the right way if there is any?
You should urlencode($msg) ( string $str ) and perhaps add an exit() after header.
Edit: Well, you only want to see ErrorPage.php in your browsers URL, right? Without any message or attributes? Then you have to work with SESSIONS (or Cookies) to store the message/location for the current user and then to redirect him back to ErrorPage with the individual message.
Get rid of the error page and show your errors oncite.
Here is the sketch of the registration code
<?
include 'config.php';
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
and a template contains the form and the error mesages
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
This is the most common way of form processing called POST/Redirect/GET
header("Location:ErrorPage.php?abc=1");
ErrorPage.php
if(isset($_GET['abc'])=="1")
{
Show Some Message
}
You can use sessions to hide that parameters. It's the simplest way.

PHP Check Empty Value From Separate File

I have a registration page and I am going to check the values of each field in both javascript and PHP. The problem is I have the registration code behind in a separate file. I put it in a seperate file because I am querying a database and much more so I ruled out posting to self. I then figured that redirecting to an separate error page would be overkill.
So what I would like to do is redirect to the registration page with the error message at the top or something of the sort just like if I was posting the form to self. How can I go about doing this?
It's ok to have registration code in the separate file.
However, this file have to be the registration page itself.
While the form is stored in the another file and just get included.
Here is the sketch of the registration code
<?
include 'config.php';
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
and a template contains the form and the error mesages
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
This is the most common way of form processing called POST/Redirect/GET
Why don't you just post to self? All you must do is structure the php so that once verified it inserts the data ect...
if( isset($_POST[ 'submit' ]) ){
//Do checks
// if all checks pass do your thing.
// redirect.... header();
exit;
}
// you could then do if( isset($_POST['name']) ){ echo 'name'; } to repopulate the fields so you don't irritate the user.
If you still insist on doing it this way still use header() to redirect your user. (not a plesent user experience in my opinion...and the user have to refill all the data out again.)
You could post to your authentication page, check if they have a blank field or whatever, then redirect via
header(Location:<your url here>?error=1);
back to the original page and have that page check for the GET variable $_GET['error']. If that variable is 1, display some error.
Is this what you are looking for?

Categories