Simple PHP Authentication Explanation - php

I dont really have a clue what I'm doing here. I've got this code but can't get it to work for PHP authentication. Please Help.
//Authorise
<?php
ini_set("session.cookie_lifetime", "0");
ini_set("session.gc_maxlifetime", "3600");
session_start();
$var = $_SESSION["authenticated"];
if(strcmp($var,'yes') !== 0){
header('Location: C:\xampp\htdocs\Edge\Authorise.php');
}
?>
Login Page
<?php
ini_set("session.cookie_lifetime", "0");
ini_set("session.gc_maxlifetime", "3600");
session_start();
include('Authorise.php');
echo "<center><h2>This site requires authentication.</h2>";
echo "<br><hr>";
if(isset($_POST['sig_response'])){
$resp = Duo::verifyResponse(get_cfg_var('duo_ikey'), get_cfg_var('duo_skey'), get_cfg_var('duo_akey'), $_POST['sig_response']);
if($resp != NULL){
header('Location: http://localhost:99/edge');
}
}
else if(isset($_POST['user']) && isset($_POST['pass'])){
if($_POST['user'] == get_cfg_var('duo_user') && $_POST['pass'] == get_cfg_var('duo_pass')) {
$sig_request = Duo::signRequest(get_cfg_var('duo_ikey'), get_cfg_var('duo_skey'), get_cfg_var('duo_akey'), $_POST['user']);
?>
<script src="Duo-Web-v1.bundled.min.js"></script>
<input type="hidden" id="duo_host" value="<?php echo get_cfg_var('duo_host') ; ?>">
<input type="hidden" id="duo_sig_request" value="<?php $_SESSION["authenticated"] = "yes"; echo $sig_request; ?>">
<script src="Duo-Init.js"></script>
<iframe id="duo_iframe" width="620" height="500" frameborder="0" allowtransparency="true" style="background: transparent;"></iframe>
<?php
}
}
else {
echo "<form action='duo.php' method='post'>";
echo "Username: <input type='text' name='user' /> <br />";
echo "Password: <input type='password' name='pass' /> <br />";
echo "<input type='submit' value='Submit' />";
echo "</form>";
}
?>
I got this code from elsewhere. Please can someone explain in more detail to me.
Thanks.

The request is not very clear, are you trying to learn what the code means? What certain functions mean? Or are you trying to get a fix?
Judging from what you wrote I will assume that you seek an explanation for the code:
ini_set changes the php configuration for the run time of the script, means it changes the configuration on the global level of the script.
session_start basically starts a session, or continues a current session, it is used for instance when dealing with sessions for login systems, to assign session variables afterwards (e.g $_SESSION["authenticated"])
strcmp returns FALSE if equal.
NOTE: !== should be changed to !=
You basically declared a condition that if $var is NOT equal to 'yes' then it would redirect to authorize.php via the header function.
You need to read more about the POST and GET methods, as there is a lot to explain and if you do not really know what you are doing, then it is best to read through, considering you are passing information through a form and using the post methods. There is a lot of information out there about these, including pros and cons, security details, it is best to get to know the language a little before dealing with these as well.
Best of luck!

Related

Storing value used in POST form in a PHP variable

I'm using a POST form that transfers data from one PHP file to another.. no issues there. However, I'm trying to store session data into a PHP variable.
<?php
if(!isset($_SESSION['login_user']))
{
session_start();
echo "<form action='../account.php' method='post'>";
echo "<p><b>Username: </b><input id='uname' type='username' name='uname' align='middle'></p>";
echo "<p><b>Password: </b><input id='pword' type='password' name='pword' align='middle'></p>";
echo "<p><input type='Submit' style='width:15%'></p>";
echo "</form>";
}
?>
I need the "uname" value to be stored as $_SESSION['login_user'] upon clicking submit, but this shouldn't prevent POSTing to the next page. How can I handle this?
session_start() should be initialized before anything you do in php
in your account.php initialize the session :
<?php
session_start();
$_SESSION['login_user'] = $_POST['uname'];
//rest of the stuff
?>
In account.php, do following assignment:
$_SESSION['login_user'] = $_POST['uname'];

php seems not to receive values from forms (post and get)

