Not displaying data on PHP file - php

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

Related

Login form fails to login client

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.

Autosave with ajax, php and mysql

I tried to write a script mixing something I found on the internet in order to autosave a form data to the mysql db... Something went wrong cause the script it is able to insert but for some reason not to update so every 20 sec (the time I set up) is generating a new row... Can anyone help me to find and solve the issue?
Here is the code:
<?php
session_start();
unset($_SESSION['article_id']);
require_once('xajax/xajax_core/xajax.inc.php');
$xajax = new xajax();
function savetodb($form) {
$title = $form["title"];
$editor = $form["editor1"];
//$host = 'localhost';
//$username = 'my_user';
//$password = 'my_pass';
//$database = 'test_db';
//$connect = mysql_connect($host, $username, $password);
//mysql_select_db($database, $connect);
if ($_SESSION['article_id']=="") {
$sql = "INSERT INTO draft (`title`, `content`) VALUES ('$title', '$editor')";
$result = mysql_query($sql, $connect);
$idlast = mysql_insert_id($connect);
$_SESSION['article_id'] = $idlast;
} else {
$article_id = $_SESSION['article_id'];
$sql = "UPDATE draft SET `title`='$title',`content`='$editor' WHERE `id`='$article_id'";
$result = mysql_query($sql, $connect);
}
// Instantiate the object xajaxResponse
$objResponse = new xajaxResponse();
$objResponse->assign("autosavemsg","innerHTML", "<br />Record saved to database successfully!");
$objResponse->alert('Done!');
return $objResponse;
}
//$xajax->register(XAJAX_FUNCTION,'savetodb');
$xajax->registerFunction('savetodb');
$xajax->processRequest();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<?php $xajax->printJavascript('xajax'); ?>
</head>
<body>
<form name="form" id="form" enctype="multipart/form-data">
<?php
echo '<label>Title</label><input type="text" name="title" id="title"><br /><br />';
echo '<textarea name="editor1"></textarea>' ;
?>
<input type="button" name="save" onclick="xajax_savetodb(xajax.getFormValues('form'));" value="Save to Database">
</form>
<div id="autosavemsg"></div>
<script language="Javascript">
//Interval
var AutoSaveTime=20000;
//time object
var AutoSaveTimer;
SetAutoSave();
function SetAutoSave() {
AutoSaveTimer=setInterval("xajax_savetodb(xajax.getFormValues('form'));",AutoSaveTime);
}
</script>
</body>
</html>
Unfortunately is not even give to me the alert "done" or the message that I set..
Probably something wrong with the session??
thanks in advance
I'm not familiar with xajax but referring to my logic, I think you are doing it wrong.
I think you have to have two different files, one is your HTML and javascript and other one is your server-side code which is responsible for inserting or updating the db.
right now as I think you are calling the file itself with ajax and in the third line of the code you have unset($_SESSION['article_id']); which will unset the session variable $_SESSION['article_id'] each time you call the ajax.
so I think you have to make two different files.
file1.php
you have your html and javascript files in it and also have the unset($_SESSION['article_id']); line in it.
files2.php you have your php and db related functions in it and delete the unset($_SESSION['article_id']); line from it.
you also have to set in file1.php that your ajax should call file2.php
I think this will do the trick

unexpected session identifier php

So I looked into other threads but didnt find a solution that worked for me.
Here is my problem:
I have two php pages:
http://codepad.org/VhblM76K and
http://codepad.org/W9bz8L3E.
The first page is supposed to get information from a form, look for it in a database, store it in a variable $_SESSION['$dataArray'] and send it to the second page.
On the second page I get the information in javascript from php with json_encode, which gives an error:
Uncaught SyntaxError: Unexpected token < result.php:20.
When I look in the source in chrome it says:
var schoolData = <br />
<b>Notice</b>: Undefined index: $dataArray in <b>C:\xampp\htdocs\highschools.bg\result.php</b> on line <b>23</b><br />
null;
How is this an unidentified index, when i can only go to the second page after visiting the first one, where I assing a value to $_SESSION['$dataArray'].
How can I fix this? I have written session_start() in both pages and it didnt work for me.
I need the variable schoolData to show the information on the page.
The reason why you're getting the error is because you're not setting any session data, because you are redirecting directly to the second page from the form.
You need to update the form so it redirects back to the same page the form is on, then replace your PHP code with the following:
if (isset($_POST['submit'])) {
$user = 'root';
$pass = '';
$db = 'highschools';
$con = mysqli_connect('localhost', $user, $pass, $db) or die("Unable to connect");
if (mysqli_connect_errno()) {
echo("Failed to connect to MySQL: " . mysqli_connect_error());
}
$givenCity = $_POST['city'];
$givenClass = $_POST['class'];
$givenName = $_POST['name'];
$result = mysqli_query($con,
"SELECT * FROM highschools WHERE name like '%$givenName%' AND city like '%$givenCity%' AND class like '%$givenClass%'; ") or die(mysqli_error($con));
$row_count = mysqli_num_rows($result);
$_SESSION['dataArray'] = array();
while($row_count > 0) {
$curRow = mysqli_fetch_array($result);
$_SESSION['dataArray'][] = $curRow;
$row_count--;
}
header('location: http://YOUR_SECOND_PAGE_ADDRESS');
Notice, the only line I've added is the last line, hedaer('location: ... ');
Don't forget to change the http://YOUR_SECOND_PAGE_ADDRESS to the actual page address of your second piece of code.
Then in the second page, replace $_SESSION['$dataArray'] with $_SESSION['dataArray']
and it should work.
Your problem is that you are writing the session as $_SESSION['$dataArray']. If you have a variable somewhere called $dataArray then you need to write it $_SESSION[$dataArray].
Alternately, if you don't have a variable named $dataArray, then you need to write it as $_SESSION['dataArray'].
EDIT:
Try print_r($_SESSION) beneath the session_start() at the top of the page and see if you have set that the $_SESSION['dataArray']:
<?php
session_start();
// See if the session contains your $_SESSION['dataArray']
// If not, you can force it to have a default value to avoid errors
print_r($_SESSION);
$_SESSION['dataArray'] = (isset($_SESSION['dataArray']))? $_SESSION['dataArray']:array(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Намерени училища</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/main.css">
</head>
<body>
<div id="contentWrapper" style="height:1000px;">
<header id="pageHeader">
</header>
<section id="schoolsContainer">
<ul id="schoolsList"></ul>
</section>
</div>
<script type="text/javascript" src="handlebars-v2.0.0.js"></script>
<script type="text/javascript" src="navTemplate.js"></script>
<script type="text/javascript">
var schoolData = <?php echo json_encode($_SESSION['dataArray']) ?>;
for (var i = 0; i < schoolData.length; i++) {
console.log(schoolData[i]['name']);
console.log(schoolData[i]['id']);
}
</script>
</body>
</html>
On the other page, this also has to be set before it works:
$_SESSION['dataArray'] = array();
while($row_count > 0) {
$curRow = mysqli_fetch_array($result);
$_SESSION['dataArray'][] = $curRow;
$row_count--;
}

How to check login detail from a text file of username and passwords? PHP

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

PHP Password Protecting

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>';

Categories