change admin password (need to make form) - php

i make the admin panel and have a problem.
need some help to make form for change password in ac-config.php file.
need form for change the adminpassword
$adminpass = "adminpassword";
thankyou
wait for useaful help.
ac-config.php
<?php
//Admin Username and password
$adminuser = "admin";
$adminpass = "adminpassword";
//Error message variables
$not_logged_in_message_error_message = "Error<br><br>You Are not logged in. Go back and try again!<br><br>";
$incorrect_error_message = "Error<br><br>You have entered the incorrect username and/or password, please go back and try again!<br><br>";
$no_pass_or_user_error_message = "Error<br><br>You have either not entered a password or a username, please go back and try again!<br><br>";
//The first page you want the script to go to after creating those cookies (this page must include the validating code as seen in admin1.php)
$first_page = "ac-admin.php";
?>
that is my login verify
ac-login.php
<?php
$formuser = $_POST["formuser"];
$formpass = $_POST["formpass"];
$formpass = md5($formpass);
if($formuser && $formpass) {
setcookie ("cookuser");
setcookie ("cookpass");
setcookie ("cookuser", $formuser);
setcookie ("cookpass", $formpass);
header("Location: ac-admin.php");
}
else {
include("ac-config.php");
echo($no_pass_or_user_error_message);
}
?>
ac-admin.php
<link href="css.css" rel="stylesheet" type="text/css" />
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Admin</title>
</head>
<body>
<div id="content">
<div id="logo"></div>
<?php include("nav.php"); ?>
<?php
include("ac-config.php");
$cookuser = $_COOKIE["cookuser"];
$cookpass = $_COOKIE["cookpass"];
$adminpass = md5($adminpass);
$moderatorpass = md5($moderatorpass);
if($cookuser && $cookpass) {
if(($cookuser == $adminuser || $cookuser == $moderatoruser) && ($cookpass == $adminpass || $cookpass == $moderatorpass)){
//Any protected stuff you want goes in here!
echo'<green>Successfully logged in!</green><br /><br />';
}
else{
echo($incorrect_error_message);
}
}
else{
echo($not_logged_in_message_error_message);
}
?>
This is Admin Page<br />
Anything want can place here<br />
<div id="footer">CopyRight 2011 - All Rights Reserved</div>
</div>
</body>
</html>

this what you are doing here is what we call "hard coded" passwords into the code, try reading some more on how to use databases or file system, then you can change your password dynamically;

Create another file, which we will use to contain a hashed version of your password. (As this is in another file, you can read/write/edit it as you wish without taking a chance of killing the PHP script which is working with it.)
Create a file "_something_random.txt"
Into that file, paste the following (and only the following - no new lines, or spaces, or anything):
11982574c05624fd4946dda5298cf9db6c679ef4
This is an SHA1 hash of "StackOverflow" - basically a one-way encryption of the word.
Within your existing files:
"ac-config.php"
<?php
//Admin Username and password
$adminuser = "admin";
$adminhashfile = '_something_random.txt';
$adminhash = file_get_contents( $adminhashfile );
.... (rest of the file as-is) ...
"ac-login.php"
<?php
$formuser = $_POST["formuser"];
$formpass = sha1( $_POST["formpass"] );
if( $formuser==$adminuser && $formpass==$adminhash ){
setcookie ("cookuser", $formuser);
setcookie ("cookpass", $formpass);
header( "Location: ac-admin.php" );
} else {
include("ac-config.php");
echo($no_pass_or_user_error_message);
}
?>
If you want to change the password at anytime, you can either manually calculate the SHA-1 hash of your new password and paste it into the "_something_random.txt" file, or you can create a PHP script which (authenticates you as already being logged-in and then) takes the new password and writes it into that file for you.
<?php
include("ac-config.php");
$newPassword = $_POST['newPassword'];
file_put_contents( $adminhashfile , sha1( $newPassword ) );

file_*_contents() & heredoc example...
<?php
//Replacing the values into the config
$config_file="";
if(isset($_POST['update']) && isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$config_file = <<<CONFIG
<?php
//Admin Username and password
\$adminuser = "$user";
\$adminpass = "$pass";
//Error message variables
\$not_logged_in_message_error_message = "Error<br><br>You Are not logged in. Go back and try again!<br><br>";
\$incorrect_error_message = "Error<br><br>You have entered the incorrect username and/or password, please go back and try again!<br><br>";
\$no_pass_or_user_error_message = "Error<br><br>You have either not entered a password or a username, please go back and try again!<br><br>";
//The first page you want the script to go to after creating those cookies (this page must include the validating code as seen in admin1.php)
\$first_page = "ac-admin.php";
?>
CONFIG;
file_put_contents('ac-config.php',$config_file);
//Where to send after update
header('Location: ./admin.php?page=changepass');
}
//Getting the values for the form
$config_file = file_get_contents('ac-config.php');
$match = preg_match('%adminuser = \"(.*?)\"%',$config_file,$confuser);
$match = preg_match('%adminpass = \"(.*?)\"%',$config_file,$confpass);
//$confuser[0] & $confpass[0] can be used to insert the values into the form
?>
<form method="POST" action="">
<input type="hidden" name="page" value="changepass">
<input type="hidden" name="update" value="go">
<h1>Change Logins</h1>
<p>Username:<input type="text" name="user" value="<?php echo $confuser[0];?>" size="20"></p>
<p>Password:<input type="password" name="pass" value="<?php echo $confpass[0];?>" size="20"></p>
<p><input type="submit" value="Submit"></p>
</form>