I'm trying to create a login and logout system. Everything works fine until I try to send hidden value (at the end) to log out. User would "submit" hidden value "logout" but it seems that the value is not send. I tried already different to approach this problem but either I am always getting errors message (but the code works) or I'm not getting errors message but it does not work.
<section>
<h2>Zaloguj się do systemu</h2>
<?php
//$username;
//$password;
if(empty($_SESSION['userpass']) && empty($_POST['pass'])){
//create a log in form if no one is log in
echo "
<form method='post' action='./indexLogin.php'>
<table>
<tr>
<td>Urzytkownik:</td>
<td><input type='text' name='name'/></td>
</tr>
<tr>
<td>Hasło:</td>
<td><input type='password' name='pass'/></td>
</tr>
</table>
<input type='submit' value='Wyślij'>
</form>
"; //end of echo
}
else if(empty($_SESSION['userpass']) && !empty($_POST['pass'])){
//echo the user name and his password
$userName = $_POST['name'];
$password = $_POST['pass'];
echo "Nastąpiło poprawne zalogowanie do systemu";
//save user password to session
$_SESSION['username'] = $userName;
$_SESSION['userpass'] = $password;
}
//problem starts here
else{
if($_POST['logout'] == true){
session_destroy();
echo "Nastąpiło poprawne wylogowanie z systemu";
}
else{
echo "Jesteś zalogowany jako: ".$_SESSION['username'];
echo "
<form method='post' action='./indexLogin.php'>
Do you want to log out?<br/>
<input type='hidden' name='logout' value='true'>
<input type='submit' value='Wyloguj'>
</form>
";
}
}
?>
when I use this code I get no error message but it does not work
//problem starts here
else{
if(!empty($_POST['pass'])){
//confirmation that log out was successful
//$_POST['logout'];
session_destroy();
echo "Nastąpiło poprawne wylogowanie z systemu";
}
else{
//form to log out
echo "Jesteś zalogowany jako: ".$_SESSION['username'];
echo "
<form method='post' action='./indexLogin.php'>
Czy chesz się wylogować?<br/>
<input type='hidden' name='logout' value='1'>
<input type='submit' value='Wyloguj'>
</form>
";
}
}
what I did as was was that I replaced post method with get. And what I found was that even if the value was in url it still did not work! I seemed that it never receive any value so it uses the last else.
First thing to check is that you actually have PHP >= 4.1 . In older PHP $_GET and $_POST just non-existent.
Second thing to check is actually print_r contents of your $_REQUEST (it is combination of $_GET and $_POST and $_COOKIE) and see if some data actually makes it to your script.
Third: I have executed your script on my host and ended up in "else if" branch. Clearly there no issue with your script but issue with the way your host handles requests. Are you on shared host? Some shared hosts have superglobals switched off intentionally and then you need to use $GLOBALS["_POST"] instead of $_POST
And of course use session_start()
actually your code seems to work, but you should enable your session with
session_start();
before your code. I was then able to submit the login credentials and to logout.
Cheers,

php, form using the same page after submittion

