How can I use .htpasswd across my entire site? - php

How can I use my .htpasswd login "session" all across my site?
I want to be able to login to via /admin.php using my .htpasswd account, then display certain admin features on other pages, ex. /browse.php, if the admin is logged in.
Here's what I tried, which didn't work.
if (isset($_SERVER["PHP_AUTH_USER"]) && $_SERVER["PHP_AUTH_USER"] == "admin") {
$reportLink = "Report Dead Link?";
if($_GET["report"] == $site_id && preg_match("/^\d+$/", $site_id) && $_SERVER["PHP_AUTH_USER"] == "admin") {
mysql_query("UPDATE `websites` SET `status` = '4' WHERE `id` = '$site_id'") or die(mysql_error());
header("Location: browse.php");
} else {
header("Location: anotherpage.php");
}
}

Ensure that your other pages are password protected under the same scheme, then the browser will re-submit the auth details for each one.
You know, PHP sessions are far more flexible for this kind of thing...

Related

PHP - session redirecting me to infinite login.php page

So I have a header included in all of my website pages (including login.php) and in that header I placed the condition that if $_SESSION['logged'] is not set and not blank, it automatically redirects to login.php.
if(!(isset($_SESSION['logged']) && $_SESSION['logged'] != '')) {
redirect_to(url_for('/login.php'));
}
THE PROBLEM is that in my login.php file I don't have $_SESSION['logged'] set because it only sets after the user clicks on login and the file login.php redirects to itself infinite times before the page loads:
if($password == $user['hashed_password']) {
$_SESSION['logged'] = $username;
redirect_to(url_for('/staff/index.php'));
}
The first code is in my header file and the second one in my login file. Login file includes header file.
Personally, I wouldnt include the redirect check on the login page at all, but if you do, you should avoid triggering the redirect condition when the user is already on the login page, for example, something like this should work:
$currentPage = basename($_SERVER['PHP_SELF']);
if($currentPage !== 'login.php' && empty($_SESSION['logged'])) {
redirect_to(url_for('/login.php'));
}
// If they hit the login page but are already logged in, or submitted
// a valid password, log them in
// might need to adjust the "already logged in logic" for you use case
if(
($currentPage === 'login.php' && !empty($_SESSION['logged'])) ||
$password == $user['hashed_password']
) {
$_SESSION['logged'] = $username;
redirect_to(url_for('/staff/index.php'));
}

Prevent User from accessing admin.php

I'm having a problem preventing regular users from accessing my admin.php page.
I've set in the database it so that users have a type (it's a boolean so either 0 = admin or 1 = normal user)
At the top of my admin.php page I have
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
}
elseif(!isset($_SESSION['type']) && $_SESSION['type'] !== 0) {
header('Location: profile.php');
exit;
}
?>
I originally had the last piece of code as:
elseif(!isset($_SESSION['type']) || $_SESSION['type'] !== 0) {
header('Location: profile.php');
exit;
but this would prevent all users, both admin or normal, from accessing the admin page. I'm not sure how to proceed.
Edit: I'm a novice at PHP and still a student so I'm not 100% familiar with PHP.
Correct code is:
// Check if the user is logged in
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] == true){ // if login
if(!isset($_SESSION['type']) && $_SESSION['type'] == 0){ //if admin (type == 0)
header('Location: profile.php');
}
else{ //if not admin (type !== 0)
header('send somewhere else');
}
}
else { // else not login
header('Location: login.php');
exit;
}
Since you're a novice at PHP, what I'm going to recommend is not an answer to fix your code (I don't see any obvious problem with it), but instead how to set up your development environment so that you can easily see what the problem is yourself.
There are two main options:
1.) (Best option) Setup Xdebug and an IDE so that you can debug your code in real time, line by line
2.) Use echo to output information to the page
Option #1
This is the best option, and I highly recommend you learn how to debug PHP line by line, as soon as you can. Xdebug is the most popular debugger for PHP; you'll need to set that up and install it. Then you'll need an IDE that supports debugging. I recommend PHPStorm if you have the funds, or Sublime Text if you need a free option.
Option #2
Instead of having your code redirect, have it output information, like this:
$loggedIn = isset($_SESSION["loggedin"]);
echo $loggedIn;
$type = $_SESSION['type'];
echo $type;
This is kind of the "poor mans" debugging. It allows you to see printed to the page, what the values of variable are. Once you know what the values are, you'll easily be able to figure out why your code isn't working. You can even then do things like this:
elseif(!isset($_SESSION['type']) && $_SESSION['type'] !== 0) {
echo "this will take you to profile.php";
}

Check role of user logged in (PHP)

