PHP Page password protection - php

I had created a simple password protection page for a PHP webpage by searching online. below is the code.
protect.php:
<?php
namespace Protect;
function with($form, $password, $scope=null) {
if( !$scope ) $scope = current_url();
$session_key = 'password_protect_'.preg_replace('/\W+/', '_', $scope);
session_start();
if( $_POST['password'] == $password ) {
$_SESSION[$session_key] = true;
redirect(current_url());
}
if( $_SESSION[$session_key] ) return;
require $form;
exit;
}
function current_url($script_only=false) {
$protocol = 'http';
$port = ':'.$_SERVER["SERVER_PORT"];
if($_SERVER["HTTPS"] === 'on') $protocol .= 's';
if($protocol === 'http' && $port === ':80') $port = '';
if($protocol === 'https' && $port === ':443') $port = '';
$path = $script_only ? $_SERVER['SCRIPT_NAME'] : $_SERVER['REQUEST_URI'];
return $protocol."://".$_SERVER[SERVER_NAME].$port.$path;
}
function redirect($url) {
header("Location: ".$url);
exit;
}
Form.php:
<html>
<body>
<form method="POST">
<?php
if( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
?>
Invalid password
<?php
}
?>
<p>Enter password for access:</p>
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
</body>
</html>
At the top of the php webpage which is to be protected with security password:
<?php
require_once('protect.php');
Protect\with('form.php', 'demo'); // demo is the password
?>
It's working fine but I am getting an error as
Undefined index: password in C:\xampp\htdocs\iv\admin\protect.php on line 9 and session start() is already defined.
(On top of the php page which is to be protected).
When I tried to make any changes its completely not working.
Anybody, please help and guide me where exactly the error.

You have to check first if the password has been submitted in your with function.
// this has to be checked first
// added isset to check if its existing
if( isset($_SESSION[$session_key]) && $_SESSION[$session_key] ) return;
^-------------------------------^
if( isset($_POST['password']) && $_POST['password'] == $password ) {
^--------------------------^
...
}

As noted by #Martin in several comments, your two issues can be easily solved by reading the linked questions/answers.
The first issue, which is the session already started error, can be easily solved by bringing out the session_start() from your function altogether and put it only once in the very top level php file.
The second issue is resolved by using empty() or isset().
function with($form, $password, $scope=null)
{
if(empty($scope))
$scope = current_url();
$session_key = 'password_protect_'.preg_replace('/\W+/', '_', $scope);
if(isset($_POST['password']) && ($_POST['password'] == $password)) {
$_SESSION[$session_key] = true;
redirect(current_url());
}
if(!empty($_SESSION[$session_key]))
return false;
require($form);
exit;
}
To set session:
<?php
# Just add by default, don't use an "if" clause
session_start();
# Do the rest of your script
require_once('protect.php');
$Protect->with('form.php', 'demo');
One final note; make sure your indenting correlates to hierarchy otherwise the script can get hard to read.

Related

memory exhausted on line 2860 with (if else)