I'm wondering what's the easiest way to make let's say a form with user/pass and submit button with php but after you submit it goes back to the same page instead of going to another php page.
I'm thinking of if/else statement but a bit confused how to set it after lots tries but still not getting the result wanted
weird I did all those you guys said before I posted..but...>.<"
let's say just something simple like this...
but I also want to set if nothing is entered then sumbit is clicked there'll be an error....should be something easy but I don't know why I can't seem to figure it out
<?php
function userPass()
{
echo "<form method='post' action=" . $_SERVER['PHP_SELF'] . ">";
echo "<input type='text' name='user' /><br/>";
echo "<input type='text' name='pass' /><br/>";
echo "<input type='submit' value='Login' />";
}
if(empty($_POST["user"]))
{
userPass();
}
if(!(empty($_POST["user"])))
{
if($_POST["user"] == "comp")
{
echo "Welcome comp";
}
else
{
echo "Wrong user";
}
}
?>
The other answers are right; you only need to send the user back around to your current page in the "action" property. You can test to see if they did so using "isset".
Something that I'm surprised hasn't been mentioned yet is that your input is not being sanitized, and you're setting yourself up for disaster. Huge injection vulnerability in your action attribute:
$_SERVER['PHP_SELF']
If you don't sanitize this, then someone can just modify the URL that they see and your poor PHP script won't know any better than to process that as your SELF constant.
In other words, you absolutely must use an htmlspecialchars() function to html-encode that parameter. With that, your action should look more like htmlspecialchars($_SERVER['PHP_SELF']).
if current page is index.php, use index.php in form tag as value of action.
like this:
<form action="index.php" method="post">
</form>
u can check for submitted form by putting:
if(isset($_POST)){
...
}
at top of page
Just use below syntax
<form method="post" action="">
You can check whether post is set using isset() method.
<?php function userPass() {
echo "<form method='post' action=" . $_SERVER['PHP_SELF'] . ">";
echo "<input type='text' name='user' /><br/>";
echo "<input type='text' name='pass' /><br/>";
echo "<input type='submit' value='Login' />"; }
if(empty($_POST["user"]))
{
userPass();
}
*if(!(empty($_POST["user"])))*
{
if($_POST["user"] == "comp")
{
echo "Welcome comp";
}
else
{
echo "Wrong user";
}
}
?>
This part of your code is wrong, you should type : if(!empty($_POST["user"]))
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
This is exactly how you work with your form to reload the page when click the submit button inside this form.
ADDITIONAL:
Add required to all input you wanted to be required or check if it's empty.
This is a code that I created to control learning the required input fields satisfy the requirements. when this is so, the data will be sent to the database. if it does not meet the requirements, there will be a message may be shown at the top of the page
<?php
if (!isset($_POST['submitform'])) {
}
else
{
$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['mobile'] = $_POST['mobile'];
$_SESSION['telephone'] = $_POST['telephone'];
$_SESSION['place'] = $_POST['place'];
$_SESSION['street'] = $_POST['street'];
$_SESSION['housenumber'] = $_POST['housenumber'];
$_SESSION['gender'] = $_POST['gender'];
if (empty($_POST['firstname']) or empty($_POST['lastname']) or empty($_POST['email']) or empty($_POST['mobile'])or empty($_POST['telephone']) or empty($_POST['place'])
or empty($_POST['street']) or empty($_POST['housenumber']) or !isset($_POST['gender']))
{
echo "Sending denied";
}
else
{
require 'database.php';
header('Location: succes.php');
} ?>
I hope this is helpful information for you
this code will help you
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post">
or you could just do this:
<form action="" method="post">
Thank you ....
You can define in the form submission:
<form method=get action=index.php >
You can also leave action out altogether, and it will automatically post/get to that same file.
I think that all have missed the actual question, i.e. if there is a way to stay in the same page after submitting a form. The answer is NO. Once you submit a form -- whether you use the POST or GET method, and of course assuming that you are using $_SERVER['PHP_SELF'] or empty action, etc. -- a new page is opened automatically. This holds at least for PHP. (I have tried a lot of different ways using XAMPP.) I don't now about other scripting languages.

PHP How to check if text field matches var

Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.

How to create HTML button based on condition?

I am using following code:
<?PHP
if ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "")
echo "<input id='Submit' name='Submit' value='Submit' type='button'>";
else
echo "<input id='Update' name='Update' value='Update' type='button'>";
?>
Is this the correct way to render buttons?
If it works, then yes it's one correct method. Another way, using a ternary if statement might be:
<?PHP $button = $_SESSION['WorkMode'] == 'New'
|| $_SESSION['WorkMode'] == '' ? "Submit" : "Update"; ?>
<input id="<?php echo $button;?>" name="<?php echo $button;?>"
value="<?php echo $button;?>" type='button' />
Really it's a matter of personal preference and clarity. I prefer to write HTML as HTML (not as a PHP string) and echo variables into that HTML using PHP tags. Some might not like to use this method. If you have PHP short tags switched on you can even use <?=$button;?>
This is totally valid and readable.
If the number of lines of code is important to you, you could also do:
<?php $action = ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'])? "Submit" : "Update" %>
<input id="<?php echo $action ?>" name="<?php echo $action ?>" value="<?php echo $action ?>" type="button" />
My PHP is a bit rusty so I might be off on the syntax, but you get the idea.
If you use a framework such as cakephp or symphony you can use their helpers to generate buttons more easily.
Basically, yes you can do it this way. Depending on the size of your application and on your programming experience you might want to consider to start using a templating system (e.g. Smarty). This way you could seperate php code and html markup.
Best wishes,
Fabian
It should be
<?PHP
if ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "")
echo "<input id='Submit' name='Submit' value='Submit' type='button'/>";
else
echo "<input id='Update' name='Update' value='Update' type='button'/>";?>
The better way of doing this is using a template system, ou simply separate the layout code from logic:
view.php:
<?php if ($new): ?>
<input id='Submit' name='Submit' value='Submit' type='button'>
<?php else: ?>
<input id='Update' name='Update' value='Update' type='button'>
<?php endif; ?>
So, $new variable is sended by the logical code (controller):
controller.php:
$new = ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "");
include("view.php")
This is a better way to doing what you want :).
Don't forget that is a good practice to also support internacionalization on view.
Depending on the behaviour you want from your buttons, you might consider changing their type to submit.
EDIT
It seems from the responses that your code is functional. However, you say that the PHP code is coming out behind the buttons.
This implies to me that the file is not being parsed by the PHP parser.
RPK: Is your web server serving other PHP files correctly?

Categories