PHP retrieving elements from file - php

I am retrieving information from a text document and trying to test if the users input matches any of the information in the text document.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<?php
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $_POST["usernamepassword"];
while(!feof($userpassfile)){
$line = fgets($userpassfile);
$users = explode("#", $line);
for($x=0; $x<sizeof($users); $x++){
if($users[$x]==$username){
header('Location: booking.php');
} else {
header('Location: login.php');
}
}
}
if($username=="ADMINadmin"){
header('LOCATION: admin.php');
}
fclose($usernamefile);
When it checks the information in the txt, it seems to only check the first and last element. I don't know why. I thought it was because in the for loop there was a < not <=, however when set to <= it wont check the file at all. Any ideas, cheers!

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<?php
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $_POST["usernamepassword"];
if($username=="ADMINadmin"){
header('LOCATION: admin.php');
fclose($usernamefile);
exit; // If user is admin, there is no need for further checking.
} else {
header('Location: login.php'); // Set redirect to login.php by default
}
while(!feof($userpassfile)){
$line = fgets($userpassfile);
$users = explode("#", $line);
if(in_array($username, users) {
// If user was found, override redirect to login.php
// and set it to booking.php
header('Location: booking.php');
// And there is no need to iterate further, so stop the loop
break;
}
}
fclose($usernamefile);

Maybe your code must look like this
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<?php
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $_POST["usernamepassword"];
if($username=="ADMINadmin"){
header('LOCATION: admin.php');
} else {
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
$in_file = false;
while(!feof($userpassfile)){
if($in_file) {
break;
}
$users = explode("#", fgets($userpassfile));
$in_file = in_array($username, $users);
}
if($in_file) {
header('Location: booking.php');
} else {
header('Location: login.php');
}
fclose($userpassfile);
}

<?php
session_start();
// note here that i has removed your DOCTYPE INPUT ...
$location = NULL;
$defaultPage = "login.php";
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $username;
// this test must be the first ... for performance
if($username=="ADMINadmin"){
$location = "admin.php";
}
else {
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
while(!feof($userpassfile)){
$line = fgets($userpassfile);
$users = explode("#", $line);
for($x=0; $x<sizeof($users); $x++){
// i have added trim : maybe there is spaces or other invisible chars in your file
// note: if your login system is case insensitive so use this condition :
// if(strtolower(trim($users[$x])) == strtolower($username)){ ... }
if (trim($users[$x]) == $username){
$location = "booking.php";
break;
}
// here it is the mistake : if the first token of the first line is not the connected user
// so php will redirect to login page
/*
else {
header('Location: login.php');
}
*/
}
}
fclose($usernamefile);
}
// it is a good practice to be explicit... for maintenance simplicity
if (is_null($location)) {
$location = $defaultPage;
}
header("Location: " . $location);
?>

Related

Code executing both if and else statements together how do i fix?

the code is running to match username with password and if both correct redirecting to another page but that and the else statements both run
Code:
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
print_r($AccountDetails);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username){
if ($StoredPassword == $Password) {
header('Location: Main.php');
}
else {
$IncorrectDetails = 1;
}
}
else {
$IncorrectDetails = 1;
}
}
if ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
its expected to come up with a popup when incorrect and redirect when correct
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username && $StoredPassword == $Password){
$CorrectDetails = 1;
} else {
$IncorrectDetails = 1;
}
}
if(isset($CorrectDetails) && $CorrectDetails == 1){
header('Location: Main.php');
}else ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
You are redirect to another page it's not a proper way instead of that you can use a variable just like you have used in else and outside the loop you can redirect to another page.
That's beacuse the redirection is not instantaneus, php code still being processed.
So, just after header('Location: Main.php'); do exit; to stop at all your script in that point, and let the redirection works.
header('Location: Main.php');
exit;
Also, you musn't print anything before the header() instruction (remove print_r()).

PHP Login using a txt file

