I can't seem to find a way to block my page from being accessed. I have a page to give tickets to users in mysql, but you can simply type it into http to receive tickets, how do i stop people from doing that??
<html>
<head>
<?php
header("refresh:33;url=tickets_give.php" );
?>
<link rel="stylesheet" href="finessecss.css">
</head>
<body bgcolor="#F9F9F9" background="background3.jpg">
<div class="videobox">
<div class="video"><p>Video Player Unavailable At This Moment</p></div>
<div class="clockbox">
<span id="countdown" class="timer"></span>
<script>
var seconds = 30;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown')[0].innerHTML = "";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
</div>
</div>
</body>
</html>
There is my code for my video page
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "users_database";
session_start();
$name = $_SESSION['name'];
$pass = $_SESSION['pass'];
if (!(isset($_SESSION['can_accesss']) && $_SESSION['name'] != '')) {
Header("Location:welcome_get.php");
}
unset($_SESSION['can_access']);
// rest of page code
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ('$access' == 'Finesseshopisthebest'){
;
}
else{
echo'mysql' or die;
}
$sql = "UPDATE users_database SET tickets=tickets+10 WHERE username= '$name' and password= '$pass'";
if (mysqli_query($conn, $sql)) {
Header("Location:tickets.php");
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
</body>
</html>
And that is my give tickets page. How do i stop people from going straight to tickets_give.php?
If you're looking for a 20-second solution, just check for the presence of a precise query string, eg yoursite.com/somepage?foo=bar. If $_GET["foo"] is not set, call exit and forget about it.
Warning: this is security through obscurity; anyone with a network monitor or even just shoulder surfing would breeze past this, but I guess it's better than nothing. Clearly a smarter, long-term solution is to add meaningful authentication, but it sounds like you have a very short-term problem you need to solve!
Related
I have a very specific problem
I want to save / load two variables to database, and the third variable use as identificator
My current -not working- code:
$sql = mysql_query("INSERT INTO time (meno, minuty, sekundy) VALUES('$firstName','$minutes','$seconds')");
if (mysql_error()) die('Error, insert query failed');
What I want in the nutshell: When I log with name (etc Roman[$firstName variable]), it will load a previous $minutes and $seconds numbers, and save every (etc minute) new one (it is a timer, so save a time)
I hope you understand
Thanks for your time, I aprreciade it
My current timer.php
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=Windows-1250" />
<title>Timing Stránka</title>
<script>
let startTime, endTime;
$(window).on('load', () => {
startTime = new Date();
});
function time_elapsed() {
endTime = new Date();
let timeDiff = endTime - startTime;
let timeSpent = timeConversion(timeDiff);
const formData = new FormData();
formData.append('timeSpent', timeSpent);
/* The line below is used to send data to the server-side. This way is reliable than using AJAX to send the data especially in cases when you are listening for an unload event. You can read more about navigator.sendBeacon() in MDN's site. */
navigator.sendBeacon('db.php', formData);
}
function timeConversion(time) {
let seconds = (time / 1000).toFixed(1);
let minutes = (time / (1000 * 60)).toFixed(1);
let hours = (time / (1000 * 60 * 60)).toFixed(1);
let days = (time / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) {
return seconds + " second(s)";
} else if (minutes < 60) {
return minutes + " minute(s)";
} else if (hours < 24) {
return hours + " hour(s)";
} else {
return days + " day(s)";
}
}
/* Note: In the line below, i listen to the unload event, you can change this event to a button click or anything else you want to listen to before calling the function. This is better than calling setInterval() every second and i think it will help your application performance also. */
window.addEventListener('beforeunload', time_elapsed, false);
</script>
</head>
<body>
</div>
</br>
</br>
</br>
<?php
echo $timeSpent
?>
And the db.php:
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
// DB connection
$host = 'db.mysql-01.gsp-europe.net';
$db_name = 'xxxx';
$username = 'xxx';
$password = 'xxxx';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection Error: " . $e->getMessage();
}
if (isset($_POST['timeSpent'])){
$timeSpent = $_POST['timeSpent'];
// create query
$query = 'INSERT INTO user_time SET time = :time';
// prepare statement
$stmt = $conn->prepare($query);
// bind data
$stmt->bindParam(':time', $timeSpent);
// execute query and check if it failed or not
if ($stmt->execute()){
echo "Query Successful";
} else {
printf("Error: %s.\n", $stmt->error);
}
}
?>
Please create two tables one table for saving two variables and another table to saving identificator. Then use foreign key and relationships with JOINS. Hope these steps will save your problem.
Kindly replace the code in your "time.php" with this:
<?php
header('Content-Type: text/html; charset=Windows-1250');
session_start();
$firstName = $_SESSION['firstname'];
$minutes = $_POST['minutes'];
$seconds = $_POST['seconds'];
// DB connection
$host = 'localhost';
$db_name = 'zadmin';
$username = 'xxx';
$password = 'zadmin_nahovno';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection Error: " . $e->getMessage();
}
// create query
$query = 'INSERT INTO time SET meno = :firstName, minuty = :minutes, sekundy = :seconds';
// prepare statement
$stmt = $conn->prepare($query);
// bind data
$stmt->bindParam(':firstName', $firstName);
$stmt->bindParam(':minutes', $minutes);
$stmt->bindParam(':seconds', $seconds);
// execute query and check if it failed or not
if ($stmt->execute()){
echo "Query Successful";
} else {
printf("Error: %s.\n", $stmt->error);
}
?>
/*
This should work (if not, then something is wrong with your variables, you should look into your variables and see if they are actually holding any data). You can make use of var_dump() to examine the variables.
*/
Meno Užívateľa: <b> <?php echo $firstName; ?> </b>
</br>
</br>
Momentálne majníš : <b> <?php echo $minutes; ?> Minút </b> <b> a </b> <b> <?php echo $seconds; ?> Sekúnd </b>
</br>
</br>
#Hnusny Pleb, so in order to get the amount of time spent on a page, i wrote the following code for you.
First, in your script, you should write this:
<script>
let startTime, endTime;
$(window).on('load', () => {
startTime = new Date();
});
function time_elapsed() {
endTime = new Date();
let timeDiff = endTime - startTime;
let timeSpent = timeConversion(timeDiff);
const formData = new FormData();
formData.append('timeSpent', timeSpent);
/* The line below is used to send data to the server-side. This way is reliable than using AJAX to send the data especially in cases when you are listening for an unload event. You can read more about navigator.sendBeacon() in MDN's site. */
navigator.sendBeacon('index.php', formData);
}
function timeConversion(time) {
let seconds = (time / 1000).toFixed(1);
let minutes = (time / (1000 * 60)).toFixed(1);
let hours = (time / (1000 * 60 * 60)).toFixed(1);
let days = (time / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) {
return seconds + " second(s)";
} else if (minutes < 60) {
return minutes + " minute(s)";
} else if (hours < 24) {
return hours + " hour(s)";
} else {
return days + " day(s)";
}
}
/* Note: In the line below, i listen to the unload event, you can change this event to a button click or anything else you want to listen to before calling the function. This is better than calling setInterval() every second and i think it will help your application performance also. */
window.addEventListener('beforeunload', time_elapsed, false);
</script>
After writing the script above, the data will be sent to your server-side and then you can simply store the time spent (i.e. in seconds, minutes, hours or days) into your DB. In order to do that, you should write something similar to this in your server-side:
<?php
if (isset($_POST['timeSpent'])){
$timeSpent = $_POST['timeSpent'];
// create query
$query = 'INSERT INTO user_time SET time = :time';
// prepare statement
$stmt = $conn->prepare($query);
// bind data
$stmt->bindParam(':time', $timeSpent);
// execute query and check if it failed or not
if ($stmt->execute()){
echo "Query Successful";
} else {
printf("Error: %s.\n", $stmt->error);
}
}
?>
Kindly find a way to use the written code to achieve your goals. I think ive tried my best in helping you. Good Luck.
Okey, i Got it.. Here is a code:
Timing PAGE:
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
session_start();
$_SESSION['firstname'] = $firstName;
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=Windows-1250" />
<title>Timing Stránka</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('db.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>
</head>
<body>
</div>
</br>
</br>
</br>
<div id="load_tweets"> </div>
Time on page: <label id="minutes">00</label>
<label id="colon">:</label>
<label id="seconds">00</label>
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<INPUT TYPE="button" onClick="history.go(0)" VALUE="Oprava">
</body>
</html>
The page of timing AKA db.php:
<?php
header('Content-Type: text/html; charset=Windows-1250');
session_start();
$firstName = $_SESSION['firstname'];
$_SESSION['firstname'] = $firstName;
$servername = "db.xxxx.gsp-europe.net";
$username = "xxxxxx";
$password = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
$dbname = "xxxxx";
/// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare("SELECT points FROM member_profile WHERE user_id = '$firstName'");
$stmt->execute();
$array = [];
$resalts = $stmt->get_result();
while ($row = $resalts->fetch_array(MYSQLI_ASSOC))
{
$points = $row['points'];
}
$hours = floor($points / 3600);
$mins = floor($points / 60 % 60);
$secs = floor($points % 60);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// check if the user exist
$check = "SELECT * FROM `member_profile` WHERE user_id = '$firstName'";
$result = mysqli_query($conn,$check) or die(mysqli_error($conn));
$rows = mysqli_num_rows($result);
//if exist increse points with 1
if($rows>=1){
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
}
//if don't exist create user with points 0
if($rows==0)
{
$query = "INSERT into `member_profile` (user_id, points) VALUES ( '$firstName' ,'0')";
$result = mysqli_query($conn,$query)or die(mysqli_error($conn));
$conn->close();
}
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=Windows-1250" />
</head>
<body>
</div>
</br>
Meno Užívateľa: <b> <?php echo $firstName; ?> </b>
</br>
</br>
Overall time : <b> <?php echo $timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs); ?> </b>
</body>
</html>
How would I output the selected data from the database over a certain amount of pages.
For example I'd like 20 result per page and it automatically adds the extra pages needed (bit like google search pages but no search is needed as I am getting everything from the database).
Sorry for a bad explanation and also badly indented code, new to stackoverflow. I've tried putting just the php, rest of the page isn't complete or I removed the unnecessary code, feel free to improve as well.
At the moment I am just calling all the data onto one page using very simple
code
<?php
session_start();
if(isset($_POST['logout'])) {
unset($_SESSION['Username']);
session_destroy();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="" style="min-width: 1024px; max-width: 1920px; margin: 0 auto; min-height: 1280px; max-height: 1080px;">
<?php
if (isset ($_SESSION['Username']))
{
?>
<button onclick="location.href = 'logout.php';">Logout</button>
<?php
if (isset ($_SESSION['Username']))
{
echo "";
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "request";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM request";
$result = $conn->query($sql);
$sql = "SELECT * FROM request ORDER BY id DESC";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
if (isset ($_SESSION['Username']))
{
?>
<div align="center">
<div class="requests">
<p><?php echo $row["Name"]; ?></p>
<p><?php echo $row["Number"]; ?></p>
<p><?php echo $row["Song"]; ?></p>
</div>
</div>
<?php
}else{
header("Location: index.php");
}
}
} else {
echo "0 requests";
}
}
mysqli_close($conn);
?>
Let's see an example of pagination in PHP. Before that, we need to understand what pagination is. Result pagination is quite simple.
We do a search on a certain DataBase table, and with the result of the search, we divide the number of records by a specific number to display per page.
Related: Data pagination in PHP and MVC
For example a total of 200 records, and we want to display 20 per page, we will soon have 200/20 = 10 pages. Simple, right? Well let's go to the code then.
First connect to MySQL:
<?php
$conn = mysql_connect("host","user","pass");
$db = mysql_select_db("database");
?>
Now let's create the SQL clause that should be executed:
<?php
$query = "SELECT * FROM TableName";
?>
Let's get to work ... Specify the total number of records to show per page:
<?php
$total_reg = "10"; // number of records per page
?>
If the page is not specified the variable "page" will take a value of 1, this will avoid displaying the start page 0:
<?php
$page=$_GET['page'];
if (!$page) {
$pc = "1";
} else {
$pc = $page;
}
?>
Let's determine the initial value of the limited searches:
<?php
$begin = $pc - 1;
$begin = $begin * $total_reg;
?>
Let's select the data and display the pagination:
<?php
$limit = mysql_query("$query LIMIT $begin,$total_reg");
$all = mysql_query("$query");
$tr = mysql_num_rows($all); // checks the total number of records
$tp = $tr / $total_reg; // checks the total number of pages
// let's create visualization
while ($dados = mysql_fetch_array($limit)) {
$name = $data["name"];
echo "Name: $name<br>";
}
// now let's create the "Previous and next"
$previous = $pc -1;
$next = $pc +1;
if ($pc>1) {
echo " <a href='?page=$previous'><- Previous</a> ";
}
echo "|";
if ($pc<$tp) {
echo " <a href='?page=$next'>Next -></a>";
}
?>
Ready, your pagination in PHP is created!
I am making a web application which allows user to get funds for the project,I have got most part working but I am stuck at one place where the php script returns a positive status code but no data gets inserted into Mysql database. Following is the php script i am using:
Code:
<?php
session_start();
if(!isset($_SESSION['username']))
{
echo "Unauthorised Page Usage Please Relogin to Access All the Page features;";
header('location:login.html');
}
$sponsor=mysql_real_escape_string($_POST['sponsorid']);
$projectid=mysql_real_escape_string($_POST['projectid']);
$pledge=mysql_real_escape_string($_POST['pledgevalue']);
$servername = "localhost";
$usernam = "root";
$password = "";
$dbname = "project";
$httpStatusCode = 400;
$httpStatusMsg = 'Incorrect Username or Password';
$protocol=isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
$connection=new mysqli($servername,$usernam,$password,$dbname);
if (!$connection) {
die("Connection failed: " . $connection->connect_error);
}
$sql1="INSERT INTO `sponsor`(`spon_id`,`project_id`,`spon_amt`,`spon_date_time`) VALUES ('$sponsor','$projectid','$pledge',NOW())";
$result=$connection->query($sql1);
if ($result) {
$Success=200;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$result);
}
else {
$Success=400;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$httpStatusMsg);
}
?>
Below is the ajax used to post data to a page:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if(this.status===404){
alert(this.responseText);
}
if(this.status===200)
{
alert("Project backed successfully");
window.location.reload(true);
}
}
};
xhttp.open("POST", "sponsor.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param= "sponsorid"+"="+ <?php echo json_encode($_SESSION['username']); ?>+"&"+"pledgevalue"+"="+document.getElementById("pledge").value+"&"+"projectid"+"="+<?php echo json_encode($projectid);?>;
console.log(param);
xhttp.send(param);
}
I have cross referenced my sponsor table to make sure that every field is same.The code works fine on my friend`s computer. Please help me
Update: the $sql1 query is giving me Error code:1644 Problem when I ran it in Database (using XAMMP).
Please help.
Change
$result=$connection->query($sql);
To
$result=$connection->query($sql1);
You have used $sql1 as a query and when you fire query to database you are using $sql which is not available actually.
If make error reporting ON you will see an error about undefined variable $sql
If still it is not solve then print generated sql query using echo $sql1; and try it executing in database.you will get exact error.
Try this:
<?php
session_start();
if(!isset($_SESSION['username']))
{
echo "Unauthorised Page Usage Please Relogin to Access All the Page features;";
header('location:login.html');
}
$sponsor=mysql_real_escape_string($_POST['sponsorid']);
$projectid=mysql_real_escape_string($_POST['projectid']);
$pledge=mysql_real_escape_string($_POST['pledgevalue']);
$servername = "localhost";
$usernam = "root";
$password = "";
$dbname = "project";
$httpStatusCode = 400;
$httpStatusMsg = 'Incorrect Username or Password';
$protocol=isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
$connection=new mysqli($servername,$usernam,$password,$dbname);
if (!$connection) {
die("Connection failed: " . $connection->connect_error);
}
$sql1="INSERT INTO `sponsor`(`spon_id`,`project_id`,`spon_amt`,`spon_date_time`) VALUES ('$sponsor','$projectid','$pledge',NOW())";
$result=$connection->query($sql1);
if ($result) {
$Success=200;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$result);
}
else {
$Success=400;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$httpStatusMsg);
}
?>
Hello, I've been stumped by the PHP code I've written. I've stared at this for hours with no success, please help find any errors I've apparently gone over.
What I want this script to do is from a html form page, to query a database table ('users') to make sure their password and username are correct, then in a separate table ('tokens') insert a random token (the method I used before, it works) into the 'tk' column, and the users general auth. code pulled from the 'users' table into the 'gauth' colum, in the 'tokens' table.
The reason for the additional general auth is so I can pull their username and display it on all the pages I plan on "securing"
Sorry if I'm confusing, this is the best I can refine it. Also, I'm not that good at formatting :). I'm going to add some html later, that's why the tags are there.
MySQL Tables:
Users Example:
cols: username | password | email | classcode | tcode | genralauth |
hello | world | hello.world#gmail.com | 374568536 | somthin | 8945784953 |
Tokens Example:
cols: gauth | tk |
3946893485 |wr8ugj5ne24utb|
PHP:
<html>
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "-------";
$password = "-------";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql1 = "SELECT username FROM users";
$data1 = $conn->query($sql1);
if ($conn->query($sql1) === TRUE) {
echo "";
}
?>
<?php
$sql2 = "SELECT password FROM 'users'";
$data2 = $conn->query($sql2);
if ($conn->query($sql2) === TRUE) {
echo "";
}
?>
<?php
$bytes = openssl_random_pseudo_bytes(3);
$hex = bin2hex($bytes);
?>
<?php
if($_POST['pss'] == $data2 and $_POST['uname'] == $data1) {
$correct = TRUE;
}
else {
$correct = FALSE;
}
?>
<?php
if ($correct === TRUE) {
$sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";
$result3 = $conn->query($sql3);
}
?>
<?php
if ($correct === TRUE) {
$sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' , '".$result3."')";
if ($conn->query($sql4) === TRUE) {
echo "New token genrated.";
} else {
echo "Error: " . $conn->error;
}
}
?>
<?php
if ($correct === TRUE) { ?>
<p>Succesfuly loged in!</p><br/>
<button>Continue</button><br/>
<?php
}
elseif ($correct === FALSE) { ?>
<p>Incorrect, please try again.</p><br/>
<button>Back</button><br/>
<?php
}
?>
<?php
if ($correct === TRUE) {
$_SESSION['auth'] = $hex;
$_SESSION['logstat'] = TRUE;
}
?>
<?php
if ($correct === FALSE) {
$_SESSION['logstat'] = FALSE;
}
$conn->close();
?>
This is the PHP I'm going to use on most pages for token auth, howver it dosn't actually check the database 'tokens', also I need a way to display signed in users username using the general auth.
PHP:
<html>
<h1 class="title">Virtual Work Sheets!</h1>
<p class="h_option">[Log In / Register]</p><hr/>
<div class="body">
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "root20";
$password = "jjewett38";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql = "SELECT tk FROM tokens";
$data = $conn->query($sql);
?>
<?php
if (!$_GET['tk'] == $data) {
echo "
<p>Invalid token, please consider re-logging.</p>
";
}
else {
?>
<?php
switch ($_GET['view']) {
case teacher:
?>
Teacher page html here...
<?php
break;
case student:
?>
Student page html here...
<?php
break;
default:
echo "Please login to view this page.";
}
}?>
</html>
I suggest that you change your approach.
Although at first glance these example files looks like a lot, once you study them you'll see it's really much more simple and logical approach than the direction you are now headed.
First, move the db connect / login stuff into a separate file, and require or include that file at top of each PHP page:
INIT.PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Might as well also load your functions page here, so they are always available
require_once('fn/functions.php');
?>
Now, see how we use it on the Index (and Restricted) pages?
INDEX.PHP
<?php
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<!-- Examples need jQuery, so load that... -->
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<!-- and our own file we will create next... -->
<script type="text/javascript" src="js/index.js"></script>
<div id="pageWrap">
<div id="loginDIV">
LoginID: <input type="text" id="liID" /><br>
LoginPW: <input type="password" id="liPW" /><br>
<input type="button" id="myButt" value="Login" />
</div>
</div>
JS/INDEX.JS
$(function(){
$('#myButt').click(function(){
var id = $('#liID').val();
var pw = $('#liPW').val();
$.ajax({
type: 'post',
url: 'ajax/login.php',
data: 'id=' +id+ '&pw=' +pw,
success: function(d){
if (d.length) alert(d);
if (d==1) {
window.location.href = 'restricted_page.php';
}else{
$('#liID').val('');
$('#liPW').val('');
alert('Please try logging in again');
}
}
});
});//END myButt.click
}); //END document.ready
AJAX/LOGIN.PHP
<?php
$id = $_POST['id'];
$pw = $_POST['pw'];
//Verify from database that ID and PW are okay
//Note that you also should sanitize the data received from user
if ( id and password authenticate ){
//Use database lookups ot get this data: $un = `username`
//Use PHP sessions to set global variable values
$_SESSION['username'] = $un;
echo 1;
}else{
echo 'FAIL';
}
RESTRICTED_PAGE.PHP
<?php
if (!isset($_SESSION['username']) ){
header('Location: ' .'index.php');
}
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
<!-- AND here go all teh restricted things you need a login to do. -->
More about AJAX - study the simple examples
I am working on a test login-check with PHP/HTML and MySQL. I got it working great; it successfully connects to the database, it can grab my database values and save them in a variable, etc., but I ran into one slight problem.
I'm using two PHP pages to do the check. The login.php page, which only contains the forum, and the welcome.php page, which does the database connecting. When I ran a test page to just have it echo the database info, it printed out right (testUser, testEmail#email.com, testPassword, 1/1/1900). So when I tried to run my login-authentication check, it just says 'Unknown user!' twice, even when I try the usernames 'usr', 'testUser', and 'testUser2' (I made two tables, and the second one is the same with 2 added to the end). Here's my code.
<html>
<head>
<?php
$title = ucfirst(basename($_SERVER['PHP_SELF'], ".php"));
echo "<title>$title</title>";
?>
</head>
<body>
<form name="form" accept-charset="utf-8" action="welcome.php" method="post">
<span class="header">Username</span><input type="text" name="usr" value="usr"></input><br>
<span class="header">Password</span><input type="text" name="pass" value="pass"></input>
<input type="submit">
</form>
</body>
</html>
<?php
$servername = removed;
$username = removed;
$password = removed;
$dbname = removed;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// the given info from the form
$usrUser = $_POST["usr"];
$usrPass = $_POST["pass"];
// convert the findings to uppercase to get rid of sensitivity
if (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) == strtoupper($row["PASSWORD"])) {
echo "Welcome $usrUser!<br>Your login was successful! ?>";
}
elseif (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) != strtoupper($row["PASSWORD"])) {
echo "Login failed as $usrUser!";
}
else {
echo "Unknown user!";
}
}
} else {
echo "0 results";
}
$conn->close();
?>
This always produces a 'Unknown user!' Is there something wrong with my check? I want it to go through each user in the database to check the info with each existing user.
Change
strtoupper($usrUsr) == strtoupper($row["USER"])
To
strtoupper($usrUser) == strtoupper($row["USER"])
Fetch single user from the database by using the username since they are unique for each user.
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase WHERE USER = '" . mysqli_real_escape_string($_POST['usr']) . "' AND PASSWORD = '" . mysqli_real_escape_string($_POST['pass']) . "'";
hey i see your if else contains $usrUsr shoudn't it be $usrUser ? (forgot the e)