I'm having difficulty trying to password-protect a section of my website. I'm not too familiar with php, so I'm using code from zubrag.com as a starting point. The problem I'm running into is that I get an error with the current code that states:
cannot modify header information - headers already sent by (output started at /var/www/index.php:78) in /var/www/index.php on line 333
I've looked at like 78, I get it, my outputs start there because that's the first line that the php bracket is at.
At line 333 is my setcookie command. I also understand that in order to have a cookie set, it needs to be done in the header. Unfortunately, I'm not sure how I can do that with my code. I've looked online and found that generally the best way to fix this is through the use of ob_start() and ob_end_flush(). Well, I tried placing those commands at numerous places and have had no luck as of yet.
I've set ob_start at the beginning of the file, before everything else. I've also tried at the beginning of the case and have had no luck.
I've set ob_end_flush at the end of the file and at the end of the case, and I've had no luck with that either.
<html lang="en">
<head>
<title>DVR Controls</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/superfish.css">
<link rel="stylesheet" media="screen" href="css/superfish-navbar.css" />
<script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="js/hoverIntent.js"></script>
<script type="text/javascript" src="js/superfish.js"></script>
<script type="text/javascript">
// initialise plugins
jQuery(function(){
jQuery('ul.sf-menu').superfish();
});
</script>
<script>
$(document).ready(function(){
$("ul.sf-menu").superfish({
pathClass: 'current'
});
});
</script>
<center><b><font size="36">The Radeus DVR Prototype</font></b></center>
</head>
<body>
<ul class="sf-menu sf-navbar">
<li class="current">
<a>Configuration</a>
<ul>
<li>
System Configuration
</li>
<li>
File Configuration
</li>
<li>
Network Configuration
</li>
</ul>
</li>
<li>
Files
</li>
<li>
Maintenance Mode
</li>
<li>
IETM
</li>
<li>
<a>Power Options</a>
<ul>
<li>
Shutdown
</li>
<li>
Reboot
</li>
</ul>
</li>
</ul>
</body>
<br><br><br><br><br>
<body>
<br>
<?php
ob_start();
$currentdir = '/data/'; //Location of Hard Drive
/**
* #func: Executes the command passed to it as argument and prints the
* command console output line by line onto the html output stream hence
* giving the illusion of having the command executing in the html window itself.
*/
function html_exec_cmd($cmd) {
$proc = popen("($cmd)2>&1", "r");
echo '<pre>';
while(!feof($proc)) {
$result = fgets($proc, 100);
echo htmlspecialchars($result);
flush();
}
pclose($proc);
echo '</pre>';
}
switch ($_GET['page'])
{
case 'SysConfig':
echo "Welcome to System Config!";
break;
case 'FileConfig':
echo "Welcome to File Config!";
break;
case 'NetworkConfig':
?>
<b><fontsize="16">Current Settings:</b></font>
<?php
html_exec_cmd('ifconfig eth0');
break;
case 'Files':
$FileCount = 0;
$dir = opendir($currentdir);
$array = array();
echo '<ul>';
echo '<form method = "post" action = "">';
while ($File = readdir($dir)){
echo '<form action="test.php" method = "post">';
//if (is_file($file))
$ext = pathinfo($File, PATHINFO_EXTENSION);
if ($ext == '264'){
$array[] = "$File";
echo "<INPUT class='radio' type='radio' name='FileName' value='$File' /> <span>$File</span><p>";
$FileCount++;
}
}
echo "<INPUT TYPE = 'Submit' name = 'FormSubmit' value = 'Submit'>";
echo '</form>';
if ($_POST['FormSubmit'] == "Submit")
{
$FileParameters = $_POST['FileName'];
$FileExecuteCommand = "cd //; /etc/init.d/matrix-gui-e stop;echo 0 > /sys/devices/platform/vpss/graphics0/enabled;./usr/share/ti/ti-omx/ decode_display_a8host_debug.xv5T -w 1920 -h 1080 -f 60 -c h264 -g 0 -d 0 -i $currentdir$FileParameters;/etc/init.d/matrix-gui-e start";
echo exec($FileExecuteCommand);
}
break;
case 'Maintenance':
###############################################################
# Page Password Protect 2.13
###############################################################
# Visit http://www.zubrag.com/scripts/ for updates
###############################################################
#
# Usage:
# Set usernames / passwords below between SETTINGS START and SETTINGS END.
# Open it in browser with "help" parameter to get the code
# to add to all files being protected.
# Example: password_protect.php?help
# Include protection string which it gave you into every file that needs to be protected
#
# Add following HTML code to your page where you want to have logout link
# Logout
#
###############################################################
/*
-------------------------------------------------------------------
SAMPLE if you only want to request login and password on login form.
Each row represents different user.
$LOGIN_INFORMATION = array(
'zubrag' => 'root',
'test' => 'testpass',
'admin' => 'passwd'
);
--------------------------------------------------------------------
SAMPLE if you only want to request only password on login form.
Note: only passwords are listed
$LOGIN_INFORMATION = array(
'root',
'testpass',
'passwd'
);
--------------------------------------------------------------------
*/
##################################################################
# SETTINGS START
##################################################################
// Add login/password pairs below, like described above
// NOTE: all rows except last must have comma "," at the end of line
$LOGIN_INFORMATION = array(
'admin' => 'adminpass'
);
// request login? true - show login and password boxes, false - password box only
define('USE_USERNAME', true);
// User will be redirected to this page after logout
define('LOGOUT_URL', 'http://www.example.com/');
// time out after NN minutes of inactivity. Set to 0 to not timeout
define('TIMEOUT_MINUTES', 3);
// This parameter is only useful when TIMEOUT_MINUTES is not zero
// true - timeout time from last activity, false - timeout time from login
define('TIMEOUT_CHECK_ACTIVITY', true);
##################################################################
# SETTINGS END
##################################################################
///////////////////////////////////////////////////////
// do not change code below
///////////////////////////////////////////////////////
// show usage example
if(isset($_GET['help'])) {
die('Include following code into every page you would like to protect, at the very beginning (first line):<br><?php include("' . str_replace('\\','\\\\',__FILE__) . '"); ?>');
}
// timeout in seconds
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES * 60);
// logout?
if(isset($_GET['logout'])) {
setcookie("verify", '', $timeout, '/'); // clear password;
header('Location: ' . LOGOUT_URL);
exit();
}
if(!function_exists('showLoginPasswordProtect')) {
// show login form
function showLoginPasswordProtect($error_msg) {
?>
<html>
<head>
<title>Please enter password to access this page</title>
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</head>
<body>
<style>
input { border: 1px solid black; }
</style>
<div style="width:500px; margin-left:auto; margin-right:auto; text-align:center">
<form method="post">
<h3>Please enter password to access this page</h3>
<font color="red"><?php echo $error_msg; ?></font><br />
<?php if (USE_USERNAME) echo 'Login:<br /><input type="input" name="access_login" /><br />Password:<br />'; ?>
<input type="password" name="access_password" /><p></p><input type="submit" name="Submit" value="Submit" />
</form>
<br />
</div>
</body>
</html>
<?php
// stop at this point
die();
}
}
// user provided password
if (isset($_POST['access_password'])) {
$login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
$pass = $_POST['access_password'];
if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
|| (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) || $LOGIN_INFORMATION[$login] != $pass ) )
) {
showLoginPasswordProtect("Incorrect password.");
}
else {
// set cookie if password was validated
setcookie("verify", md5($login.'%'.$pass), $timeout, '/');
// Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
// So need to clear password protector variables
unset($_POST['access_login']);
unset($_POST['access_password']);
unset($_POST['Submit']);
}
}
else {
// check if password cookie is set
if (!isset($_COOKIE['verify'])) {
showLoginPasswordProtect("");
}
// check if cookie is good
$found = false;
foreach($LOGIN_INFORMATION as $key=>$val) {
$lp = (USE_USERNAME ? $key : '') .'%'.$val;
if ($_COOKIE['verify'] == md5($lp)) {
$found = true;
// prolong timeout
if (TIMEOUT_CHECK_ACTIVITY) {
setcookie("verify", md5($lp), $timeout, '/');
}
break;
}
}
if (!$found) {
showLoginPasswordProtect("");
}
}
?>
<B><fontsize=16>Are you sure you want to Format the data disk?</b></font><br><br>
<?php
echo '<form method = "post">';
echo "<INPUT TYPE = 'Submit' name = 'FormatSubmit' value = 'Submit'>";
?>
<br><br><br>
Please check the box to verify you want to Format the data disk.
<Input type = 'Checkbox' Name ='FormatCheck' value ="checked">
<?php
echo '</form>';
if (($_POST['FormatSubmit'] == "Submit") & ($_POST['FormatCheck'] == "checked"))
{
html_exec_cmd('echo -e "o\nn\np\n1\n\n\nw\n" | fdisk /dev/sda;sleep 1;mkfs.ext3 /dev/sda1;mount /dev/sda1 /data/');
}
ob_end_flush();
break;
case 'IETM':
echo "Welcome to IETM";
break;
case 'Shutdown':
//echo "Welcome to Shutdown";
?>
<B><fontsize=16>Are you sure you want to shutdown the DVR?</b></font><br><br>
<?php
echo '<form method = "post">';
echo "<INPUT TYPE = 'Submit' name = 'ShutDownSubmit' value = 'Submit'>";
?>
<br><br><br>
Please check the box to verify you want to shutdown the DVR.
<Input type = 'Checkbox' Name ='ShutDownCheck' value ="checked">
<?php
echo '</form>';
if (($_POST['ShutDownSubmit'] == "Submit") & ($_POST['ShutDownCheck'] == "checked"))
{
$ShutDownCommand = "init 0";
echo exec($ShutDownCommand);
}
break;
case 'Reboot':
//echo "Welcome to Reboot";
?>
<B><fontsize=16>Are you sure you want to reboot the DVR?</b></font><br>
<br>
<?php
echo '<form method = "post">';
echo "<INPUT TYPE = 'Submit' name = 'RebootSubmit' value = 'Submit'>";
?>
<br><br><br>
Please check the box to verify you want to reboot the DVR.
<Input type = 'Checkbox' Name ='RebootCheck' value ="checked">
<?php
if (($_POST['RebootSubmit'] == "Submit")& ($_POST['RebootCheck'] == "checked"))
{
$RebootCommand = "reboot";
echo exec($RebootCommand);
}
echo '</form>';
break;
default :
echo "The Radeus DVR";
}
?>
</body>
</html>
<?php ob_end_flush(); ?>
If you are going to use PHP's header function it must be called before any response is sent to the user. In this case the response preventing this from working is the HTML at the top of your page that comes before your PHP code.
You could use a bit of javascript in a PHP echo statement to do the redirect and avoid the PHP header issue altogether. For instance:
echo '<script type="text/javascript"> window.location = "login.php"; </script>';
Related
I've been trying to create an admin panel for my website. I created a login form but whenever I try to log in, it says that the user does not exist. I can't seem to find where I made a mistake.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - Admin panel</title>
</head>
<body>
<?php
include 'db.php';
?>
<?php
include 'functions.php';
?>
<?php
include 'title_bar.php';
?>
<h3>Login Here: </h3>
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) or empty($password)){
echo "<p>Fields should not be empty</p>";
} else {
$check_login=mysqli_query($con,"SELECT id, type FROM users WHERE username='$username' AND password='$password'");
if(mysqli_num_rows($check_login) == 1){
$run=mysqli_fetch_array($check_login);
$user_id=$run['id'];
$type=$run['type'];
if($type =='d') {
echo "<p>Your acount is deactivated by an admin!</p>";
} else {
$_SESSION['user_id'] = $user_id;
header('location: adminpanel.php');
}
} else {
echo "<p>Wrong Username or Password</p>";
}
}
}
?>
<form method='post'>
User name:
<input type ='text' name = 'username' />
<br/><br/>
Password:
<input type = 'password' name = 'password' />
<br/><br/>
<input type = 'submit' name = 'submit' value='Login' />
</form>
</body>
</html>
Any help would be appreciated.
Just because I see this all the time on SO, I will address some of my comments. There are a lot of reasons why it could fail based on what you have. First off, a solid framework would do almost all this for you, you would just have to do basic logic but not all the grunt work. Second, just because you want to echo some text in a specific part of your page, doesn't mean you should do a bunch of logic that leads up to echo in the same part of the page. The idea is that the browser output is the last thing to happen so you will want to do the bulk of your logic before the page outputs.
First break up your logic into a specific-task functions/class/methods that will be easily understood and ready to be re-used:
/functions.php
<?php
// I am going to use PDO because I am more familiar with it
function verifyUser($username,$password,$con)
{
// Get the basics from the database
$query = $con->prepare("SELECT `password`,`type`,`id` FROM `users` WHERE `username` = :0");
// Bind the value for security
$query->execute(array(":0"=>$username));
// Get the results
$result = $query->fetch(PDO::FETCH_ASSOC);
// If empty, return false
if(!$result)
return array('verified'=>false);
// You need to store the password using password_hash()
$verified = password_verify($password,$result['password']);
// If user is revoked
$revoked = is_deactivated($result);
// Return all the validation settings
return array(
'type'=>$result['type'],
'id'=>$result['id'],
'revoked'=> $revoked,
'verified'=>$verified,
'valid'=>($verified && !$revoked)
);
}
function getUserById($id,$con)
{
$query = $con->prepare("SELECT * FROM `users` WHERE `id` = :0");
$query->execute(array(":0"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!$result)
return false;
return $result;
}
function is_deactivated($userArr = false,$con = false)
{
// Set default user empty
$user = false;
// If value is numeric (id)
if(is_numeric($userArr)) {
// Get the data by from database, assign to user
$user = getUserById($userArr,$con);
}
// If the value is an array, just assign to user
elseif(is_array($userArr))
$user = userArr;
// If the value is still empty, stop, return deactivated
if(empty($user))
return true;
else
// If user is valid (in db), return bool if they are revoked
return ($user['type'] == 'd');
}
function loginObserver(&$error,$con)
{
// See if the action to log in is set
if(isset($_POST['action']) && $_POST['action'] == 'login') {
// Run the verify function
$verify = verifyUser($_POST['username'],$_POST['password'],$con);
// If user is in db
if($verify['verified']) {
// See if they are revoked, send back error
if($verify['revoked']) {
$error = 'revoked';
return false;
}
// Assign your session id
$_SESSION['user_id'] = $verify['id'];
// Return true for success
return true;
}
else {
// User was not in system, send invalid error
$error = 'invalid';
return false;
}
}
else
// Return a string so the subsequent logic knows that
// no attempt was made to log in.
return 'invalid';
}
Secondly, now that you have all your business logic stored away in contained functions (classes/methods) you can cleanly apply them to the page.
/login.php
<?php
// Put this at the very beginning. I would consider putting it on a config page and
// including it would be better because then you will have some consistency
// through your site
session_start();
// Add your functions and or classes, better yet would be to have an autoloader
// to load classes and a pseudo-autoloader to load functions
include('functions.php');
// Put your database connection at the top, on the config page would be better
include('db.php');
// Move logic to the top and pass errors to the page
$error = false;
// Run the observer function
$login = loginObserver($error,$con);
// Invalid means no attempt was made to login
if($login != 'invalid')
// If there are no errors (empty), redirect
if(!$error) {
// This needs to go before output of html to browser
header('location: adminpanel.php');
// Stops the script from processing the rest of the page
exit;
}
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - Admin panel</title>
</head>
<body>
<?php
// This is probably fine, it's likely just html
include('title_bar.php');
?>
<h3>Login Here: </h3>
<?php if($error) {
echo ($error == 'invalid')? 'Wrong username or password.':'Your access has been revoked by admin.';
} ?>
<form method='post'>
<!-- add an action here -->
<!-- You should do a token system for verifying submission authenticity -->
<input type="hidden" name="action" value="login" />
User name:
<input type='text' name='username' />
<br/><br/>
Password:
<input type='password' name='password' />
<br/><br/>
<input type='submit' name='submit' value='Login' />
</form>
</body>
</html>
Finally, this code is not tested so there may be errors in logic. It is intended to show you how to apply my (and perhaps other's comments practically). I don't want to say "Don't do this and don't do that" but don't show an alternative. This script is based on yours so you can identify similarities easier, but is no way implied this is the only way, or the correct way to do a login.
The Problem
I am trying to submit a form in php but due to the nature of what i want i need the page to not go onto the next one i just want it to submit the data and refresh the current page or whatever, at current it submits the data and goes onto page 2 which i dont want i just need it to submit the data and stay on the current page, if thats possible!
The Code
//page 1 code
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form method="post" action="jacob_dailey.php">
<select name="baby_status">
<option value="playing">Playing</option>
<option value="awake">Awake</option>
<option value="sleeping">Sleeping</option>
</select>
<br />
<input type="submit" value="Submit"/>
</form>
</center>
//page 2 code
<?php
if (isset($_POST['baby_status'])) {
$baby = $_POST['baby_status'];
setcookie("baby_status", $baby, time() + 31556926, '/'); // Data will Store For 1 Year
header('Location: ' . $_SERVER['PHP_SELF']);
}
$status = $_COOKIE['baby_status'];
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
echo '</center>';
?>
Page 2 code shouldnt be as important but i just need it so when i click submit on page 1 it updates the information on page 2 but doesnt take me to page 2.
Cheers!
Your form can submit onto itself. Just in the action="xyz" either leave it (the whole action=... attribute) out entirely or else name the page that also contains the form there between quotes.
Then when you load the page you check the $_POST or $_GET array (depending on the method) to see if the submit button was pushed or if someone just navigated to the page. (You'll want to give you submit button a name="foo".)
action="jacob_dailey.php" in your form takes you to that page, you either paste your php code to main page and replace action with just "" or you will search AJAX and learn how to it with that
You can use jQuery.ajax(). Example here:
http://www.formget.com/form-submission-using-ajax-php-and-javascript/
This example uses a database, but you can use a php file to return values and read them from the response in javascript. Do not put any action to the form but enable a click event handler on the submit button to enable the function.
Also my example here: http://dev.ossipesonen.fi/alkoholilaskuri/
A very simple form where you insert values, pass them onto PHP with $_POST and then calculates the right amounts and sums, and you print them in the response.
Solution: Update Status Without Page Reload Using XHR and Filesystem Storage
If you want someone on another computer to see the update, then you'll need to store that information on the server. You could store the information in a database, but for this small bit of information I'm using the filesystem.
page1.php
<?php
// get baby status if available
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
// prepare to update select list
list($pl_check, $pl_check, $pl_check) = array('', '', '');
switch ( $status ) {
case 'playing': $pl_check = ' selected '; break;
case 'awake': $aw_check = ' selected '; break;
case 'sleeping': $sl_check = ' selected '; break;
}
?>
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form id="baby_form" method="post" action="update_baby.php">
<select id="baby_status" name="baby_status">
<option value="playing" <?php echo $pl_check ?>>Playing</option>
<option value="awake" <?php echo $aw_check ?>>Awake</option>
<option value="sleeping"<?php echo $sl_check ?>>Sleeping</option>
</select><br />
<input type="submit" value="Submit"/>
</form>
See Baby Status
</center>
<script>
// XHR/PHP/Filesystem method
function update_baby () {
var baby_status = document.getElementById('baby_status');
var status=encodeURIComponent(baby_status.options[baby_status.selectedIndex].value)
var parameters = 'baby_status=' + status
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('POST', 'update_baby.php', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
console.log(this.responseText)
alert(this.responseText)
}
xhr.send(parameters)
}
// hook up baby status function to form submit
document.getElementById('baby_form').addEventListener('submit', function(evt){
evt.preventDefault()
update_baby()
})
</script>
page2.php
<?php
// execute baby update code and get current status
include 'update_baby.php';
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
?>
<br>
Update Baby Status
</center>
update_baby.php
<?php
if (isset($_POST['baby_status'])) {
$status = $_POST['baby_status'];
// prepare php script text for baby status file
$status_write = <<<EOT
<?php
\$status = '$status';
?>
EOT;
// write status to baby_status.php
if ( $baby_status_file = fopen('baby_status.php', 'w') ) {
fwrite($baby_status_file, $status_write);
fclose($baby_status_file);
}
echo 'Baby status updated.';
}
else {
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
}
?>
Note: To use this option the directory these files are in must be writeable by the web server.
I have a form that requires users to enter a username and password. There is a text file of registered usernames and passwords. How can I get the login.php to check if the username exists in file and that the corresponding password exists. And if so to inform user and return to index.php with the name of user displayed on top of page?
The text file has 4 elements for each user separated by a comma: fullname, email, username and password.
The function I have written so far is:
function validate_fname() {
global $fname, $validated, $errors_detected;
if (!empty($_POST['fname'])) {
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$validated['fullname'] = $_POST['fname'];
$fname = htmlentities($_POST['fname']);
return "<p>You entered full name: $fname</p>";
} else {
$errors_detected = true;
return "<p>Full name must be no more than 150 characters and must contain one space.</p>"; }
}
else {
$errors_detected = true;
return "<p>Field not submitted!</p>";
}
}
and the login.php is as follows:
<?php
session_start();
include 'includes/header.php';
require_once 'functions.php';
?>
<title>Login</title>
<h1>Login</h1>
<br />
Home |
About Us |
Members Area |
Register |
<br /><br />
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
$uname = '';
$pw = '';
$validation;//Holds success or failure messages.
if($_SERVER['REQUEST_METHOD'] == 'POST') { //Only executes functions when form is submitted.
$validation = validate_logon();
}
?>
<form action="<?php echo $self; ?>" method="post"> <!--Sets up form-->
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<?php
include 'includes/logindetails.php';
?>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<br />
New users click on register link on top of page;
</body>
</html>
Please note logindetails.php just has the text to create two form fields for username and password.
Thanks in advance :)
There is function that works like that way but, this is highly NOT recommended at all when it comes to storing passwords. There are many smart dudes out there that can easily break into an app like that design you are asking.
You need to use fopen() and fread().
Taken from http://uk3.php.net/manual/en/function.fread.php
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
?>
Then maybe use explode(' ', $contents) to read the items into array.
<?php
$details = explode(' ', $contents);
foreach($details as $value){
if($uname === $value){
return 'Match found';
}
}
fclose($handle);
Read : http://uk3.php.net/manual/en/control-structures.foreach.php
[UPDATE: Solved: Thanks everyone. See code here: http://pastebin.com/1fJmXeG2] I greatly appreciate any help I can get on this problem. We have a logon page on our site running on an old Linux server using Apache 1 and PHP 4. We want to move it to a new Windows 2008 server (64-bit)... so I installed Apache 2.25 and PHP 5.4 on the new server. I also enabled OCI8 connecting to an Oracle 11g database. I moved the files for the logon page over to the new server and they don't work. What happens is the page does not run the script and it just forwards to the index.php instead of redirecting to index php with the appropriate response. Of course there was some deprecated language which I updated in the PHP script, but it still doesn't work. I am a complete newbie so I am not sure if it is a problem with the script or a problem with the PHP settings. I know I can connect to the database, since I made a test page doing so. Please help me if you can... I am really desperate. The following is the code for my authorization page:
<?php session_start();
// Begin or continue session by registering variables
$_SESSION['USER_ID'] = 'USER_ID';
$_SESSION['PASSWORD'] = 'PASSWORD';
$_SESSION['FIRST'] = 'FIRST';
$_SESSION['LAST'] = 'LAST';
$_SESSION['ACCESS_KEY'] = 'ACCESS_KEY';
$_SESSION['conn'] = 'conn';
$_SESSION['BEENHERE'] = 'BEENHERE';
$_SESSION['CUSTOMER_NAME'] = 'CUSTOMER_NAME';
$_SESSION['WAREHOUSING'] = 'WAREHOUSING';
$_SESSION['TRANSPORTATION'] = 'TRANSPORTATION';
$_SESSION['MYACCOUNT'] = 'MYACCOUNT';
// Set Environment Variables
$SYS_DBUSER = "*****";
$SYS_DBPASSWORD = "*****";
$SYS_DB = "*****";
// Begin Authorization Routine
if ( (!isset($USER_ID)) && (!isset($PASSWORD)) )
{
echo '<html>';
echo '<head>';
echo '<title> Customer Access - Login</title>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">';
echo '</head>';
echo '<body bgcolor="#FFFFFF" text="#000000">';
echo '<div align="center">';
echo '<p><img src="../images/logocir3.gif" width="120" height="123"> </p>';
echo '<p><b><font size="5" color="#0000FF" face="Arial, Helvetica, sans-serif">The ';
echo 'The Company</font></b></p>';
echo '<p><font size="4" color="#0000FF" face="Arial, Helvetica, sans-serif"><b><i>Customer Access</i></b></font></p>';
echo '<form name="form1" method="post" action="index.php">';
echo '<p> <font size="3" face="Arial, Helvetica, sans-serif">Username:</font> ';
echo '<input type="text" name="USER_ID" maxlength="15">';
echo '</p>';
echo '<p><font size="3" face="Arial, Helvetica, sans-serif">Password: </font> ';
echo '<input type="PASSWORD" name="PASSWORD" maxlength="15">';
echo '</p>';
echo '<p><input type="submit" name="Submit" value="Login"></p>';
echo '</form>';
echo '<p> </p>';
echo '</div>';
echo '</body>';
echo '</html>';
exit;
}
elseif ( ($BEENHERE == 1) && (isset($FIRST)) && (isset($PASSWORD)) && (isset($ACCESS_KEY)) && (isset($USER_ID)) && (isset($LAST)) && (isset($conn)) && (isset($CUSTOMER_NAME)) )
{
return (TRUE);
}
else
{
// Connect to database
unset($conn);
$conn = oci_connect($SYS_DBUSER,$SYS_DBPASSWORD,$SYS_DB);
// Generate sql statement
$loginsql = oci_parse($conn,"SELECT FIRST_NAME,LAST_NAME,CUSTOMER_NAME,ACCESS_KEY,TRANSPORTATION,WAREHOUSING,MYACCOUNT FROM WEB_USERS WHERE USER_ID = SUBSTR(UPPER('$USER_ID'),1,15) AND PASSWORD = SUBSTR(UPPER('$PASSWORD'),1,30) AND ENABLED = 'Y'");
// Execute statement
oci_execute($loginsql,OCI_NO_AUTO_COMMIT);
// Retrieve number of rows for authentication
$nrows = oci_fetch_all($loginsql,$results);
// Database Authenticate
if ( $nrows != 1 )
{
// Display if login fails
unset($USER_ID);
unset($PASSWORD);
unset($FIRST);
unset($LAST);
unset($ACCESS_KEY);
unset($conn);
unset($BEENHERE);
unset($CUSTOMER_NAME);
unset($WAREHOUSING);
unset($TRANSPORTATION);
unset($MYACCOUNT);
echo "<H1>Login Failure - Please Check Your Password AND/OR Username</H1><BR>";
echo "<H3>Try Again</H3>";
// Close used resources
oci_free_statement($loginsql);
oci_close($conn);
exit;
}
else
{
// Assign login information to global variables
unset($FIRST);
unset($LAST);
unset($ACCESS_KEY);
unset($BEENHERE);
unset($CUSTOMER_NAME);
unset($WAREHOUSING);
unset($TRANSPORTATION);
unset($MYACCOUNT);
$FIRST = $results['FIRST_NAME'][0];
$LAST = $results['LAST_NAME'][0];
$CUSTOMER_NAME = $results['CUSTOMER_NAME'][0];
$ACCESS_KEY = $results['ACCESS_KEY'][0];
$TRANSPORTATION = $results['TRANSPORTATION'][0];
$WAREHOUSING = $results['WAREHOUSING'][0];
$MYACCOUNT = $results['MYACCOUNT'][0];
$BEENHERE = 1;
// Close used resources
oci_free_statement($loginsql);
oci_close($conn);
}
}
?>
Here are my php settings in a png file: http://i.imgur.com/7c8BzZG.png?1
I don't know about the rest, but you need to add session_start(); to the top of your php page. This should be the first thing on every page you carry your sessions on. I usually put it right next to the tag like so:
<?php session_start();
...
Since PHP4, request variables are only available via the arrays $_GET (for GET requests) and $_POST (for POST requests). You've got some rewriting to do, starting off with turning
if ( (!isset($USER_ID)) && (!isset($PASSWORD)) )
into
if ( (!isset($_POST)) )
or
if ( (!array_key_exists('USERID', $_POST)) && (!array_key_exists('PASSWORD', $_POST)) )
More:
http://php.net/manual/en/function.array-key-exists.php
http://www.php.net/manual/en/reserved.variables.php
Lots of things to fix in your code:
Like joemurphy said, to check if the form has been submitted:
if (!isset($_POST)) {....}
Don't use lots of echo statements to display HTML. Close your PHP tag (?>) and just output the HTML code as normal. Then when you're finished with the HTML, add a PHP opening tag (<php) and continue with your PHP code.
Check for values in $_SESSION with
if (isset($_SESSION['USER_ID'])){...}
If you need a specific value:
if (isset($_SESSION['USER_ID']) && $_SESSION['USER_ID'] == 1){...}
You don't need to set dummy values to initialize them in session or unset them before setting them. Set them only when you have appropriate values for them, then clear them out on logout. So delete the "Begin or continue session by registering variables" section.
I am trying to learn some new stuff and always wanted to learn how to make a website with PHP and mysql...
I found this easy tutorial and sample files to play with
http://css-tricks.com/php-for-beginners-building-your-first-simple-cms/
I'm trying to add another table it works in the database but when I try to display it it don't work. Here is the code I got and using:
<?php
class simpleCMS {
var $host;
var $username;
var $password;
var $table;
public function display_public() {
$q = "SELECT * FROM laptopvoltage ORDER BY created DESC LIMIT 3";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$lvmodel = stripslashes($a['lvmodel']);
$lvmanuf = stripslashes($a['lvmanuf']);
$lvvolt = stripslashes($a['lvvolt']);
$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<h2>
$lvmodel
</h2>
<p> !!!!!!this dont show upp!!!!!! - - - - >>>>>
$lvmanuf
</p><----------- WHY?
<p>
$lvvolt
</p>
</div>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<h2> This Page Is Under Construction </h2>
<p>
No entries have been made on this page.
Please check back soon, or click the
link below to add an entry!
</p>
ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION
<p class="admin_link">
Add a New Entry
</p>
ADMIN_OPTION;
return $entry_display;
}
public function display_admin() {
return <<<ADMIN_FORM
<form action="{$_SERVER['PHP_SELF']}" method="post">
<label for="lvmodel">Title:lv model</label><br />
<input name="lvmodel" id="lvmodel" type="text" maxlength="150" />
<div class="clear"></div>
<label for="lvmanuf">Title:lv manu</label><br />
<input name="lvmanuf" id="lvmanuf" type="text" maxlength="150" />
<div class="clear"></div>
<label for="lvvolt">Title:lvvolt</label><br />
<input name="lvvolt" id="lvvolt" type="text" maxlength="150" />
<div class="clear"></div>
<input type="submit" value="Create This Entry!" />
</form>
<br />
Back to Home
ADMIN_FORM;
}
public function write($p) {
if ( $_POST['lvmodel'] )
$lvmodel = mysql_real_escape_string($_POST['lvmodel']);
if ( $_POST['lvmanuf'] )
$lvmanuf = mysql_real_escape_string($_POST['lvvolt']);
if ( $_POST['lvvolt'] )
$lvvolt = mysql_real_escape_string($_POST['lvvolt']);
if ( $lvmodel && $lvmanuf && $lvvolt ) {
$created = time();
$sql = "INSERT INTO laptopvoltage VALUES('$lvmodel','$lvmanuf','$lvvolt','$created')";
return mysql_query($sql);
} else {
return false;
}
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this->buildDB();
}
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS laptopvoltage (
lvmodel VARCHAR(150),
lvmanuf TEXT,
lvvolt VARCHAR(150),
created VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
}
?>
it just wont show $lvmanuf. Any help on this would be great as the fields are showing up in my database.
this first file only shows results, if your not to familiar with web logic and design then ill try my best to explain, this first file is called index.php, every website and web-application has a file either call index.html or index.php the reason behind this is that the web server looks for a file named either index.html or index.php and dont misunderstand there are more than just these file types and names a server can start off of its just that these are the most common, since that is out of the way now i will explain the code behind the first file.
as you can see we have set up our basic html document inside and added a script, now the script we made will make the files that are loaded inside the id we specified disappear after a set ammount of seconds, next inside the body of the html we put this code,
<span id="messages">
<?php include "constant.php"; ?>
</span>
this code contains to main players for this script first the span tag with the id attribute tells our javascript the id of the text we want to be invisible after the set amount of seconds, next the
<php include "constant.hpp"; ?>
it includes every thing from the constant.php document we make.
file 1
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="content-language" content="en-US" />
<title>MySQL Connection test</title>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('messages'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
</head>
<body>
<span id="messages">
<?php include "constant.php"; ?>
</span>
</body>
</html>
this second file im not going to explain to much about it, since it would make this way to long, but this file is the connection file to the mysql database.
the only part you need to fill in on this is the
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
this will connect your website to the database.
file 2
constant.php
<?php
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
//do not modify anything past this point unless you know php well.
$database_link = null;
$database_defaults = array("127.0.0.1","3306","MySQL","root","");
$error_defaults = array("error_no_101" => "required field *IP is empty, using default parameters!",
"error_no_102" => "required field *PORT is empty, using default parameters!",
"error_no_103" => "required field *NAME is empty, using default parameters!",
"error_no_104" => "required field *USER is empty, using default parameters!",
"error_no_105" => "required field *PASS is empty, using default parameters!");
if(empty($database_ip)){
$database_ip = $database_defaults[0];
echo $error_defaults["error_no_101"] . "<br/>";
}
if(empty($database_port)){
$database_port = $database_defaults[1];
echo $error_defaults["error_no_102"] . "<br/>";
}
if(empty($database_name)){
$database_name = $database_defaults[2];
echo $error_defaults["error_no_103"] . "<br/>";
}
if(empty($database_admin_user)){
$database_admin_user = $database_defaults[3];
echo $error_defaults["error_no_104"] . "<br/>";
}
if(empty($database_admin_pass)){
$database_admin_pass = $database_defaults[4];
echo $error_defaults["error_no_105"] . "<br/>";
}
$database_link = mysqli_connect($database_ip, $database_admin_user, $database_admin_pass, $database_name);
if (!$database_link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
} else {
echo 'Success... ' . mysqli_get_host_info($database_link) . "\n";
}
mysqli_close($database_link);
?>
i put this up to help you fix your code, not to teach you the syntax of the language.
to learn the syntax of php i recommend you go here:
this is the official php website documentation that teach you the correct way to code php,
http://www.php.net/manual/en/langref.php
you could also try this place if you have the money for a subscription:
http://www.lynda.com/MySQL-tutorials/PHP-MySQL-Essential-Training/119003-2.html?srchtrk=index:1%0Alinktypeid:2%0Aq:php%0Apage:1%0As:relevance%0Asa:true%0Aproducttypeid:2
for html you could go to:
http://www.w3schools.com/html/default.asp
you could also try this place if you have the money for a subscription:
http://www.lynda.com/HTML-tutorials/HTML-Essential-Training-2012/99326-2.html