user authentication for all pages in wordpress website - php

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

Related

Redirect page after delete account in php

I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help

Php redirect after successful login

I'm having an issue with a simple verification file, it doesn't redirect to index page after successful login.
Basically the login.php file has the html form for login, the form calls auth.php file which already has the login data and decides if your login and password is correct or not. Now it should redirect to index.php after successful login but it doesn't , instead it just cleans up the form in the login.php file and you keep trying , BUT if you refresh the page ( after successful login ) you get auto redirected to index page.
Fixed! changed the code to something even simpler than that.
if($logindata[$_POST["username"]]==$_POST["password"])
This bit doesn't look correct; maybe you were looking for:
if($logindata[$_POST["password"]]==$_POST["password"])
Sometimes headers does not work well for some reasons, instead try to use a simple html redirect like this:
<?php
$usernames = array("user1", "user2");
$passwords = array("pass1", "pass2");
$page = "index.php";
for($i=0;$i<count($usernames);$i++){
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++) {
if ($usernames[$i] == $_POST["username"]) {
$found = 1;
}
}
if ($found == 0) {
$redirect_url = "./login.php?login_error=1"
}
if($logindata[$_POST["username"]]==$_POST["password"]) {
session_start();
$_SESSION["username"]=$_POST["username"];
$redirect_url = "./index.php"
}
else {
$redirect_url = "./login.php?login_error=2"
}
echo "<center><br><br><br><p>You will be redirected in about 2 seconds. If not, click this link: <a href='$redirect_url'>Back</a></p></center>";
?>
<html>
<head>
<meta http-equiv="refresh" content="2;url='<?php echo "$redirect_url"; ?>'/>
<title>Redirecting...</title>
</head>
</html>
<?php
exit;
?>
I presumed the redirect location is in the same folder of the php file. Adjust the var $redirect_url path of they aren't.

Redirect page when user is verified

i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.

How can I use .htpasswd across my entire site?

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...

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