Related

How to call an HTML file from PHP

I am trying to create an administrator login page using HTML and PHP (the PHP is here for several other purposes too) where once the administrator logs in, an HTML file needs to run.
I will include my login page code below. I need to insert the command in the if statement in the PHP file. I tried different ways of using the include function; maybe I am not using it right.
Code:
PHP file
?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='admin' and $password =='Parthurnax')
{
include 'test.html';
}
else
{
echo 'you are not the admin';
}
?>
HTML file:
<html>
<body>
<div align="center">
<form action="page.php" method="POST">
<b>Username:</b><input type="text" name="username"><br>
<b>Password:</b><input type="password" name="password"><br>
<input type="submit">
</form>
</div>
</body>
</html>
change
if ($username =='admin' and $password =='Parthurnax')
{
<?php include 'test.html';?>
}
else
{
echo 'you are not the admin';
}
to
if ($username =='admin' and $password =='Parthurnax')
{
include 'test.html';
}
else
{
echo 'you are not the admin';
}
You have openend PHP tags in an already open PHP script.
Don't forget the test.html page is still accesible without logging in.
If i were to directly put in test.html in my browser, i'd get your protected page.
Change it to a PHP script and check for a logged in user. If the user is not logged in either 301 them to the login page or die your script.
use below if you want to redirect to the new page
if(whatever_condition_set_true) {
header('Location: whatever_page.html');
exit;
}
or
if your want to include any page based on condition then use
if(whatever_condition_set_true) {
include_once('whatever_page.html');
}
Use header("yourlink.html"); and don't forget to exit()

Basics - Setting and using a session cookie in php?

I'm sure this is a basic question and I'm sure the answer is basic too - apologies if so, but I'm having trouble linking my practical example to the theory I've read.
I'm using the PHPAuth project for my site's authentication. The bit that's got me confused in the notes is the description for the login method that reads:
Authenticates a user with the system. Note: You need to take the
returned session hash and create the session cookie, the method does
not do this for you.
If a successful login returns:
Array ( [error] =>
[message] => You are now logged in.
[hash] => 374d0de4f97b96b6665c23aa0998dbae1f790fe6
[expire] => 0
)
What do I actually do with this information to allow the next page to see that a user is logged in?
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php");
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
if (!$auth->isLogged()) {
header('HTTP/1.0 403 Forbidden');
echo "Forbidden";
exit();
}
echo "you are logged in";
?>
I am assuming the above code will handle the session cookie as this is code is almost exactly as the example given by the PHPAuth project so specifically, I'm asking what is meant by the bold text in the above quote.
FYI, the class functions for checking the cooking look like this:
/**
* Returns is user logged in
* #return boolean
*/
public function isLogged() {
return (isset($_COOKIE[$this->config->cookie_name]) && $this->checkSession($_COOKIE[$this->config->cookie_name]));
}
/**
* Returns current session hash
* #return string
*/
public function getSessionHash(){
return $_COOKIE[$this->config->cookie_name];
}
My previous answer answers my question, but I'm posting this answer in the hope that it may help someone else using the PHPAuth project.
This is my login page:
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
if ($auth->isLogged()) {
echo "You are already signed up and logged in";
exit();
}
$msg = null;
$showform = true;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//check for errors
if (empty($_POST["email"]) ||
empty($_POST["pwd"]) ) {
$msg = "All fields are required.";
} else { //all good - proceed
$result = $auth->login($_POST["email"], $_POST["pwd"]);
//check for success
if ($result["error"] == 1) {
$msg = $result["message"];
} else {
//success
$msg = $result["message"];
$showform = false;
setcookie($config->cookie_name, $result['hash'], time()+3600, "/"); //NOTE: the time can be set with config from the cookie_forget or cookie_remember settings in the PHPAuth config table
}
}
}
?>
<html>
<head></head>
<body>
<?php
if ($showform == true) { ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div>
<label for="email">Email:</label>
<div>
<input type="email" name="email" id="email" placeholder="Enter email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
</div>
</div>
<div>
<label for="pwd">Password:</label>
<div>
<input type="password" name="pwd" id="pwd" placeholder="Enter password">
</div>
</div>
<div>
<button type="submit" name="submit">Submit</button>
</div>
<?php echo $msg; ?>
</form><?php
} else {
echo $msg . '<br />';
}
?>
</body>
</html>
This is a secured page:
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
if (!$auth->isLogged()) {
header('HTTP/1.0 403 Forbidden');
echo "Forbidden";
exit();
}
echo "You are logged in";
?>
And this is a logout script:
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
echo $auth->logout($_COOKIE['authID']);
?>
The basic answer appears to be this:
Obviously, we need to create the session cookie. In this particular case, the cookie name needs to be the name stored in the config db, "authID".
To do this, I just need to use setcookie see http://php.net/manual/en/function.setcookie.php
In my testing example, on a successful login, I set the cookie and then redirect on a script page like this:
setcookie('authID', $_GET['h'], time() + (86400 * 30), "/");
header('Location: main.php');

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 to redirect the user back to desired URL after login page in PHP?

