How to prevent variables showing in URL? - php

<?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.

Related

PHP Session lost/login not working

I have a question regarding sessions in php. I made a login page, and whenever I tried it, it just gave me a redirect error. So I followed the answer from this question.
So now, instead of getting the redirect error, whenever I press the login button nothing happens, the form is emptied and that is all. What am I doing wrong? This is currently how the code which is giving me issues looks like.
index.php:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$password = $_POST['password'];
$file = file_get_contents("data.txt");
if (strstr($file, "$name||$password")) {
$_SESSION["valid_user"] = $_POST["name"];
$_SESSION["valid_time"] = time();
Header("Location: welcome.php");
} elseif (empty($name) && empty($password)) {
echo "Both fields are empty. Please fill them.";
} elseif (empty($name)) {
echo "No name was entered.";
} elseif (empty($password)) {
echo "No password was entered";
} else {
echo "Wrong credentials, please try again.";
}
}
To be more specific the code which I think is the problem is this part:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
But whenever I try it I either get the redirect error:
My browser gives me "ERR_TOO_MANY_REDIRECTS" when I try to enter the page.
or the page just empties the form and nothing else happens. And the error messages which are supposed to be displayed when I don't type anything in the form is not displaying either. It's been giving me headaches the whole day today so if anyone could just point me in the right direction that would be great.
Also the form HTML I use in index.php:
<body>
<form method="post" action="index.php" >
<p>Enter name:</p>
<input type="text" name="name" />
<br/>
<br/>
<p>Enter password:</p>
<input type="password" name="password" />
<br/>
<br/>
<input type="submit" value="Login" name="submit"/>
</form>
</body>
I think there are too many errors related to code. There must be spaces between the opening PHP tag and session_start();.
Plus, the conditional statement you've given in if (isset($_SESSION['valid_user'])) is being interpreted as "if it IS set". What you should have used is the ! operator, meaning if it is "NOT" set.
That is why you are getting "too many redirects".
<?php session_start();// try putting space between here
if (!isset($_SESSION['valid_user'])) {
header("Location: login.php"); // Redirect back to your login page
exit();
}
also in } elseif (empty($name) && empty($password)) {
// all elseif should be like else if(condition)
also change file names.
You should also add an exit; after every header, otherwise your code will want to continue to execute.
Problem is here when you have a valid user then you are trying to redirect it on index.php which again check for valid user and again redirect on index.php its like INFINITE loop.
Thanx #Fred-ii-
You've got your answer but here is an explanation about "Too many redirects". You are getting that error on your browser because your code is keep redirecting to another page. Both of your statements are returning true:
if (isset($_SESSION['valid_user'])) {
} //Returning true - Redirect to index
if (strstr($file, "$name||$password")) {
} //Returning true - Redirect to welcome
As there are/were no exits after the redirects, the code carries on executing: redirect here than redirect there...
Also you should check the session validation as follows:
if(!isset($_SESSION['session']) || $_SESSION[''] == "")
This will check if the session is not set OR empty.

stop preventing HTML code rendering with Return and Die function in php

As you know in a php script when you call Return or Die it prevents the rest of HTML codes from rendering.
In an occasion when I just want to stop the php script but not whole the page what would I do?
Ex:
<?php
if(!isset($_POST['txt_username']))
{
echo "Please enter your username";
return;
}
?>
<i want="this html">to be rendered</i>
I want my HTML codes to be rendered afterward.
Thanks for reading.
Your question is not clear, but you need to stop the PHP code to execute, but the HTML to render? You might need output buffer or functions.
E.g.:
<form action="" method="post" >
<input type="text" name="txt_username" />
<input type="submit" />
</form>
<?php
function doSmth(&$password) {
if(!isset($_POST['txt_username']))
{
echo "Please enter your username";
return false;
}
$password .= "333";
echo "You password has been changed to $password";
}
$password = 128;
doSmth($password);
?>
<body>
<p> <b> Your password is <?= $password; ?> </b></p>
</body>
Examples:
Text field is set:
Output:
You password has been changed to 128333
Your password is 128333
Text field is not set:
Output:
Please enter your username
Your password is 128
Use the conditional statement to include more PHP is needed. The HTML can then be rendered regardless of the PHP's if/else statement. Example:
<?php
if( !isset($_POST['txt_username']) )
{
echo "Please enter your username";
}
else
{
//Some dditional PHP functions
}
?>
<i want="this html">to be rendered</i>
<?php
$stateOfRender = false;
if(!(isset($_SESSION['sessionid']))) {
echo "You have not logged yet. Now you are redirecting to Login Page";
header('Refresh: 5; URL = login.php');
} else {
$stateOfRender = true;
}
// In everywhere you can use this variable to control your statement
// for example:
if($stateOfRender) {
// Open DB connection and fetch user data and settle it to page.
}
?>
In my php code i use this method to handle process. Generally i use it in db connection. If dbconnection is success i render page with control this variable. I hope to it helps you.

PHP:my session_variables shows when the page refresh

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
}

php redirection not working

Ive got this register script that puts the information into a mysql database. now it all works fine and when someone does something wrong its says the error (e.g. "Username not defined")
but when it goes wrong it does not look very good because it just displays the message on an empty page, so i thought i would make it redirect to the form page and display the message there.
here is the working script
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$errors = array();
if(!$username) {
$errors[] = "Username is not defined";
}
if(!$password) {
$errors[] = "Password is not defined";
}
and it continues.
now i just thought i could do this
$errors = array();
if(!$username) {
$errors[] = header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
}
if(!$password) {
$errors[] = "Password is not defined";
}
but no, all it does is ignore it.
could someone please help me
please feel free to ask for more of the script if you need it
many thanks connor
You cannot wrap a header in a array like that.
You just call the function, then it redirects.
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
it does not look very good because it just displays the message on an empty page,
What's the problem?
Why not to show the form again? with fields already filled.
This is going to be a user-friendly interface.
Just include your form in the same page with fields populated.
That's more common way than your redirects to blank form.
This is called POST/Redirect/GET pattern and here goes a short example of it:
the code
<?
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';
?>
the template
<? 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>
You are placing the return value of the header function in an array, then continuing with your page execution.
If you don't care about anything that would normally happen below that redirection, which I believe is what you're implying, you should just set the header and then immediately exit. Do not try to place the return value of the header function into the errors array like that, as there's no point.
if(!$username) {
header('Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined');
exit;
}
I don't if this is the problem, but it's important to include the status code in header too. Like:
header("Location: /foo.php",TRUE,302);
307 for Temporary Redirect, 302 for permanently moved. Chrome, a while ago, didn't accepted headers redirect without status code (i don't know nowadays).
try this after filling your error array:
if (count($errors) > 0)
{
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' );
exit;
}
Keep in mind there should be no html output before this part!

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