I have an HTML page that I do not want to be available unless the login is successful. My login starts a session, however I don't know how to check for the session in the HTML and if the session exists I want to display the page, if not I want to display a unauthorised message. How can I do this?
You can't check for the session in the HTML per se you'd have to do it in PHP. Depending on how your page is built using PHP you could try putting something like this at the top of your HTML file:
<?php
if (!isset($_SESSION['my_login_var'])) {
echo 'Unauthorised';
exit();
}
?>
But you'd be far better off doing this earlier on in your PHP code, in which case you could use the header function to send the user to a proper 403 page.
UPDATE
Usually PHP does some processing before the HTML is outputted and the headers are sent to the connecting client, so you want to send a 403 header before that output happens. This could be in an included PHP file that is run before the HTML is built, or even in the HTML file itself if no other content has been outputted before the script reaches that point.
You can make a small adjustment to the code above to send a 403 header and 'properly' deny access to the page:
<?php
if (!isset($_SESSION['my_login_var'])) {
header('HTTP/1.1 403 Forbidden');
exit();
}
?>
You're going to need to look up PHP sessions. See http://us.php.net/manual/en/function.session-start.php for PHP session_start() documentation.
Basically you will need to do session_start(). If the login is successful, set a session variable like $_SESSION['logged_in'] = true;. Then do some logic on your page and redirect/display message depending on the result.
You should attempt something and come back and ask a more specific question if you have problems.
Related
I have a framework and I think I'm following something like the MVC pattern: A framework (the model) an index page that controls the input (the controller) and the views pages (that are included inside main.php/the main html)
I read a lot about structure and logics, to write a good application. I read many comments like "Why are you outputting anything if all you are going to do is try and redirect the user to another page?". Well the answer is, the most common case: redirect after the user successfully logged in. Do I need to print something? Of course, the whole main page with a login form/post. How I'm supposed to do that redirection??
So I'm a bit confused about logics and structure of the application. How do you store all the output and do the header redirection without printing anything?
I was thinking about using javascript to do the redirection but I also read comments saying; "if you write good code (following a good logic/structre), you won't need to use hacks like javascript redirection". How is that even possible?
Because the php output_buffering should not be enabled.
I have the output_buffering enabled, and I can use header (after output) without any problem. If I use the javascript redirection the whole page reloads, but using header it just loads the content (the views content that are included in main.php).
So how do you do this without output_buffering?
If you want to redirect to a success page AND pass messages - say, after a successful login - an easy solution is to use "flash" sessions, where you store a message in a SESSION and then, as soon as it's used, you discard it. You don't need to sore anything in the output buffer for this.
This is a very basic example, but should give you the gist of it.
login.php
if($login_successful) {
// put your message in the session
$_SESSION['message'] = 'Login Successful';
// redirect to the success page
header('location: success.php');
}
success.php
<?php
session_start();
// check if $_SESSION['message'] exists
if(isset($_SESSION['message'])) {
// print the message
echo $_SESSION['message'];
// clear the session
$_SESSION['message'] = null;
}
Looks like you are mixing up some things here. What you are talking about are actually two different requests. Either the user wants to view the main page, or he wants to log in using that form on your main page. In your index.php you would have something like this (pseudocode):
if (isLoginRequest) {
// user wants to log in
if( validateLogin($loginFormData) ) {
redirect('successful');
} else {
displayLoginError();
}
} else {
// user wants to view main page
echo main.html
}
Update to answer the question in the comments: The better alternative would be to leave your form validation stuff in login.php and refer to that in your login form <form action="login.php" .... Then in your login.php you would have something like this:
if (loginSuccessful) {
redirect('success.php');
// no need to call die() or whatever
} else {
setFlashMessage('Login failed'); // set a flash message like timgavin described
redirect('index.php')
// also no die() or whatever
}
index.php then is responsible to display your main page and, if set, rendering the flash message from a failed login attempt.
Simple solution: Move the login post script from login.php to another file (login_post.php). The same for other scripts using header() after dom output. (no need to change the form action="")
In index.php:
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
//some more security checks like esc_url() (non-php function)
if ($url == '/login') {
include('header_pages/login_post.php');
}
// all these includes before including main.php
// where views pages are included and the DOM output starts
Since header() is inside the post script, no more headers already sent errors (And output_buffering off, of course).
Same for logout page that is currently being included inside main.php
Thanks to the other answers, they helped me finding this solution.
i'm new to php, and i'm having a hard time establishing proper session mgmt. controls to prevent unauthorized access to a specific section of my site. I'll give an example...
myimaginarysite.com/application/index.php has a form to auth the user and it will redirect you to 'portal.php' after successful auth. 'portal.php' will check for a valid session as part of an include and then based on that it will either send u back to authenticate via header("location....) or just load up the HTML content. Now, if an unauthorized user hits 'portal.php' directly.. because they won't have a valid session.. they will get redirected back to the index, however, if you proxy the traffic you will see that the whole HTML content for 'portal.php' will actually be sent to the client (although not displayed on the browser) before redirecting back to the login page. So my question is... am I missing something, is there a way to make sure the HTML content is suppressed and is not sent to the client??
below is a snippet of my code for 'portal.php'
<?php
include "includes/checksession.php";
?>
<html>
<body>
Who Am I ??
<br></br>
Log Off
.....bunch of authenticated content.....
</body>
</html>
You need to stop script execution after sending the redirect headers with die() or exit(). Header redirection only sets the http headers, otherwise the page content is the same unless you instruct it otherwise.
Stopping script execution, like Juhana suggested, is probably the easiest solution for now, but there are other possibilities of course. You can just make the output conditional:
<?php
if (checkSession())
{
// redirect to login page
}
else
{
// output HTML.
}
If your site grows larger, it will probably (hopefully) also be more structured. If so, it might be easier to include other page fragments. So your code could look like this at first:
if (!checkSession())
{
include 'loginpage.php';
}
else
{
include 'portalpage.php';
}
And eventually maybe:
if (!checkSession())
{
ApplicationContext.setController(new LoginPageController());
}
Whatever the case, exit works fine and may be useful, especially for a case like this, but it terminates your script quite abrubtly, so it might get in the way of other processes that you may want to include, like debug-output or logging, profiling, and stuff like that.
I am trying to write a page in php which shows a loading message while it does some processing and then auto redirects to another page
<?php
//show a loading message - this is the bit I need help with
// do some processing - don't need help with this bit
header("Location: http://www.mysite.com/mynextpage.php");
exit;
?>
I can't use echo or javascript otherwise I get a "Cannot modify header information - headers already sent" error when the page executes.
Any clues?
First of all, you mustn't use any header change after outputing some data, that is why you get the error above.
Another way, use header redirections by refreshing page on next page:
<?php
header('Refresh: 5; url=http://www.mysite.com/mynextpage.php' );
echo 'Wait 5 sec then redirected';
Note:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Best way is to use ajax requests. Via javascript you should show the loading element, perform the request, on success redirect on target page
Using java script to redirect after the processing has finished seems to be the way to go.
I'm using
<script type="text/javascript">
window.location="http://www.mysite.com/mynextpage.php";
</script>
at the end of the page and it's working
i am doing a simple job. i am calling a ajax function like call_ajax(file, container_id) from the file just as parent.php.
which process the page file and get reponse to the desired container_id.
here file is file1.php. now on file1.php is running successfully and get back response.
but the problem is that when i going through some checking just as login comfirm i have to redirect to the login page such as login.php from file1.php and stop transfer response to the parent.php.
i am using header function of php to transfer but yes it transfer and get response as login page in the container id. I know that its correct as by ajax behaviour what ever target file get content return as response. but what is the solution of my problem. i would not like found my login page in container_id and want to load login page from file1.php.
Well i dont really know how you did your pages but for me i would use a meta tag. It best used if the person is not logged in and access the page . this is the code i used. So place this in your php coding so when ajax calls the files it will run through the php files and when it hits this line it will "refresh" another page and exit the main one
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=Login.php">';
exit;
The person will be redirected immediately. And if you can Please Post your codes!
You Can use Some thing like this to Change your location with in an ajax call.
echo "script top.location='login.php'; script ";
exit;
im building my first dynamic site. i have an index.php that based on whether the following session variable is true or false
if($_SESSION['loggedIn'])
{
include 'logged-in/logged-in.php';
}
else{
include 'not-logged-in/not-logged-in.php';
}
the not-logged-in.php displays some forms so you can either login or register this calls a function within an included php file. if the login() function validates via login via mysql it sets
$_SESSION['loggedIn'] = 1;
header("Location: ../index.php");
i however get this error...
Warning: Cannot modify header information - headers already sent by (output started at //index.php:8) in //not-logged-in/not-logged-in.php on line 5
sorry i '*' out the url to keep my project private.
i come from a simple graphics programming background and so this is all new to me. any tips or advice would be greatly appreciated.
This error is caused by having something output to the browser, either with echo, print, etc. before you call the header().
Personally I wouldn't use a session variable to store whether the user is logged in or not because you may want to disable a user, and if they're already logged in they will still have access until their session expires. I like to store the username and hashed password in the session and then re-run the login procedure, using these details, for each page.
this error happens when you're trying to send an http header (like the Location in you code) after there is some kind of output. Check your code and verify your are not sending intentionally any output before sending this header (or even the session_start()). also, if you're using the php closing tags, be sure to not have a single space or newline after it, because it counts as output