hello I am working on a project where i have to create a php login using a text file. I have the basic code laid out but when I put a username and password on file and try signing in, it does not work. I could really use some advise. thank you. The code below is my login php file.
<?php
session_start();
$User = $_GET["user"];
$Pass = $_GET["password"];
if (!strpos($User,"#")) {
$User = $User . "#etown.edu";
}
$Validuser = false;
$_SESSION["user"] = $User;
$_SESSION["pass"] = $Pass;
$_SESSION["login"]= $Validuser;
?>
<!DOCTYPE html>
<html>
<body>
<?php
print "<h2>Welcome $User</h2>";
$infile = fopen("account.txt","r");
$entry = fgets($infile);
while (!feof($infile)) {
$array = explode(" ",$entry);
if ($array[0] == $User){
$name = $array[0];
$code = $array[1];
$code = substr($code,0,strlen($code)-1);
}
$entry = fgets($infile);
}
print "Name: $name <br/>";
print "pass on file: $code <br />";
fclose($infile);
if ($name==$User && $code==$Pass)
$Validuser = true;
$_SESSION["login"] = $Validuser;
print "That's All!<br/>";
if ($Validuser) {
print "Welcome valid user<br/>";
}
else {
print "You are not a valid user. Go become one first!";
print '<script type="text/javascript">';
print ' //document.location = "register.html";';
print '</script>';
}
?>
</body>
</html>
try adding this
$User = isset($_GET["user"]) ? $_GET["user"] : '';
$Pass = isset($_GET["user"]) ? $_GET["password"] : '';
$name ='';
$code='';
i'm assuming your txt file is like this
ja#etown.edu 12345
ja2#etown.edu 12345
ja3#etown.edu 12345

Steam OpenID API

