Im Using the following code to validate (poorly, I know) a form's $_POST[]ed data. How can I pass $auth onto the new page so I can print it for the user? (short of using my-account.php?auth=You Must......)
if (!$_POST['supportarea'] || !$_POST['supportbody']) {
$auth = 'You must provide some information if we are ever to help you with your support ticket';
header('Location: ../pages/my-account.php');
}
Thanks. Alex.
You should use the session. In your script:
session_start();
$_SESSION['flash'] = 'You must ...';
In the my-account.php script:
session_start();
if (!empty($_SESSION['flash'])) {
$flash_message = htmlspecialchars($_SESSION['flash']);
unset($_SESSION['flash']);
} else {
$flash_message = null;
}
Then, if !empty($flash_message), show it to the user.
Related
I'm sorry, I followed WikiHow steps (link is down there) and I made everything but here is the problem:
My index.php contains password input.
if(isset($_POST['login']))
{
require('session.class.php');
if(hash('sha256', $_POST['pass']) == hash('sha256', 'password123'))
{
$session = new session();
$session->start_session('_s', false);
$_SESSION['namesession'] = 'something';
header(location: /mama.php);
}
else
{
echo "<font color='#FF0000'>Wrong password!</font>";
}
}
I don't understand how to put session check on other pages. Other words:
How to put inside if password is correct, you can stay on mama.php page..
http://www.wikihow.com/Create-a-Secure-Session-Management-System-in-PHP-and-MySQL#Create_session.class.php_file_sub
When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
So if you want to check the post data put the if statement after the session_start().
I have been developing the following php script (+ sqlite database) to create a login for my web.
Up to now I had used just one PHP file, but now I want to use different files for login and protected contents, I mean, I used to have all my web in one file php (contents and password script were together) but now I want to detach it in different php files (one for the login, login.php, and other phps protected: index.php, calendar.php...)
I used this code to password-protect php content:
<?php require_once "Login.php"; ?>
but it doesn't seem to work: it displays the form to login next to the content I wanted to protect.
This is the php script I'm using as login.php:
<?php
$db = new PDO('sqlite:data.db');
session_start();
if (isset($_GET['logout'])) {
unset($_SESSION['pass']);
header('location: index.php');
exit();
}
if (isset($_SESSION['timeout'])) {
if ($_SESSION['timeout'] + 4 < time()) {
session_destroy();
}
}
if (!empty($_POST['pass'])) {
$result = $db->query("SELECT user,password FROM users");
foreach ($result as $row) {
if (password_verify($_POST['pass'], $row['password'])) {
echo "Welcome! You're logged in " . $row['user'] . "! <a href='index.php?logout=true'>logout</a>";
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['timeout'] = time();
}
}
}
if (empty($_SESSION['pass'])) {
echo '<form method="POST" action=""><input type="password" name="pass"><form>';
}
?>
MY QUESTION IS: How can I use my php script to protect different files?Is there any way to embed a logout link too?
One way is to store a token in session variables when a user logs in. Confirm the token is there on each page, if it isn't redirect the user to the login page. For example assert_login.php:
<?php
session_start();
if('' == $_SESSION['token']) {
header("Location: login.php");
exit();
}
?>
Then, in the PHP at the top of each of your pages:
<?php
require('assert_login.php');
?>
You can also clear the session variable on logout, logout.php for example:
<?php
require('assert_login.php'); // has session_start() already
$_SESSION['token'] = ''; // empty the token
unset($_SESSION['token']); // belt and suspenders
header("Location: login.php");
exit();
?>
I was also going through same issue & the way I solved it:
PSEUDO CODE:
PHP SESSION START
if(isset(GET(logout){
SetLogout();
die()}
$redirect=false
if not session[auth] exists
if SERVER REQUEST METHOD IS POST
$redirect=true;
if POST(username) && POST(pass) exists
Sanitize both of them & assign to $user& $pass
if user == "John" && $pass == "secret"
Go To SetLogin();
else{
Go To SetLogout();
echo "Wrong Username or Password"
drawlogin();
die();}
} //user pass comparing ends
} //Server method is NOT POST, so maybe it is GET.
//Do nothing, let the control pass to next lines.
}//SESSION(auth) does not exists, so ask user to login
else {
drawlogin();
}
//Post-Redirect-Get
if ($redirect)
redirect header to this same page, with 301
die()
// Secret Content here.
function SetLogin($user){
$SESSION(auth) = TRUE;}
function SetLogout($user){
if SESSION(auth) exists
unset($SESSION(auth))
redirect back with 301, without query string //shake ?logout
}
function drawlogin(){
echo all the HTML for Login Form
What it does is, it checks various things/variables, and if all passes, the control passes to Secret Content.
Save it as pw.php, & include it on top of any file you want to protect. Logout can be triggered by Logout
Note that this is just a pseudo code, typed on a tablet. I will try to update it with actual version. It is not checked for errors. Use all standard PHP Security precautions..
I have a login page and I want to achieve this effect:
If user fails to login, display error message. After user presses refresh button, the error message should not be visible anymore.
I dont want to pass $_GET variable, for example index?page=login$failure. I want to do this in invisible in url way.
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
Now how do I say for my form, that something before redirect went bad without addint it with $_GET?
Update. So using sessions, can I do like this?
<?php
if(isset($_POST['submit_form_register'])) {
...
if($login === false) {
$_SESSION['is_form_error'] = true;
$user->go_to('index.php?page=login'); //Redirects back, cleaning the $_POST data.
}
..
}
?>
And for HTML output:
<?php if(isset($_SESSION['is_form_error']) and ($_SESSION['is_form_error'] === true)) { ?>
<div>Your email or credential is invalid.</div>
<?php } unset($_SESSION['is_form_error']); ?>
But this one doesnt work for me. I bet its because something wrong with unset. Any tips?
SOLVED: Didn't have exit; after header(); in $user->go_to($url);
You could use Session for show and hide errors
When user enter wrong user/pass you set error session and use it in view and then delete session(after showed)
`//Set Session
if (!$success) {
$_SESSION['login_error'] = 1;
}
//show
if (isset($_SESSION['login_error'])) {
echo "Invalid Username/Password";
unset($_SESSION['login_error']);
}`
Don't forget to start code with session_start();
The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.
I have an installation of Codeigniter, IonAuth + Hybridauth which I am reworking so my users can choose their own username instead of generating one using the first and last names returned by facebook.
So in my code below I check to see if a username was posted, if not I want to load the choose_username view but for some reason the view is not loading and its completely skipping that section which is why I added die('Why no view')
Update: This first piece of code runs fine in a new controller
Checkout the code here:
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
Longer version:
function login_provider($provider = '')
{
if(empty($provider)) redirect();
try
{
// create an instance for Hybridauth with the configuration file
$this->load->library('HybridAuthLib');
if ($this->hybridauthlib->serviceEnabled($provider))
{
// try to authenticate the selected $provider
$service = $this->hybridauthlib->authenticate($provider);
if ($service->isUserConnected())
{
// grab the user profile
$user_profile = $service->getUserProfile();
////////////
//var_dump($user_profile);
//die();
////////////
$provider_uid = $user_profile->identifier;
if($this->ion_auth->login_by_provider($provider,$provider_uid))
{
$data['user_profile'] = $this->ion_auth->user_by_provider();
//$this->load->view('auth/user_profile',$data);
$user = $this->ion_auth->user()->row();
//Redirect to custom subdomain
$url = explode('://',site_url());
if (strpos(site_url(),$user->username) !== false) {
redirect($url[0].'://'.str_replace('www','',$url[1]).'dashboard','refresh');
}
else{
redirect($url[0].'://'.$user->username.str_replace('www','',$url[1]).'dashboard');
};
}
else
{ // if authentication does not exist and email is not in use, then we create a new user
//Check if username was posted
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
So when I run the above code, all i get is a blank page with: Why no view.
As above, usually when I run into this sort of issue it's from a bug in the view code.
Also, I don't know what, is actually being passed by this post in the event of there not being username data but you might want to also be checking for an empty value for username. This is probably not the issue but it would be good to confirm that the initial if is evaluating the way you expect.