So i have fixed the problem with the loop by placing the ifelse statement outside the for loop. So when it is true it is working fine. However when FALSE i get the following error!
Notice: Undefined offset: 2 in webaddhidden.php on line 25 Invalid Login
I am new to PHP and am trying to make a simple login with a text file.
Error Message: if an incorrect username/password is entered :
Invalid LoginInvalid LoginInvalid LoginInvalid Login Notice: Undefined offset: 2 in webaddhidden.php on line 25 Invalid Login
and if the correct username/password the error is:
Invalid LoginMatch Found!
So it prints both the if and the ifelse statements.
Your help would be much appreciated.
Thanks!!!!
The code I am using is:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$matchFound = false;
$fileArray = array();
$myFile = fopen("customers.txt", 'r');
while(!feof($myFile) ) //reads all lines of text file
{
$fileArray[] = fgets($myFile);
}
fclose($myFile);
for($lineCounter = 0; $lineCounter < count($fileArray); $lineCounter++)
{
$exploadedLine = explode("\t",$fileArray[$lineCounter]);
if(trim($exploadedLine[2] == $username && trim($exploadedLine[3])
== $password))
{
echo 'Match Found!';
$matchFound = true;
break;
}
elseif($matchFound == false)
{
echo 'Invalid Login';
}
}
?>
This block of code is actioned as the file is searched - inside the loop.
elseif($matchFound == false)
{
echo 'Invalid Login';
}
It needs to be placed outside the loop.
Few things you can do to fix/improve your code:
You can use file() to directly read lines of text files into an array. http://www.php.net/function.file-get-contents
Make sure indexes of are set in exploded array using isset() function to avoid notices in case the text file is not formatted as expected. http://www.php.net/manual/en/function.isset.php
Move the logic block checking invalid login out of the loop so that it doesn't print invalid error message each time the loop finds a mismatch.
Try using the code below:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$matchFound = false;
$fileArray = file("customers.txt"); //reads all lines of text file
for ($lineCounter = 0; $lineCounter < count($fileArray); $lineCounter++) {
$exploadedLine = explode("\t", $fileArray[$lineCounter]);
if ((isset($exploadedLine[2]) && trim($exploadedLine[2]) == $username) &&
(isset($exploadedLine[3]) && trim($exploadedLine[3]) == $password)) {
echo 'Match Found!';
$matchFound = true;
break;
}
}
if ($matchFound === false) {
echo 'Invalid Login';
}
?>
Related
This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
I need to delete a specific string set from a txt file. Currently, the code works in a similar manner to post the data directly to the file. However, trying to remove the same data, inputted in the same manner, will not allow it. In it's current state, the code looks like this for the string removal.
We were NOT allowed to use prebuilt sorting functions or use functions like str_replace or similar code.
Here is the current code for the string removal:
$blankReplace = "";
$found = false;
$fileData = file($fileInput,FILE_IGNORE_NEW_LINES);
for($i = 0; ($i < count($fileData)) && != $found; $i ++)
{
if($fullNameAndEmail == $fileData[$i])
{
$pos = $i;
$name = $fileData[$i];
$found = true;
}
}
if($found == true)
{
// Exit path. Go to for($j = 0) path
unset($fileData[$pos]);
shuffle($fileData);
}
else
{
//Error Msg
}
$writeToFile = fopen($inputFile,'w+');
for($j = 0;$j<count($fileData);$j++)
{
if(trim($fileData[$j]) != " ")
{
$rewrittenList = trim($fileData[$j])."\n";
fwrite($writeToFile, $rewrittenList);
}
}
The code outputs an error of T_IS_NOT_EQUAL in code upon researching the error. The data comes in as direct data from the file() read, so it should work. The error is pointing at for($i = 0; ($i < count($fileData)) && != $found; $i ++) line currently, but likely also references a similar occurrence in the code.
The data is inputted in the format:
firstname lastname emailaddress
I also need to be able to handle if multiple instances of the mentioned name occur so say we have:
Matt Person emailaddr#email.com
Matt Person emailaddr#email.com
That it will delete one instance, and not all, in cases similar to this.
Any help is appreciated, Thank you for your time in advance.
EDIT:
Example input:
Matthew person person#email.com
John holton person#email.com
Person Name person#gmail.com
The user will input a person's name (in format above) and it will result in removing a person. Say they input into the form:
$fullName = "Matthew person";
$emailAddr = "person#email.com";
The output will edit the data to put the data into a single line again
$fullNameAndEmail = $firstName." ".$lastName." ".$emailAddr;
The output of the code, in this example will remove "Matthew person person#email.com"
So the output in the text file will output:
John holton person#email.com
Person Name person#gmail.com
Edit 2: Code in it's current state
<!doctype HTML>
<html>
<meta charset="utf-8">
<head>
<title>Updating the guest book!</title>
</head>
<body>
<?php
$fileInput = "guestBook.txt";
$fileInputInData = file_get_contents($fileInput); // Gets data from file
$testBool = file_exists($fileInput);
$fullName = trim($_POST["fullName"]);
$emailAddr = trim($_POST["emailAddr"]);
$fileSize = filesize($fileInput);
if(!empty($fullName) and !empty($emailAddr))
{
if($testBool == 0)
{
echo "There was an issue with the file. Please have it checked.</br>";
}
else
{
echo "Made it into else path for testBool </br>";
if($fileSize > 0)
{ #code for truth
echo "Made it into filesize check. Filesize: $fileSize </br>";
$fullNameLen = strlen($fullName);
$emailAddrLen = strlen($emailAddr);
$fullNameArr = explode(" ", $fullName);
$firstName = trim($fullNameArr[0]);
$lastName = trim($fullNameArr[1]);
$fullNameToWrite =$firstName." ".$lastName;
$emailAddrCheck=substr_count($emailAddr, "#");
if ($emailAddrCheck == 1)
{
echo "Email address check passed</br>";
#email addr entered right path
$fullNameAndEmail =$fullNameToWrite." ".$emailAddr." has signed in.\n";
$inputFile = "guestBook.txt";
//$pos = strpos($writeToFile, $fullNameAndEmail);
//$writeToFileEx = explode("\n", $fileInputInData);
$blankReplace = "";
$str = $fileInputInData;
$find = $fullNameAndEmail;
$arr=explode("\n", $str);
Foreach($arr as $key => &$line)
{
If($line == $find)
{
Unset($arr[$key]);
shuffle($arr);
}
}
$writeToFile = fopen($inputFile,'w+');
$rewrittenList = trim($arr)."\n";
fwrite($writeToFile, $rewrittenList);
fclose($inputFile);
}
else {
echo "Email address check failed. Invalid email address entered. </br>
Line 55 occured.</br>";
#email addr entered wrong message
}
//asort(array) sorts array low to high (ascending)
//arsort(array) sorts array high to low (descending)
}
else
{
echo "Did not make it into filesize check. Filesize: $fileSize. Line 63 occured </br>";
}
}
}
else if (empty($fullName) or empty($emailAddr))
{
echo "Error! Line 23: One of the inputs was left empty. Line 69 occured </br>";
}
else
{
echo "Error! Line 23: Did not detect any values in either data area,</br>and program
did not go into first error. Line 73 occured </br>";
}
?>
<br>
</body>
</html>
I think you have overcomplicated it.
I foreach each line and check if it matches.
If it does I unset the line.
After the loop I implode on new line and the string is back to normal but without the $find's.
$str = "Matt Person emailaddr#email.com
John doe doesoe#gmail
Matt Person emailaddr#email.com
Trump donald#whitehouse";
$find = "Matt Person emailaddr#email.com";
$arr=explode("\n", $str);
Foreach($arr as $key => &$line){
If($line == $find){
Unset($arr[$key]);
}
}
Echo implode("\n", $arr);
https://3v4l.org/hmSr7
I am trying to create a CSV Checker which inserts the checked data into a Database and any unsuccessful data added to a .txt file.
I am trying to used regular expressions to validate the data I am inserting, the while loop without any validation works and inserts fine but as soon as regular expressions are used it does not work.
<?php
include_once('connection.php');
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$date = date('d/m/y h:i:s a', time());
$filetxt = "./errors.txt";
$errors = array();
$var1 = 5;
$var2 = 1000;
$var3 = 10;
$sql = '';
if(isset($_POST["Import"]))
{
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while(($emapData = fgetcsv($file, 10000, ",")) !==FALSE)
{
if(isset($_GET['strProductCode']))
{
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode']))
{
$errors['strProductCode'];
}
}
if(isset($_GET['strProductName']))
{
$emapData[1] = $conn->real_escape_string(trim($_GET['strProductName']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductName']))
{
$errors['strProductName'];
}
}
if(isset($_GET['strProductDesc']))
{
$emapData[2] = $conn->real_escape_string(trim($_GET['strProductDesc']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductDesc']))
{
$errors['strProductDesc'];
}
}
if(isset($_GET['intStock']))
{
if (!preg_match("^[0-9]", $_POST['intStock']))
{
$errors['intStock'];
}
}
if(isset($_GET['intPrice']))
{
if (!preg_match("[0-9]", $_POST['intPrice']))
{
$errors['intPrice'];
}
}
if(isset($_GET['dtmDiscontinued'])){
if($emapData[6] == preg_match("[a-zA-Z]", $_POST['dtmDiscontinued']))
{
$emapData[6] = $date;
echo $date;
}else{
$emapData[6] = Null;
}
}
if(count($errors > 0))
{
// errors
$write = "$emapData[0], $emapData[1], $emapData[2], $emapData[3], $emapData[4], $emapData[5], $emapData[6]\r\n";
file_put_contents($filetxt , $write , FILE_APPEND);
}else{
// insert into Database
$sql = "INSERT INTO tblproductdata(strProductCode, strProductName, strProductDesc, intStock, intPrice, dtmAdded, dtmDiscontinued) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$date','$emapData[6]')";
$res=$conn->query($sql);
}
}
fclose($file);
echo "CSV File has successfully been Imported";
echo "<br>";
echo "Any errors within the CVS Database are reported here.";
echo "<br>";
$fh = fopen($filetxt, 'r');
$theData = fread($fh, filesize($filetxt));
fclose($fh);
echo $theData;
}else{
echo "Invalid File: Please Upload a Valid CSV File";
}
header("Location: index.php");
}
?>
My knowledge of PHP is not great but this is my best attempt.
Any help would be greatly appreciated.
There are several issues in your code. Let's start with the regular expressions and your error checking:
Some of your expressions are invalid. Note that each expression needs a delimiting character at the beginng and ending of the expression. In some of your expressions (like ^[0-9]) these delimiters are missing. Please also note that using ^ as a delimiter for a regular expression is not a good choice, because the ^ character also has a special meaning in regular expressions.
This should actually cause PHP Warnings. I see that you have error_reporting enabled; you should also have a look at your display_errors setting.
As mentioned in my comment, you do not assign any values to the $errors array. The statement $errors['strProductName'] in itself does not change the array; this means that $errors will always be empty. You probably mean to do something like:
$errors['strProductName'] = TRUE;
You're actually checking count($errors > 0) where you should be checking count($errors > 0). count($errors > 0) translates to either count(TRUE) or count(FALSE) which both equal 1.
Some other notes:
Some times, you check for $_GET['strProductCode'], but then use $_POST['strProductCode'].
You do not reset the $errors array for each iteration. That means that for each line that you read, the $errors variable will still contain the errors from the previous iteration. As a result, the first invalid line will cause all following lines to be recognized as invalid, too.
You register an error when one of the parameters is of an invalid format, but not when one of them is not set at all (i.e. when isset($_POST[...]) is FALSE). Each of them should probably be sth. like this:
if (isset($_POST['strProductCode'])) {
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode'])) {
$errors['strProductCode'] = TRUE;
}
} else {
$errors['strProductCode'] = TRUE;
}
I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>
I am submitting a form, using the following function (prize.php):
loadmodule('validate'); //This just loads the validate.php function.
$validate = new Validate;
if($_POST)
{
$validateForm = $validate->validateForm();
switch($validateForm)
{
case 1:
$error = 'You\'re not logged in..';
$stop = true;
break;
//If no error = success.
if($validateForm['code'] == "100"){
$won = $val['prize'];
$type = $val['type'];
$success = 'You have won! The prize was '.$won.' '.$type.'';
die($success);
}
}
die($error);
}
This is the function to validate the form (validate.php):
function validate()
{
global $userdata;
if(!is_array($userdata))
return 1; // User not logged in - return error code one.
//If no error, lets show a success message.
$prize = "100";
$text = "dollars";
return array("code"=>"100","prize"=>"$prize","type"=>"$text");
}//If won
}
The above code returns:
Notice: Undefined variable: error in /home/.../public_html/pages/prize.php on line 27
Although, it shouldn't throw an error there, since the die($success) should be triggered by the code 100.
What am I doing wrong?
$error = '';
$stop = false;
switch($validateForm){
case 1:
$error = 'You\'re not logged in..';
$stop = true;
break;
}
//If no error = success.
if($validateForm['code'] == "100"){
$won = $val['prize'];
$type = $val['type'];
$success = 'You have won! The prize was '.$won.' '.$type.'';
die($success);
}
first guess is that the if($validateForm['code'] == "100"){ is ment to be outside the switch.
$validateForm = $validate->validateForm();
returns an array.. later on your're doing a if ($validateForm==1) in the switch.. when $validateForm is an array.
you might have better luck with a simple is_array() if statement than the whole switch
I have this code:
btn_jouer.onRelease = function ()
{
verif = txt_email_user.text;
if (txt_email_user.text == "")
{
txt_erreur.textColor = 16724736;
txt_erreur.text = "Champ(s) manquant(s)";
}
else if (verif.indexOf("#", 0) == -1 || verif.indexOf(".", 0) == -1)
{
txt_erreur.textColor = 16724736;
txt_erreur.text = "Adresse E-mail invalide";
}
else
{
php_login = new LoadVars();
php_login.email = txt_email_user.text;
php_login.sendAndLoad(_root.page_Login, php_login, "POST");
php_login.onLoad = function(succes)
{
if (succes)
{
//txt_erreur.text = php_login.etat;
//return;
if (php_login.etat == "exist")
{
_root.var_user.id = php_login.id;
_root.var_user.nom = php_login.nom;
_root.var_user.prenom = php_login.prenom;
_root.var_user.score = php_login.score;
_root.MovieLogin.unloadMovie();
if (_root._root.selectedPhone == "KS360")
{
_root.gotoAndStop(4);
}
else
{
_root.gotoAndStop(3);
} // end else if
}
else if (php_login.etat == "non")
{
trace (php_login.etat);
txt_erreur.text = "Email non enregistré! veuillez vous s'inscrir";
} // end if
} // end else if
};
} // end else if
};
The "page_Login" is login.php file on the server,
After debugging, the file login.php successfully received Posted data so i got:
$_POST['email'] = "what ever you type in swf form";
The login.php processor file:
if(isset($_REQUEST['email'])){
$email = strtolower(addslashes($_REQUEST['email']));
$DB->_request("select * from gamers where email='$email'");
if($DB->_nr() > 0) {
$row = mysql_fetch_array($DB->Result);
echo "&etat=exist&nom={$row['nom']}&prenom={$row['prenom']}&score={$row['score']}";
//
exit;
}
else {
echo "&etat=non";
exit;
}
}
Here above, the $DB->_nr() always returns "0" even the email address exists!
I have tried to create a simple html page having a form with method POST and have a simple input type text with a name="email"
When i write my email which is valid in the database and hit submit $DB->_nr() returns 1.
This really is driving me crazy, i'm sure that the email address exists, the login.php page receive posted data "email = validemail#domain.com" from SendAndLoad(); but mysql_num_rows returns 0.
Any one there had the same issue??
Any help would be so much appreciated!
Barry,
Use the following code in PHP to compare the email in both cases: given from flash and from HTML form:
if(isset($_REQUEST['email'])){
//createa the testFile.txt and give it attributes with 0777 for permission (in case you are under linux)
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "-".$_REQUEST['email']."-\r\n");
fclose($fh);
$email = strtolower(addslashes($_REQUEST['email']));
$DB->_request("select * from gamers where email='$email'");
if($DB->_nr() > 0) {
$row = mysql_fetch_array($DB->Result);
echo "&etat=exist&nom={$row['nom']}&prenom={$row['prenom']}&score={$row['score']}";
//
exit;
}
else {
echo "&etat=non";
exit;
}
}
if you test for both of the cases, you will be able to compare the two exact forms. I have put "-" in the front and the end of it just to see if there are any whitespaces next to the email value.
Please reply with a compare result. thank you.