I want to make Steam login for my site. The only thing I want from Steam is to login, get his username and start a session for that user. I followed a tutorial on YouTube, did basically everything on that video but when I press sign in through Steam I get: example.com/(()%7D.
Code:
<?php
include "includes/apikey.php";
include "includes/openid.php";
ob_start();
$OpenID = new LightOpenID("http://astral-gaming.com");
session_start();
?>
This is my header. Also, I put this php on the middle of the doc (because I want sign in to appear after all navbar elements:
<?php
if(!$OpenID->mode) {
if(isset($_GET['login'])) {
$OpenID->identity = "http://steamcommunity.com/openid";
header("Location: ($OpenID->authUrl()}");
}
if(!isset($_SESSION['T2SteamAuth'])) {
$login = "<li><img src=\"http://steamcommunity- a.akamaihd.net/public/images/signinthroughsteam/sits_small.png\"/></li>";
}
} elseif($OpenID->mode == "cancel"){
} else {
if(!isset($_SESSION['TF2SteamAuth'])) {
$_SESSION['TF2SteamAuth'] = $OpenID->validate() ? $OpenID->identity: null;
$_SESSION['TF2SteamID64'] = str_replace("http://steamcommunity.com/openid/id/", "", $_SESSION['TF2SteamAuth']);
if($_SESSION['TF2SteamAuth'] !== null) {
$Steam64 = str_replace("http:// (ignore space)steamcommunity.com/openid/id/", "", $_SESSION['TF2SteamAuth']);
$profile = file_get_contents("http:// (ignore space) api.steampowered.com/IsteamUser/GetPlayerSummaries/v0002/?key={$api}&steamids=($Steam64)");
$buffer = fopen("cache/{$steam64}.json", "w+");
fwrite($buffer, $profile);
fclose($buffer);
}
header("Location: index.php");
}
}
if(isset($_SESSION['T2SteamAuth'])) {
$login = "<li>Steam LogOut</li>";
}
if(isset($_GET['logout'])) {
unset($_SESSION['T2SteamAuth']);
unset($_SESSION['T2SteamAuth']);
header("Location: index.php");
}
You have bad/mismatched bracketing/bracing everywhere in your code:
header("Location: ($OpenID->authUrl()}");
^-- this should probably be a {?

PHP If Statements Not Firing

I'm currently building a system for a football league. And are currently working on the script file for adding results. Most of the script works and the result is always successfully added to the database. However the authentication part seems to fail. The if statement on line 12 does not seem to fire and I can't understand why.
My code can be found in the pastebin link here: http://pastebin.com/ty4pdGgn
<?PHP
include 'functions.php';
dbConnect();
//$userEmail = mysql_real_escape_string($_POST["userEmailText"]);
$userCode = mysql_real_escape_string($_POST["userPasscodeText"]);
$authenticated = false;
$userEmail = "info#example.com";
if ($userEmail == "info#example.com") {
header('Location: ../results.php?error=authentication');
}
$allUsers = mysql_query("SELECT * FROM accounts WHERE email = '$userEmail'");
while ($thisUser = mysql_fetch_assoc($allUsers)){
if ($userCode != $thisUser['passCode']) {
header('Location: ../results.php?error=authentication2');
}
echo $thisUser['passCode'];
$authenticated = true;
$userID = $thisUser['userID'];
}
if (!$authenticated) {
header('Location: ../results.php?error=authentication3');
}
$dateSubmitted = $_POST['submissionDate'];
$homeTeam = $_POST['homeTeam'];
$awayTeam = $_POST['awayTeam'];
$homeGoals = $_POST['homeGoals'];
$awayGoals = $_POST['awayGoals'];
if ($homeTeam == $awayTeam) {
header("Location: ../results.php?error=team");
}
if (getTeamLeague($homeTeam) != getTeamLeague($awayTeam)) {
header("Location: ../results.php?error=league");
} else {
$leagueID = getTeamLeague($homeTeam);
}
if ($homeGoals > $awayGoals) {
$winnerID = $homeTeam;
} else if ($homeGoals < $awayGoals) {
$winnerID = $awayTeam;
} else if ($homeGoals == $awayGoals) {
$winnerID = -1;
}
$cQuery = mysql_query("INSERT INTO results VALUES ('', $userID, '$dateSubmitted', $leagueID, $homeTeam, $homeGoals, $awayTeam, $awayGoals, $winnerID, 0)");
if ($cQuery){
header('Location: ../results.php');
} else {
echo mysql_error();
}
?>
Any help with this matter will be much appreciated. The functions.php contains no errors as this is all to do with database entry and not the authentication.
Put a die(); after the header("Location:...");
As your comparison code (the "if" part on line 12) that you pasted has to work, i have two advice:
Put a die(); or exit(); after the header() part.
Try looking here, as I am not sure if header() will work, while the location path you set is relative. Basic advice is to always use base paths for redirects, like "http://your.site.com/script.php").

want to place part of php code somewhere else on page

I'm very new to php. I found some CMS like code for east text editing here on SO and now I'm trying to implement it on our micro site.
My problem is, that I want login error report to show on exact position on the page - just under the login button.
Can someone tell me how can I put that error report text whereever I want? I don't want to override it with CSS positioning.
In basic, I want to put that p class="error":
<?php
if (empty($_POST) && isset($_GET['action'])) {
$action = $_GET['action'];
switch ($action) {
case 'logout':
session_unset();
session_destroy();
break;
}
}
if (!isset($_SESSION['user'])) {
$user = '';
$pass = '';
if (isset($_POST['login'])) {
$user = strtolower(trim($_POST['user']));
$pass = $_POST['pass'];
$errors = array();
if ($user == '' || $user != '1') {
$errors['user'] = '';
}
if ($pass == '' || $pass != '1') {
$errors['pass'] = '';
}
if (empty($errors)) {
$_SESSION['user'] = $user;
} else {
echo '<p class="error">Insert correct ';
if (isset($errors['user']))
echo 'name';
if (count($errors) == 2)
echo ' a ';
if (isset($errors['pass']))
echo 'password';
echo '.</p>', "\n";
}
}
}
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
?>
somewhere else in the whole code of my page. Do I need to cut out something from that php code, or do I need to write new part of code for that?
Thank you for you help, Matej
Instead of just doing 'echo' all over the place, which means you get output at the place where the PHP code is embedded in the page, set some flags/message variables to output later.
e.g.
<?php
$errors = false;
$msgs = '';
if (....) {
$errors = true;
$msgs = "something dun gone wrong";
}
?>
... various bits of your html go here ...
<?php if ($errors) { echo $msgs; } ?>
... more html here ...

Categories