OK. I have a page called plans.php, inside I have three links (Plan 1, Plan 2, Plan 3). Each link has its own page and it redirects to login page (login.php, which works fine). So if the user is not logged in when they click lets say on "Plan 2" it will force the user to login so they can see the desired page, all depends of what "Plan" the user chooses.
PROBLEM:
I'm having a hard time redirecting the user back to the "desired Plan (URL)".
Solution:
If the user chooses "Plan 1 or Plan 2 (whatever plan)" then it will force user to login (I have that working fine), after user logs in successfully the user has to be redirected to their respective "Plan page".
If any is familiar with this issue please help.
plans.php
Plan 1
Plan 2
Plan 3
plan-2.php
<?php
ob_start();
include "header.php";
if(!$current_user) {
require_login();
}
ob_end_flush();
?>
HTML code:
What the user is going to see after login page.
<p>Hello, you have been redirected to "Plan 2"</p>
login.php
<?php
ob_start();
include "header.php";
if($current_user) {
req_logout(); }
ob_end_flush();
?>
HTML code:
<form action="authenticate.php" method="POST">
<label for="email">Email</label><br/>
<input type"text" class="input" name="username" id="username" />
<label for="password">Password</label><br/>
<input name="password" type="password" class="input" id="password"/>
<input type="submit" value="Sign In" class="submit"/>
</form>
This file verifies user credentials where the login form submits to.
authenticate.php
<?php
session_start();
require_once "db.php";
db_connect();
require_once "auth.php";
$user_id = credentials_valid($_POST['username'], $_POST['password']);
if($user_id){
log_in($user_id);
if($_SESSION['redirect_to']){
header("Location: " . $_SESSION['redirect_to']);
unset($_SESSION['redirect_to']);
}else{
// Default page after user logs in.
header("Location: manage.php");
}
}else{
header("Location: login.php?error=1");
exit("You are being redirected");
}
?>
I have some PHP functions in this file.
auth.php
// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}
// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
if($_SESSION['user_id']){
$user_id = intval($_SESSION['user_id']);
$query = "SELECT *
FROM `********`
WHERE `id` = $user_id";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$current_user = mysql_fetch_assoc($result);
return $current_user;
}
}
}
return $current_user;
}
// Requires a current user (Restrict Access to Page)
function require_login(){
if(!$current_user){
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header('Location: signin.php');
exit("You must log in.");
}
}
Try to send a parameter when a user clicks on a plan link. Pass or save the parameter and after successful login, use that parameter to redirect to the proper page.
in plan-2.php
session_start();
$_SESSION['redirect_to']="plan-2.php";
EDIT:
Here is complete solution using parameter sending via GET and POST (as I have been asked for):
plans.php
Plan 1
Plan 2
Plan 3
plan.php
<?php
ob_start();
$getbackURLid=$_GET['no'];
include "header.php";
if(!$current_user) {
require_login($getbackURLid);
}
ob_end_flush();
?>
signin.php
<?php
ob_start();
include "header.php";
if($current_user) {
req_logout(); }
ob_end_flush();
?>
HTML code:
<form action="authenticate.php" method="POST">
<label for="email">Email</label><br/>
<input type"text" class="input" name="username" id="username" />
<label for="password">Password</label><br/>
<input name="password" type="password" class="input" id="password"/>
<input type"hidden" name="url" value="<?php echo $_GET['url'];?>" />
<input type="submit" value="Sign In" class="submit"/>
</form>
authenticate.php
<?php
session_start();
require_once "db.php";
db_connect();
require_once "auth.php";
$user_id = credentials_valid($_POST['username'], $_POST['password']);
if($user_id){
log_in($user_id);
if($_POST['url']){
header("Location: plan.php?no=".$_POST['url']);
unset($_SESSION['redirect_to']);
}else{
// Default page after user logs in.
header("Location: manage.php");
}
}else{
header("Location: login.php?error=1");
exit("You are being redirected");
}
?>
auth.php
// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}
// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
if($_SESSION['user_id']){
$user_id = intval($_SESSION['user_id']);
$query = "SELECT *
FROM `********`
WHERE `id` = $user_id";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$current_user = mysql_fetch_assoc($result);
return $current_user;
}
}
}
return $current_user;
}
// Requires a current user (Restrict Access to Page)
function require_login($getbackURLid){
if(!$current_user){
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header('Location: signin.php?url=$getbackURLid');
exit("You must log in.");
}
}
Since some popular browsers (like Chrome) cache server redirect responses, if you do a server redirect, the requested page will always redirect to the same page as the first redirect the browser encountered.
To solve this, you validation PHP page should contains the following redirection:
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
// Check if the session's user is logged in properly
$redirect = "";
if (!$_SESSION['current_user']) {
$target_page= "http://www.myserver.com/login?sender=" + urlencode(curPageURL());
echo "<html>";
echo " <head>";
echo " <script>";
echo " window.location = '", $target_page, "';";
echo " </script>";
echo " </head>";
echo " <body></body>";
echo "</html>"
} else {
?>
<html>
<head>
</head>
<body>
<!-- put your page html here -->
</body>
</html>
<?php
}
?>
Please note that I'm not a PHP developper, my code may contains syntax errors and must be revised properly.
So... yeah, the code may look a little bit crappy but the important thing to remember is to not use the http response redirection. I tried all possible ways to disable response caching but chrome don't care at all. The only safe way I found is to do the redirection using javascript. I did not try the META http-equiv="refresh" way though. I guess it's safe as well since we see that often.
Another thing to remember is to avoid rendering your sensitive page content if the user is not logged in.
With that in mind, you should be good to go.
Hope it helps!