I've searched in various places for this solution, but have not been able to solve the problem that happened to me. What happens is actually in the following code:
[21-Jul-2017 23:35:30 UTC] PHP Parse error: memory exhausted in
/home/.../public_html/folder/index.php on line 2860
Chronologically, I want to create many options if one of the options is met. Here's the problem code:
<?php
if(isset($_GET['url'])) {
$u = $_GET['url'];
if($u == 'old/page1.html') {
header('Location: /new/page1.htm');
} if($u == 'old/page2.html') {
header('Location: /new/page2.htm');
} if($u == 'old/page3.html') {
header('Location: /new/page3.htm');
} if($u == 'old/page4.html') {
header('Location: /new/page4.htm');
}
//.....
//.....(line 5691)
}
?>
If I only use the above code, then it can run normally. But if I use my code number of 5691 lines, then the warning starts to appear and the site can not be opened.
I suspect there is a problem on the maximum amount of memory used, but do not know exactly.
If you really need to sort it out this way, then this would probably be better:
<?php
if (isset($_GET['url'])) {
$u = $_GET['url'];
$redirects = [
'old/page1.html' => '/new/page1.htm',
// ...
];
if (array_key_exists($u, $redirects)) {
$redirect = $redirects[$u];
header(sprintf(
'Location: %s',
$redirect
));
}
}
This way at least you can manage the redirect mapping separately, without the need to add a bunch of conditions.
You could also put the mapping into a separate file:
<?php
return [
'old/page1.html' => '/new/page1.htm',
// ...
];
and then adjust your script:
<?php
if (isset($_GET['url'])) {
$u = $_GET['url'];
$redirects = require __DIR__ . '/redirects.php';
if (array_key_exists($u, $redirects)) {
$redirect = $redirects[$u];
header(sprintf(
'Location: %s',
$redirect
));
}
}
This way you don't need to modify your script if the mapping changes.
Alternatively, use elseif:
<?php
if (isset($_GET['url'])) {
$u = $_GET['url'];
if ($u == 'old/page1.html') {
header('Location: /new/page1.htm');
} elseif ($u == 'old/page2.html') {
header('Location: /new/page2.htm');
} elseif ($u == 'old/page3.html') {
header('Location: /new/page3.htm');
} elseif ($u == 'old/page4.html') {
header('Location: /new/page4.htm');
}
}
You can replace those 5691 lines of code with this
if(isset($_GET['url'])) {
$u = $_GET['url'];
if(substr($u, 3) === 'old'){
$new = str_replace('old', 'new', $u);
header("Location: $new");
}

Redirect if user is not an admin is not working on SSL

I've been using the code below for a while with no trouble. I redirect back to the main page if user is not an admin. I just installed SSL and now does not work anymore. I know it has something to do with the code checking for SSL but I'm not sure how to do that. Any help is appreciated.
function redirect_admin_login()
{
global $wpdb;
global $current_user;
$visitor = $current_user->ID;
$login_page = home_url('');
$page_viewed = basename($_SERVER['REQUEST_URI']);
if ($page_viewed == "wp-admin" && $_SERVER['REQUEST_METHOD'] == 'GET' && $visitor != '1')
{
wp_redirect($login_page);
exit;
}
}
add_action('init', 'redirect_admin_login');
Give the following code a shot
function admin_redirect()
{
if (!current_user_can('administrator') && (!defined('DOING_AJAX') || !DOING_AJAX ))
{
wp_safe_redirect(get_home_url());
exit();
}
}
add_action('admin_init', 'admin_redirect', 1);

Putting a session in a if and else statement

I've got a problem with putting a session to store some page info into a variable
heres the code:
<?php
$t = $_GET['nm'];
if ($t=="1")
{
session_start();
// store session data
$_SESSION['nm']=1;
}
else
{
?>
<script>
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
window.location = "http://www.gouda-info.nl/mobile";
}
</script>
<?php
}
$session = $_SESSION['nm'];
if ($session=="1")
{
When i try to use the script it just doesn't work. I use this script to redirect mobile users, but if they choose to use the Desktop version they'll be allowed by activating the session that stores if the user has activated the desktop version by putting nothing or a 1 in the link like so:
http://www.example.com/index.php?nm=1
hope anyone comes up with a bright solution. :)
EDIT:
it just fails if i try to run this code, it gives me a blank page.
session must be started on the top, and sometimes you deal with == 1 and other with $t == "1"
try this code:
// first line
session_start();
$t = $_GET['nm'];
if ($t == 1) { // use 1 instead of "1"
// store session data
$_SESSION['nm'] = 1;
} else {
?>
<script>
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
window.location = "http://www.gouda-info.nl/mobile";
}
</script>
<?php
}
$session = $_SESSION['nm'];
if ($session == 1) { // use 1 instead of "1"
}
You are using js code in php, but your js will be run after entire php file executed. So use php instead;
<?php
session_start();
$t = $_GET['nm'];
if ($t == "1") {
// store session data
$_SESSION['nm'] = "1";
} else {
if(isMobile()) {
header('Location: http://www.gouda-info.nl/mobile');
exit();
}
}
$session = $_SESSION['nm'];
if ($session == "1") {
......
}
function isMobile($user_agent=NULL) {
if(!isset($user_agent)) {
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
}
return (strpos($user_agent, 'Android') !== FALSE
|| strpos($user_agent, 'webOS') !== FALSE
|| strpos($user_agent, 'iPhone') !== FALSE
|| strpos($user_agent, 'iPad') !== FALSE
|| strpos($user_agent, 'iPod') !== FALSE
|| strpos($user_agent, 'BlackBerry') !== FALSE);
}

