I am trying to check if a user has taken a quiz before and if he/she has, I want them to be not able to take the quiz again. I implemented the code to do this by using cookies and for some reason my code refuses to stop a user from taking the quiz again. I've been staring at this for a very long time now so help would be nice!
Notes: $_SESSION["index"] is set to 0 initially from a previous page and $_COOKIE['quizTakers"] is an empty array initially. Each Question comes one at a time.
<?php
session_start();
#get array of quizTakers from cookie
$addUser = unserialize($_COOKIE['quizTakers']);
$userN = $_SESSION['username'];
#check if user has taken quiz already and make sure you only check once and not after every question submit
if(count($addUser) != 0 && intval($_SESSION["index"]) == 0 ){
foreach ($addUser as $user) {
if( strcmp($userN,$user) ){
echo "You already took the quiz! <br \>";
echo "<form action=\"changeUser.php\" method=\"post\"> Go Back: <input type=\"submit\"><br \> </form>";
exit();
}
}
array_push($addUser, $userN);
setcookie('quizTakers', serialize($addUser), time()+86400);
echo "loop was entered <br />";
}
#if array is empty(this is should execute the every first time someone takes the quiz
elseif (count($addUser) == 0) {
#add user to array if this is first person taking a quiz yo
array_push($addUser, $userN);
setcookie('quizTakers', serialize($addUser), time()+86400);
echo "cookie added line 29 <br/>";
}
$indexTemp = intVal($_SESSION["index"]);
if(isset($_SESSION["notFirstIndex"])){
#get array of correct answers
$correctAns = $_SESSION["correctAnswers"];
#get particular answer at current index
$currentCorrectAns = intval($correctAns[$indexTemp]) +1;
$userAns = intval($_POST['ans']);
echo "The User picked: ".$userAns." and the correct Answer was: ".$currentCorrectAns."<br/>";
if($userAns == intVal($currentCorrectAns)){
echo " you were correct! <br />";
$_SESSION["totalCorrect"] += 1;
}
else{
echo "you were wrong";
$_SESSION["totalIncorrect"] +=1;
}
}
elseif(!isset($_SESSION['notFirstIndex'])){
echo "Welcome to your quiz, $userN <br />";
echo "You havent answered any questions yet! <br />";
}
?>
<!DOCTYPE html>
<html>
<HR>
</html>
<?php
#When questions are over show results
if($_SESSION["numQuestions"] == $indexTemp){
$_SESSION["index"] = 0;
echo "Your Results are: <br /> ";
echo "Total Questions: ".$_SESSION["numQuestions"]."<br/>";
echo "Total Correct: ".$_SESSION["totalCorrect"]."<br/>";
echo "Total Incorrect: ".$_SESSION["totalIncorrect"]."<br/>";
$percentage = (intval($_SESSION["totalCorrect"]) / intval($_SESSION["numQuestions"])) * 100 ;
echo "Percentage Rightht: $percentage % <br/ >";
echo "<form action=\"process.php\" method=\"post\"> Back to Main screen: <input type=\"submit\"><br \> </form>";
$takers = unserialize($_COOKIE['quizTakers']);
echo $takers[0];
if(count($takers) == 1){
echo "<br />";
echo "You were the first Quiz Taker: <br />";
echo "Total Takers: 1 <br />";
echo "Number Right: ".$_SESSION["totalCorrect"]."<br/>";
echo "Number Incorrect: ".$_SESSION["totalIncorrect"]."<br/>";
echo "Average: $percentage % <br/ >";
exit();
}
exit();
}
$filename = $_SESSION["quizOfTheDay"];
$quizStuff = file($filename);
$ctr =1;
$questionInfo = $quizStuff[$indexTemp];
$questionParse = explode("#", $questionInfo);
#$_SESSION["correctAns"] = $questionParse[2];
#echo $_SESSION["correctAns"]." from line 56 <br />";
$_SESSION['notFirstIndex'] = "true";
$answerChoices = explode(":",$questionParse[1]);
echo "$questionParse[0]? <br />";
?>
<!DOCTYPE html>
<html>
<form action="questions.php" method="post">
<?php
foreach ($answerChoices as $answerChoice) {
echo "<input type='radio' name='ans' id='q1' value=".$ctr."> <label for='q1'>".$answerChoice."</label> <br />";
$ctr +=1;
}
$_SESSION["index"] = $indexTemp +1;
?>
<input type="submit" name="submit" value="GO!">
</form>
</html>
Before the cookie is set, $_COOKIE['quizTakers'] doesn't exist, and when you call unserialize() on this you set $addUsers to false. Then when you try to do array_push($addUser, $userN);, this fails because $addUser isn't an array, so $addUser is still false. Then you put this into the cookie.
The next time the user runs the script, you read false from the cookie, and the username isn't found in this, so you don't stop the user from taking the quiz again.
You're making this much more complicated than it needs to be. You don't need to put an array into the cookie, because cookies aren't shared by all the users. Just set a cookie to a simple string and test whether the cookie is set.
if (isset($_COOKIE['took_quiz'])) {
echo "You already took the quiz! <br \>";
echo "<form action=\"changeUser.php\" method=\"post\"> Go Back: <input type=\"submit\"><br \> </form>";
exit();
}
setcookie('took_quiz', 'true', time()+86400);
As others pointed out, users can get around this by clearing cookies. So if you need something more secure, you need to implement a login system and use a database or file to track which users have already taken the quiz.
I have not read your code, but did you foundamentally understand the concept of a cookie/session?
A cookie will store data at the browser and sends it everytime the website is requested. A session, will store the data on the server, but will store a cookie a the clients side to identify the user on subsequent requests.
So the user can simple wipe the cookies (in both cases) and the server does not know, that this user has ever taken the quiz.
What you can try is a combination of IP address and browser metric, but beware that IP adresses can change (very quick ;) )
Cookies could be erased by the user and you wouldn't know if they did your quiz or not .
You may need to force people to register to gain access to your quiz if you want a permanent way to know if they completed them or not as cookies can easily be wiped.
Related
In my project, i have a login page with verification code.
Some verification code of login page is like:
<form class="form-login" action="index.php" method="post">
<input type="text" name="code" class="form-control" placeholder="verification code">
<img id="codeImg" src="create_code.php" alt="not clear, another" style="cursor: pointer; vertical-align:middle" onClick="create_code()">
</form>
In create_code.php, some code about creating verification code is like:
session_start();
header("Content-type: image/png");
$str = "1,2,3,4,5,6,7,8,9,a,b,c,d,f,g";
$list = explode(",", $str);
$cmax = count($list) - 1;
$verifyCode = '';
for ( $i=0; $i < 5; $i++ ){
$randnum = mt_rand(0, $cmax);
$verifyCode .= $list[$randnum];
}
$_SESSION['code'] = $verifyCode; // stor verifycode in session
In index.php, I need to check the inpu verifycode and session verifycode, some code is like:
session_start();
if(!isset($_GET['log_out']) && ($_POST['code'] != $_SESSION['code']))
{
echo "verifycode is wrong!<br />" . "<meta http-equiv='refresh' content='2;url=index.html'>";
die();
}
But unlucky, it is fail. I have found there is nothing in $_SESSION['code']。$_SESSION['code'] should be a value, but a blank instead.
besides, it worked OK a few days ago, but it fails today. I have no changed any code, it seems nothing wrong, who can help me ?
I have solved this problem。 My Linux server disk space is 100%. When I deleted some files, it works Ok. Is there some session log file can print prompt message ?
This may sound really broken but essentially my intentions are for in php1, have a name for example validate to match a regex, if it fails to meet the conditions it will then redirect to php2 where there awaits a form where a user can retype it and submit it back to php1 where it will do the checks again. Then finally in the first php, if everything works ok it will echo it back.
Also how would i expand it so multiple things such as credit cards etc. can be validated too?
Thanks
php1
if (isset ($_POST["CardHolder"])) {
cardholder = $_POST["CardHolder"];
cardholder = sanitise_input($cardholder);
if (!preg_match("/^[a-zA-Z\s]{1,40}$/", $cardholder)) {
$errMsg .= "First name can only contain alpha characters, please re-enter";
$newcardholder = $_POST["newcardholder"];
$cardholder = $newcardholder;
}
else {
$cardholder = $_POST["CardHolder"];
}
if ($errMsg != "") {
header("Location: fix_order.php?errMsg=".$errMsg)
}
php2 (fix_order.php)
if (isset ($_GET["errMsg"])){
$cardholder = $_GET["errMsg"];
echo "<form action='process_order.php' method='post'>"
."<p><label>$cardholder:</label>"
."<input type='text' name='newcardholder'/></p>"
."<p><input type='submit' value='Submit'/>";
"</form>";
}
When calling header("Location:...") you need to give the full and absolute URL.
so header("Location: fix_order.php") will not work.
My colleague and me are having a hard time trying to solve this problem. We have a special kind of webshop, because we have customers and sub-customers. If the person logged in is a sub-customer, we want to show some extra html on our page. This works, but if a sub-customer logs out, and a normal customer logs in, the extra html is still visible, but we don't understand how this is possible. The problem is also vice versa: if the first logged in is a normal user, then logs out, then a sub-customer logs in, the extra html is not visible.
1. loginck.php
//after the user types his e-mail end password, we check if its a normal user or a sub-user.
If normal user then => $_SESSION['multiklant'] = 0;
else sub-user then => $_SESSION['multiklant'] = 1;
else $_SESSION['multiklant'] = 0; //user not found
2. index.php
if ($_SESSION['multiklant'] == 1) {
$userid = $_SESSION['userid'];
echo "<div class='col-md-3'>";
echo "<label for='leveradres'>Leveradres*:</label><br/>";
echo "<select id='leveradres' class='form-control'>";
echo "<option value='0'>Selecteer...</option>";
$qry = "SELECT * FROM LEVERADRESSEN WHERE LA_EMAIL = '" . $_SESSION['klemail'] . "'";
$res = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($res)) {
echo "<option value='" . $row['LA_ID'] . "'>" . $row['LA_NAAM'] . "</option>";
}
echo "</select>";
echo "</div>";
}
3.1 logout click on index.php
$("#logout").click(function () {
var lgout = $.get("logout.php");
lgout.done(function (data) {
$(".show-2").trigger("click");
$("#logout").addClass("hidden");
});
});
3.2 logout.php
<?php
session_start();
$_SESSION = array();
session_unset();
session_destroy();
header("Location:index.php");
exit();
?>
As you can see, we used AJAX here, but even without the problem stays. If possible we would like to keep the AJAX, but if not it can be deleted. Also a combination, where the redirect is not in de php but in the javascript part.
Could this be a caching problem? Because if we reload our browser without cache, it al works.
We are searching the internet, including this site already for 6 hours...
Code tested in Chrome on MAC and Internet Explorer 11 on Windows, gives no difference.
Your logout does a header location with exit. In other words: is the $.get('logout.php') done?
Why do you do a redirect serverside? So full page and scripts will be reloaded! And you're waiting for 'done'. Do this:
remove the lines with header and exit from logout.php
After the session is destroyed, the page is ready and the .done callback will be executed.
Look at response header after logout and check "cache-control".
I think problem in cache.
YES!
After searching a long time and trying some of your suggestions (which we are grateful for, I upvoted the most useful ones) we found the solution.
It was after reading this it all came (more) clear. Index.php is our only page with content. So yes, we start a session there, but if we change the session variables afterwards via AJAX, index.php doesn't track those changes.
This is why we tried to refresh the page after logging out, so the sessions variables would be refreshed to. That didn't work. It was until we did also a refresh after logging in also, it al worked, although with some page refresh for the users.
So we put those blocks of code in separate php files and check when needed with AJAX
This is our solution:
1. When the user logs in:
$("#blockleveradressen").load("leveradressen.php");
var testmultiklant = $.get("testmultiklant.php");
testmultiklant.done(function (data){
if(data == 3){
$("#een").removeClass().addClass("col-md-3");
$("#twee").removeClass().addClass("col-md-3");
$("#drie").removeClass().addClass("col-md-3");
}else {
$("#een").removeClass().addClass("col-md-4");
$("#twee").removeClass().addClass("col-md-4");
$("#drie").removeClass().addClass("col-md-4");
}
});
2. leveradressen.php
include "include/session.php";
include "include/MyConnect.php";
if ($_SESSION['multiklant'] == 1) {
$userid = $_SESSION['userid'];
echo "<div class='col-md-3'>";
echo "<label for='leveradres'>Leveradres*:</label><br/>";
echo "<select id='leveradres' class='form-control'>";
echo "<option value='0'>Selecteer...</option>";
$qry = "SELECT * FROM LEVERADRESSEN WHERE LA_EMAIL = '" . $_SESSION['klemail'] . "'";
$res = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($res)) {
echo "<option value='" . $row['LA_ID'] . "'>" . $row['LA_NAAM'] . "</option>";
}
echo "</select>";
echo "</div>";
}
3. testmultiklant.php
include "include/session.php";
if ($_SESSION['multiklant'] == 1) {
echo 3;
} else
{
echo 4;
}
4. index.php
<div id="blockleveradressen">
</div>
<div id="een" class="col-md-4">
<label for="datepicker">Leveringsdatum*:</label><br/>
<input type="text" id="datepicker" readonly="readonly"/>
<input type="hidden" id="datepickerAlt" readonly="readonly" visible="false">
</div>
<div id="twee" class="col-md-4">
<label for="timepicker">Leveringstijdstip*:</label><br/>
<input type="text" id="timepicker" class="time"/>
</div>
<div id="drie" class="col-md-4">
<label for="betaalMethode">Betaalmethode*:</label><br/>
<select id="betaalMethode" class="form-control">
<option value="Overschrijving">Overschrijving</option>
<option value="Visa">Visa</option>
<option value="Cash">Cash</option>
</select>
</div>
Just need to clean up the code, but this works. Just learned another lesson: single-paged websites and php (session more specific) are not best friends :-)
Ok so here's my problem, I am trying to use information from my database to create a change password script for a secondary account. However the password for the main account is hashed in md5. No matter what I try I cannot get the base64/md5 code to match up when doing a comparison.
This is the code I use to enter the information into the database for the second account.
$nametrim = StrToLower(Trim($ya_username));
$pwdtrim = StrToLower(Trim($user_password));
$Salt = base64_encode(md5($nametrim.$pwdtrim, true));
$result2 = $db->sql_query("call adduser('$nametrim', '$Salt', '0', '0', '0', '$rmad', '$ya_user_email', '0', '0', '0', '0', '0', '0', '0', '', '', '$Salt')") or die ("Can't execute query.");
The main account and secondary account register fine, no problems there, the problem comes with my change password script when trying to recreate the base64 code.
$unametrim = StrToLower(Trim($uname));
$unamemd5 = md5($unametrim);
$Salt1 = base64_encode($unamemd5.$upass);
I should note that $upass is already in MD5 when pulled from the database, hence the reason I only MD5'd the username. No matter what I try I cannot get them to match at all.
Here is the rest of my change password page as a reference, hopefully someone can help me with this problem.
<?php
/****************************************************************************/
/* Generated by Module Creator - By Disipal Designs (www.disipal.net) */
/* PHP-Nuke Tools v4.00 */
/****************************************************************************/
if (!defined('MODULE_FILE')) {
die ("You can't access this file directly...");
}
require_once("mainfile.php");
$module_name = basename(dirname(__FILE__));
get_lang($module_name);
include("header.php");
define('INDEX_FILE', true);
global $userinfo, $db;
$fname=substr(strrchr($_SERVER['PHP_SELF'],'/'), -(strlen(strrchr($_SERVER['PHP_SELF'],'/')) -1));
$uname = $userinfo['username'];
$upass = $userinfo['user_password'];
$unametrim = StrToLower(Trim($uname));
$unamemd5 = md5($unametrim);
$Salt1 = base64_encode($unamemd5.$upass);
$result = $db->sql_query("SELECT * FROM users WHERE name='$unametrim'") or ("Can't execute query.");
$row = $db->sql_fetchrow($result);
$uid = $row['ID'];
$aname = $row['name'];
$passwd = $row['passwd'];
$passwd2 = $row['passwd2'];
$ipno = $row['idnumber'];
$rmad = $_SERVER['REMOTE_ADDR'];
OpenTable();
echo "<p align='center'><b><u>Change Game Account Password</u></b></p>";
if (isset($_POST['upass'])) {
$funame=$_POST['uname'];
$fpasswd=$_POST['pass1'];
$fpasswd2=$_POST['pass2'];
$fupass=$_POST['upass'];
$encryptpass = md5($fupass);
$encryptpasswd = md5($fpasswd);
$encryptpasswd2 = md5($fpasswd2);
$nametrim = StrToLower(Trim($funame));
$pwdtrim = StrToLower(Trim($fupass));
$Salt = base64_encode(md5($nametrim.$pwdtrim, true));
if ($fpasswd == $fpasswd2) {
$db->sql_query("CALL changePasswd ($result->quoteSmart'$nametrim', '$Salt')");
$db->sql_query("CALL changePasswd2 ($result->quoteSmart'$nametrim', '$Salt')");
echo "<p align=\"center\"><b>Game account password has been changed successfully</b></p>";
echo "<form method=\"POST\" action=\"modules.php?name=Change_PW\"><p align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Continue\"></p></form>";
}
}
if (isset($_POST['passwd1'])) {
$funame=$_POST['uname'];
$fpasswd=$_POST['passwd1'];
$fpasswd2=$_POST['passwd2'];
$fupass=$_POST['upass'];
$encryptpass1 = md5($fupass);
$encryptpasswd = md5($fpasswd);
$encryptpasswd2 = md5($fpasswd2);
$nametrim = StrToLower(Trim($funame));
$pwdtrim = StrToLower(Trim($fpasswd));
$Salt = base64_encode(md5($nametrim.$pwdtrim, true));
if (empty($fpasswd) || empty($fpasswd2)){
echo "<p align=\"center\"><b>You cannot leave the password field blank</b></p>";
echo "<form method=\"POST\" action=\"modules.php?name=Change_PW\"><p align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Continue\"></p></form>";
} else {
if ($encryptpasswd == $encryptpasswd2) {
$db->sql_query("CALL changePasswd ($result->quoteSmart'$nametrim', '$Salt')");
$db->sql_query("CALL changePasswd2 ($result->quoteSmart'$nametrim', '$Salt')");
echo "<p align=\"center\"><b>Game account password has been changed successfully</b></p>";
echo "<form method=\"POST\" action=\"modules.php?name=Change_PW\"><p align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Continue\"></p></form>";
} else {
echo "<p align=\"center\"><b>Passwords did not match, please try again</b></p>";
echo "<form method=\"POST\" action=\"modules.php?name=Change_PW\"><p align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Continue\"></p></form>";
}
}
}
if (isset($_POST['upass']) || isset($_POST['passwd1'])) {
} else {
if ($passwd != $Salt1) {
echo "<p align=\"center\"><b>Your game account password does not match your web account.</b><br>Update game account password to match web account?</p>";
echo "<p align=\"center\"><form method=\"POST\" action=\"modules.php?name=Change_PW\">
<input type=\"hidden\" name=\"uname\" value=\"".$uname."\">
<input type=\"hidden\" name=\"upass\" value=\"".$upass."\">
<input type=\"hidden\" name=\"pass1\" value=\"".$passwd."\">
<input type=\"hidden\" name=\"pass2\" value=\"".$passwd2."\">
<p align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Update Password\"></p>
</form></p>";
} else {
if (isset($_POST['passwd1'])) {
echo "<form method=\"POST\" action=\"modules.php?name=Change_PW\"><p align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Continue\"></p>";
} else {
echo "<p align=\"center\"><form method=\"POST\" action=\"modules.php?name=Change_PW\">
<input type=\"hidden\" name=\"uname\" value=\"".$uname."\">
<p align=\"center\">New Password:<br><input type=\"password\" name=\"passwd1\"\"></p>
<p align=\"center\">Confirm Password:<br><input type=\"password\" name=\"passwd2\"\"></p>
<p align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Change Password\"></p>
</form></p>";
}
}
}
echo "Test Area<br>Salt: $Salt1<br>Passwd: $passwd<br>unametrim: $unametrim<br>unamemd5: $unamemd5<br>upass: $upass";
CloseTable();
include("footer.php");
?>
Any ideas on what I can do here, been working on this for ages and haven't been able to figure out how to get it working properly.
It looks like you will need to rethink your entire approach to whatever it is you are actually trying to accomplish, because what you appear to be attempting to do is fundamentally impossible due to the nature of MD5 or any cryptographic hash function.
When you only have a cryptographic hash of a value and not the original value, it's impossible, for all practical purposes, to do anything further with the value.
I should note that $upass is already in MD5 when pulled from the database, hence the reason I only MD5'd the username. No matter what I try I cannot get them to match at all.
That's be cause there's nothing meaningful that you can combine with md5('foo') to get the same result as md5('foobar'). Hashes can't be concatenated, just like they can't be reversed.
md5('foo') = acbd18db4cc2f85cedef654fccc4a4d8
md5('bar') = 37b51d194a7513e45b56f6524f2d51f2
md5('foobar') = 3858f62230ac3c915f300c664312c63f
You don't show the code where the salt value is actually or where in the database it is stored, but it presumably has to be stored somewhere or it would be rather pointless to have assuming it's a salt in the usual sense... so the thing for you to do would be to simply fetch and reuse it, because it's impossible to regenerate it if you don't have the plain-text version of the password in hand.
Of course, the fact that there's a salt in here somewhere suggests that the password may not even be what's represented in the md5 value you think is the password. The point of a salt is that you store an md5 of (thing you want to secure + salt) so that if you have a security breach, then the thing you stored isn't easily looked up in a table like the one this site has. (They aren't "decoding" MD5 -- that's impossible. They have tables of hashes and the values that generated those hashes. The three md5 values I used as examples are terrible passwords, of course, but that site has those three in its lookup tables already... passwords stored as MD5 without a salt are much more easily cracked).
The only other option I see that you have, after asking the user if they want to change one password to the other would be to actually require that they "confirm" their main password, which gives you a chance to get your hands on the plain-text version of the password, which you should, of course, validate as authentic before acting on it.
[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.