User profile data does not appear after logging in

I am creating a social network website where each user has his own profile, but there is a problem when I log in, the profile page does not appear. I used cookies and sessions I did lot of research about the problem but without any success, so I think that the problem is in the cookies. I do not know how to fix it; if anyone can help me, I will appreciate that.
profile.php
<?php
ob_start();
require_once('for members/scripts/global.php');
if($logged == 1){
echo("you need to be loged in to view profiles");
exit();
}
if(isset($_GET['id'])){
$id=$_GET['id'];
$id= preg_replace("#[^0-9]#","",$id);
}else{
$id=$_SESSION['id'];
}
//collect member information
$query = mysql_query("SELECT * FROM members WHERE id='$id'LIMIT 1") or die("could not collect user information ");
$count_mem = mysql_num_rows($query);
if($count_mem == 0){
echo("the user does not exit");
exit();
}
while($row = mysql_fetch_array($query)){
$username = $row['username'];
$fname = $row['firstname'];
$lname = $row['lastname'];
$profile_id= $row['id'];
if($session_id == $profile_id){
$owner = true;
}else{
$owner = false;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php print("$fname"); ?> <?php print("$lname"); ?>'s profile</title>
<link href="style/stylesheet.css" type="text/css"/>
</head>
<body>
<div class="container center">
<h1><?php print("$username"); ?></h1>
<?php
if($owner == true ){
header("Location: profile.php");
?>
<!--
edit profile<br />
account settings<br />
-->
<?php
}else{
header("Location: index.php");
?>
<!--
private message<br />
add as friend<br />
-->
<?php
}
?>
</div>
</body>
</html>
<?php flush(); ?>
If you need other related code, let me know. Thank you.
There are quite a few things wrong with the code that you have displayed. For starters, Do not use mysql_ functions. From the PHP manual
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
Secondly, your header redirects are imbedded in your HTML, which is bad practice and you've only been saved by ob_start(). With that though, you have a conditional that will either redirect to 'profile.php' or 'index.php', be lucky you get redirected to 'index.php', otherwise you'd have a forever self-redirecting page.
I can't see if/where you ever set the variable $session_id, but from what can be seen, it's null and will never == $profile_id, so $owner will always be false.
With that, you have a while loop while fetching one row...remove it, no need for it.
Now for some of the logic in your code. If you have to be the profile owner in order to view it, check that immediately after your query, and if not the owner, header("Location: index.php"); die; and don't have an else, anything following it means that it's the profile owner viewing the page.
Also, you need to make sure session_start(); is at the top of the page if you plan on using the session variables. You have ob_start(); up there, but at the end you call flush(). Read up on ob_start() and call the proper flush function for the buffer you started.

Categories