Redirect is giving me 2 address in the browser bar. So I am getting an error. Can't figure it out

I am getting 2 address in the browser window so I am getting an error. This is on GoDaddy. I'm thinking maybe a change in the php might fix it because it seems to be bringing up the domain the redirect is coming from.
Example:
my site.com - trying to redirect to an external site after the submit button in the form is submitted.
It redirects me to:
http://www.mysite/ http://external_site
instead of just: external_site.com
Any help would be great as I am totally lost on this…
The redirect is in a hidden field in a form. It is using GoDaddy's php which is below:
<?php
$request_method = $_SERVER["REQUEST_METHOD"];
if($request_method == "GET"){
$query_vars = $_GET;
} elseif ($request_method == "POST"){
$query_vars = $_POST;
}
reset($query_vars);
$t = date("U");
$file = $_SERVER['DOCUMENT_ROOT'] . "/../data/gdform_" . $t;
$fp = fopen($file,"w");
while (list ($key, $val) = each ($query_vars)) {
fputs($fp,"<GDFORM_VARIABLE NAME=$key START>\n");
fputs($fp,"$val\n");
fputs($fp,"<GDFORM_VARIABLE NAME=$key END>\n");
if ($key == "redirect") { $landing_page = $val;}
}
fclose($fp);
if ($landing_page != ""){
header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
} else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
?>
Remove $_SERVER["HTTP_HOST"] in the first header ...
<?php
/* above your code */
if ($landing_page != ""){
header("Location: $landing_page"); // If the http:// is missing don't forget to add it
} else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
?>

isset variables created using extract function

$array = explode('/', $_SERVER['REQUEST_URI']);
$count = count($array);
extract($array, EXTR_PREFIX_ALL, 'var');
can the variables (created using extract function) be isseted automatically? to avoid "Notice: Undefined variable:" errors when error_reporting(E_ALL); is enabled.
thank you
I tried doing something of this sort, still needed to isset() whenever, the variables are used next in the code (when error_reporting(E_ALL); is enabled).
if(isset($var_0))
{
$var_0 = filter_var($var_0, FILTER_SANITIZE_STRING);
}
if(isset($var_1))
{
$var_1 = filter_var($var_1, FILTER_SANITIZE_STRING);
}
if(isset($var_2))
{
$var_2 = filter_var($var_2, FILTER_SANITIZE_STRING);
}
if(isset($var_3))
{
$var_3 = filter_var($var_3, FILTER_SANITIZE_STRING);
}
==========================
Alternatively, tried the one line if condition,
$var_0 = isset($var_0) ? filter_var($var_0, FILTER_SANITIZE_STRING) : '';
$var_1 = isset($var_1) ? filter_var($var_1, FILTER_SANITIZE_STRING) : '';
$var_2 = isset($var_2) ? filter_var($var_2, FILTER_SANITIZE_STRING) : '';
$var_3 = isset($var_3) ? filter_var($var_3, FILTER_SANITIZE_STRING) : '';
while the error got subsided, but, a new problem arises i.e., variables (which are not created by extract function are getting isseted because of this one line if condition approach).
I am posting two of the routing rules (of two urls) in the website.
$pagename = "not-found.php";
//Different Routing Engine Rules follows
if ((isset($var_1)) && (($var_1 == "") || ($var_1 == "index.php"))) {
if((isset($var_2)) || (isset($var_3)) || (isset($var_4)) || (isset($var_5)) || (isset($var_6)) || (isset($var_7)))
{
$pagename = "not-found.php";
}
else
{
$pagename = "default-home.php";
}
}
if (($var_1 == "login"))
{
//echo "Login Page URL\n";
if((isset($var_2)) || (isset($var_3)) || (isset($var_4)) || (isset($var_5)) || (isset($var_6)) || (isset($var_7)))
{
$pagename = "not-found.php";
}
else
{
$pagename = "login.php";
}
}
include "code/" . $pagename;
any help will be appreciated, thank you
If I understand your question correctly then, no. It's still your responsibility to know what variables are available and act accordingly. You can simply disable these notices via error_reporting(E_ALL & ~E_NOTICE) for the portion of code in question.
Edit
Looking at your updated question, I think it would be helpful if you could explain what you're trying to achieve. Personally, I see the use of extract as a bit of a code smell and there may be a better way :)

Categories