URL rewriting, same URL across multiple PHP files - php

Hey so I have create a login system to a website and I wish to have this login appear when I type in my address. When I have typed in details and logged in, I wish to be redirected to another PHP file, but with the same address.... this way, All I need to do is type in my address if I am allready logged in and I will go to the site which requires login.
I have made a transaction happen identifing if the session is created, if it is, it redirects me to another page, but also to another URL. I tried googleing it, but couldn't find anything exact and straight forward.
Currently:
Login page:
www.example.com
Member page:
www.example.com/members
What I wish for:
Login page:
www.example.com
Member page:
www.example.com

The program structure should look like this.
index.php
if (user is logged in)
display dashoard
else
display login page
Since you are using PHP, make use of session functions. Thus, URL rewriting is no longer necessary.
Update
Assuming if you have file structure in PHP like this:
- index.php
- login.php
+ template
- login.php
- dashboard.php
You can do the following structure in index.php file.
define('IN_FILE', true);
if (isset($_SESSION['user'])) {
require 'template/dashboard.php';
} else {
require 'template/login.php';
}
In template/dashboard.php
if (!defined('IN_FILE')) {
exit;
}
// Then your HTML, PHP and whatnot
And in login.php
if (!isset($_SESSION['user'])) {
require 'template/login.php';
} else {
header('Location: index.php');
}
Change the code according to your needs.

This can be achieved using several approaches.
a) Use session to determine the current page, so if a user click on a link, create a session store the value and on page load read the session data and include the file accordingly.
b) Use URL parameter to determine the page (this is the most common approach). for example in index.php you can add more parameters like index.php?page=somepage and by reading the value using $_GET and including the PHP file accordingly.
There are some more way to achieve what you want to, for instance using javascript/jQuery this is possible.

Related

Redirect to index.php when directly access any php page in root folder

there is one file called reports.php . if someone directly accessed 192.168.1.1/reports.php it should redirect to index.php
prevent the direct access from users to reports.php
through step by step procedure only they can reach reports.php
For а case you described, you need to specify a condition in the reports.php file that results in deciding to do a redirect or execute your business logic. For example, if you use get parameters you can do this:
if (!isset($_GET["step"])) {
// do redirect
}
// do business logic
The example uses the query parameter step.
You can also use the session extension built-in to php using the global variable $_SESSION
You can see how to redirect here: How do I make a redirect in PHP?
you can use sessions,
https://www.php.net/manual/en/book.session.php
on your index.php start session with name and check on everyother page if the session exist, if not redirect to index.php

redirection without reloading the whole page

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.

How to prevent direct access to php pages through URL

I have index.php that include pages like
<?php
define('MyConst', TRUE);
include_once('template/header.php');
if (!empty($_GET['action'])) {
$action = $_GET['action'];
$action = basename($action);
include("template/$action.php");
} else {
include("template/main.php");
}
include_once('template/footer.php');
?>
With in a template directory I have main.php which has link to other pages like page1.php, page2.php.
Goto page 1
Goto page 2
How could I prevent users form accessing pages directly typing "http://mydomain.com/?action=page1" on the URL? And redirect them to main.php if they have done it?
You can not. What you want is simply not possible.
For the server side there is no way to know whether an URL is typed or clicked.
If I understand correctly, the thing you want is to prevent the user to access http://example.org/?action=page1 unless they came from http://example.org/?action=main. To do that, you must be able to detect whether they came from http://example.org/?action=main. The safest way to do that is to generate some random value that you associate to the users when they access http://example.org/?action=main and to check whether there is a correct value associated to the users when they want to access http://example.org/?action=page1. If not, they tried to access that page directly.
Check for HTTP_REFERER and if it is not pointing to right values (like your meny page) then redirect user.
Maybe you can try this, On your index.php :
session_start();
if(! isset($_GET['action']))
{
$_SESSION['pageAccess'] = true; # Set the key whatever you want
}
then under that script (we need that session_start() used twice) :
if(isset($_GET['action']))
{
if(! isset($_SESSION['pageAccess']) || ! $_SESSION['pageAccess'])
exit('There is no direct access allowed.');
}
Hope this help, have a nice day.
As per your Question:
There are two approaches that you can follow:
Use HTTP_REFFRER and check on desired page if User is coming from the page u wanted. IF he is accessing the direct URL then show him error page.
Use $_SESSION but this approach can be harmful as SESSION will always be there untill browser / instance closed.
So better to go for 1st approach.
And also as per Pehaa, you can not check id URL is typed

PHP restriction to pages

I'm having a problem with a web site I'm creating so I want to know:
How can I prevent that an unauthenticated user could acces the website by doing something like:
Website.com/content
It suppose that unauthenticated user cannot acces the page content, but if they write it directly in the address bar they can see the content. So how can I prevent this to happen? How can make to only allow authenticated users see the content when they write it in the address bar?
I want to do this using cookies... by the way I already implemented the authentication using the database.
place a check
<?
if (!authorized()) { # substitite with your own authorize function
header('401 Unauthorized', 401);
die('You are not authorized!');
}
?>
on the page.
UPDATE: place it before you start output. If you are not using ob_start, that means at the top of your page.
Lets say you have a page for error message "website.com/unauthorize"
and a inlcude file, "check_auth.php", while user logged in, validate user and pass and create a cookie "userLogin" with value 0 or 1.
1 to represent successful login, 0 for invalid id/pass.
and include check_auth.php in every file in which you want restrictions.
include "check_auth.php";
and in this file write:
<?php
if ( ! isset($_COOKIE['userLogin']) && $_COOKIE['userLogin'] != 1 )
{
header("Location: website.com/unauthorize");
}
this will check for login state and will redirect unauthorize users to error page. include this file in all the pages on top where you require restriction.
I'm normally an asp.net developer. And in asp.net we have a master page, It's like a template you can put other content pages into.
If PHP have something similar (include?) Then you could make a function that checks if a user is supposed to be where he is, and if not redirect him to the login page. And include that on all the not-accessible pages.

How can I redirect page without changing URL with PHP?

I want the following:
After logging in, A user will have assigned session variable, and the logging in page will be refreshed. The URL should not be changed at all but the page would be different.
I don't know the idea of doing that.
I know that Facebook does it. (Logging in, and logged in page url is same but different page)
I'm using nginx, PHP.
Should I some sort of rewrite URL? or some configuration on nginx? Or should I manipulate header with php in some way? then how to?
just do a conditional on an include. In general if the session does not exist you say something like
<?
if (!isset($_SESSION['user'])){ include_once("login_please.php"); exit(); }
..actual page content
?>
Use PHP to decide what to show (or which page to include) based on the session variable.
if ($_SESSION['form_submitted'] == true) {
include('content.php');
}
else include('form.php');

Categories