first, I have searched for a question that is the same with mine, unfortunately I can't understand the answers. It says use Auth, etc... bla bla bla. I only know basics so far.
So here is my question: how to check the user currently logged in and its role?
I thought I could do it so easily, actually I did, but the user of the site I'm building should only be one. lol. I have two columns named session and membership. Anyway, my code is written below (It is definitely wrong, I just realized it this 2AM in the morning. It would 100% work if the user of the side is again only one.
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
header("Location: http://localhost/se/");
}
//if(!empty($_SESSION['user']) )
else
{
//This following codes are for checking the session in DB
$query = "
SELECT
id,
password,
emailAddress,
membership
FROM memberlist
WHERE
session = :var_val
";
// The parameter values
$query_params = array(
':var_val' => 'True'
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if ( $row['membership'] == 'Officer' || $row['membership'] == 'Member' )
{
header("Location: http://localhost/memberdir/index.php");
}
}
If a user's membership == 1, then go to admin directory.
else go to members directory.
Please help :(
To start a user session:
session_start();
To add parameters to that session:
$_SESSION['parameter'] = $parameter;
To get that parameter:
$getParameter = $_SESSION['parameter'];
So make sure you put session_start(); before any output to the page (before you print anything):
if ( $row['membership'] == 'Officer' || $row['membership'] == 'Member' )
{
session_start();
$_SESSION['membership'] = $row['membership'];
include('memberdir/index.php');
//or header("Location: http://localhost/memberdir/index.php");
}
So in your member file that you show a particular user (or only one user, doesn't make a difference), you check that the session parameter exists and what to do with it:
if (isset($_SESSION['membership'])) {
//membership parameter is set
if($_SESSION['membership'] == 'Officer') {
echo "Hey, your membership is Officer, here is your page";
} else if ($_SESSION['membership'] == 'Member') {
echo "Hey your membership is Member, here is your page";
}
}
This should help you understand the basics and you can go from there.
when the user login success you can do like this:
if(login success)
{
$_SESSION['user']=array('id'=>$id,
'emailAddress'=>$emailAddress,
'membership'=>$membership);//the three values are selected from database when login in
}else
{
// do some thing
}
then when you check the user ,you can use:
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
header("Location: http://localhost/se/");
}else
{
//get user info from session
}

user authentication for all pages in wordpress website

I would like to to have a wordpress website for authorized users only. I was thinking to add custom php code to my theme's header file that checks if a specific user is authorized to access the page and if not users are redirected to a custom login page. I am also thinking of adding a new table to my database for user information. Is there a plugin that does that for me? I couldn't find any.
Apply basic authentication to the site's folder where the wordpress site is.
Create a .htaccess file in the folder like this (but using your own path and username):
AuthUserFile /home/YOURACCOUNT/public_html/wordpress/.htpasswd
AuthGroupFile /dev/null
AuthName "Authentication"
AuthType Basic
<LIMIT POST GET>
require valid-user YOURUSERNAME
</LIMIT>
Then create a .htpasswd file like this:
YOURUSERNAME:YOURPASSWORD_AS_MD5_ENCRYPTION
To convert your password to MD5 encryption go here:
http://hash.online-convert.com/apache-htpasswd
Well, with some nasty hacking I was able to work it out.
In my theme's header.php file I added the following lines of code to the top:
if(session_id() == '') {
session_start();
}
if (!$_SESSION['authenticated']) {
header('Location: '.get_site_url().'/login.php');
}
I created a custom login.php file in my project's root folder containing a simple login form, posting its data to another custom file "webservice.php" with the following lines of code:
//webservice.php
<?php
if(session_id() == '') {
session_start();
}
$username = $_POST['username'] ? $_POST['username'] : '';
$password = $_POST['password'] ? $_POST['password'] : '';
if ($password && $username) {
$response = file_get_contents("http://example.com/api/Accounts?username=".$username."&password=".$password);
$json = json_decode($response);
if ($json->{'Status'} == "Success") {
$_SESSION['authenticated'] = true;
echo "<META http-equiv=\"refresh\" content=\"0;URL=http://example.com/\">";
}
else {
$_SESSION['authenticated'] = false;
echo "<META http-equiv=\"refresh\" content=\"0;URL=http://example.com/login.php?incorrect=yes\">";
}
}
else {
echo "<META http-equiv=\"refresh\" content=\"0;URL=http://example.com/\">";
}
Yet, in another custom file(logout.php) I only unset my session variable:
<?php
if(session_id() == '') {
session_start();
}
if ($_SESSION['authenticated']) {
$_SESSION['authenticated'] = false;
echo "<META http-equiv=\"refresh\" content=\"0;URL=http://example.com/\">";
}
?>
I would love to know my solution's disadvantages...
Based on your additional comments try a plugin with wordpress to make the work easy on you.
https://wordpress.org/plugins/tags/user-registration

Block access based on SESSION

I am working on a user based website. So, I have different sections for different users. I want that if the session username is "Rock", he shouldn't be able to access other user's profile say "Gray".
So,
if $_session['username']=="rock"
{
//BLOCK ACCESS TO OTHER FILES IN FOLDER PLACED IN DIRECTORY
}
How do I do that?
Thank you
If you have multiple users you can't hard-code this type of thing.
Assuming your using a database...
// Comes from database
$username = $row['username'];
// Check session
if ($username !== $_SESSION['username']) {
header("Location: /access/denied/page/");
exit();
}
On gray's page you could have:
if($_SESSION['username'] != 'gray'){
header('Location: http://www.goal.com/');
exit;
}
If you want to allow certain people to access gray's page you could have an array with the people that can access it...
$allowed = array('bob', 'james');
if(!in_array($_SESSION['username'], $allowed)){
header('Location: http://www.goal.com/');
exit;
}
Or the other way around, if you only want to deny certain people access you could have.
$blocked = array('rock', 'pop');
if(in_array($_SESSION['username'], $blocked)){
header('Location: http://www.goal.com/');
exit;
}

Categories