php - check if value is in csv-file - php

im trying to check if two php-values are in one line in the csv fiel.
csv:
password, name
12345, max
44444, emil
but when my variable is $password="123" and in the csv file its "12345" he accepts it.
But, how can i check if its 100% equals? I dont understand why "123" is enough?
$search = $name;
$search2 = $password;
$lines = file('Benutzer.csv');
$line_number = false;
$line_number2 = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE );
$line_number2 = (strpos($line, $search2) !== FALSE );
}
if($line_number and $line_number2 ){
header('Location: alert_anmelden_erfolgreich.php');
}
else{
header('Location: alert_anmelden_NICHT_erfolgreich.php');
}

strpos looks for a substring in a string. So first things first"
strpos('12345','345')
will return 2 since the substring exists starting at that index. In your case:
strpos('12345','123')
or really 1,12,123,1234,12345 will all return the position 0. Now, when equating as you do to false you're essentially getting:
0==`false`
which is of course true because 0 an be casted to false. As #u_mulder, commented use of the full type equality operator === would fix that, but still won't solve your problem!. What you want is strcmp, which will return 0(false) only if the strings are identical, and can be used like you wanted. You could also use === or == between the strings since you don't care about 'less/more' string.
if( $line === $search )

Related

Check whether the given two words are existing in a PHP string

I want to check if a string contains two specific words.
For example:
I need to check if the string contains "MAN" & "WAN" in a sentence like "MAN live in WAN" and returns true else false.
What I've tried is looping string function in a conditional way:-
<?php
$data = array("MAN","WAN");
$checkExists = $this->checkInSentence($data);
function checkInSentence( $data ){
$response = TRUE;
foreach ($data as $value) {
if (strpos($string, $word) === FALSE) {
return FALSE;
}
}
return $response;
}
?>
Is it the right method or do I've to change it? How to implement this any suggestions or idea will be highly appreciated.
Note: data array may contain more than two words may be. I just need check whether a set of words are exists in a paragraph or sentence.
Thanks in advance !
It's alsmost good. You need to make it set the response to false if a word is not included. Right now it'll always give true.
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
Try this:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
This also should work!
$count = count($data);
$i = 0;
foreach ($data as $value) {
if (strpos($string, $value) === FALSE) {
#$response = TRUE; // This is subject to change so not reliable
$i++;
}
}
if($i<$data)
response = FALSE;

Find if a value exist in a CSV file with PHP

This is my code to check if a row of my .csv file contains a specific name, but it does not work.
I think it has something to do with the if statement.
$file_handle = fopen("sources.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] = 'paul') {
echo 'Found';
}
}
fclose($file_handle);
I am trying to check in sources.csv files, for the name 'Paul' .
I can't use a database like MySQL for technical reasons.
Since you haven't provided a sample of your file, am submitting the following as an alternative.
Do note that in your present code, you are assigning using a single equal sign = instead of comparing using == or ===, just saying as an FYI.
if ($line_of_text[0] = 'paul') should read as if ($line_of_text[0] == 'paul')
Assuming the following .csv format (will work even without the commas) and is case-sensitive, consult Footnotes regarding case-insensitive search.
Paul, Larry, Robert
Code:
<?php
$search = "Paul";
$lines = file('sources.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE);
}
if($line_number){
echo "Results found for " .$search;
}
else{
echo "No results found for $search";
}
Footnotes:
For a case-insensitive search, use stripos()
$line_number = (stripos($line, $search) !== FALSE);
Row number found on...
To give you the row's number where it was found:
$line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
or (case-insensitive)
$line_number = (stripos($line, $search) !== FALSE) ? $count : $line_number;
then just echo $line_number;
Your problem is this line:
if ($line_of_text[0] = 'paul') {
This will always be true because you are assigning the value paul to $line_of_text[0] with the assign operator =. What you want to do is check if the two are equal, so you need to use the equality operator, ==. The line of code should be:
if ($line_of_text[0] == 'paul') {
There is also the === equality operator in PHP which checks for the same value AND same type. (This is a particularly nasty feature of PHP when compared to compiled languages)
e.g. consider: `$foo = 5; $bar = "5";
if ($foo === $bar) // this will be false because foo is an int, and bar is a string
if ($foo == $bar) // this will be true
Don't be confused with the != comparison operator:
if ($foo != $bar) // foo is not equal to bar (note the single =)
Try using in_array instead of ==
if(in_array('paul', $line_of_text)) {
// FOUND
}

Why is strcmp returning false on the second run?

So right now I'm making a simplistic login system. The client enters the form data and the php handles it by checking a text file that goes like so:
name
pass
name
pass
...so on
The php I'm using to process this is:
$name = $_REQUEST['name'];
$pass = $_REQUEST['pass'];
$validName = false;
$validPass = false;
$pos = 0;
$file_handle = fopen("database.txt", "r");
while (!feof($file_handle)) {
$line = ltrim( fgets($file_handle), "\n" );
if ($pos % 2 == 0 ) // Checks for names first on even rows
{
if( strcmp( $name, $line))// Normal checking returns correctly
$validName = true;
}
else if( $validName === true ) // if odd, and a matching name check pass
{
if( !strcmp( $pass, $line) )// What's going on here? Why is it opposite?
{
$validPass = true;
}
break;
}
$pos++;
}
What's happening is that the first check if( strcmp( $name, $line)) checking if there is a name in the data base that matches the input from the client.
This correctly returns true when the clients name matches a name in the data base. I check the password the EXACT same way, but some how it returns false when it's suppose to be true, and returns true when it's suppose to be false.
What's going on here?
On a side note, I'm only using strcmp because I couldn't get $name === $line to work.
strcmp() returns an integer, not a boolean. In fact, it returns 0 if the strings match, which would evaluate to false in an if-statement. That is why it appears to have "reverse" behavior compared to a typical boolean function.
See the documentation.
According to your code, it is not exact same way, but rather opposite:
if( strcmp( $name, $line))
if( !strcmp( $pass, $line))
Looks like there was a bigger problem then I thought.
There was 2 problems.
1, As Daniel explained perfectly
2, There was an extra character at the end of each line which threw off all comparisons. So to fix this I deleted the end of the line and now everything's working.
while ( !feof($file_handle) )
{
$line = ltrim( fgets($file_handle) );
$line = substr($line, 0, -1);/// This gets rid of the extra character
if ( ($pos % 2) == 0 )
$validName = ( $name === $line );// compares with ===, which is faster then strcmp
else if( $validName )
{
$validPass = ( $pass === $line );
break;
}
$pos++;
}fclose($file_handle);

strpos with two words to find

I found this example on stackoverflow:
if (strpos($a,'are') !== false) {
echo 'true';
}
But how do I make it search for two words. I need something like this: if $a contains the words "are" or "be" or both echo "contains";
I tried xor and ||
Just check both words separately and use the boolean or-operator to check if either one or both are contained in $a:
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo "contains";
}
Note that due to the or-operator, the second check (for 'be') is not performed if the first one already showed that $a contains 'are'.
An alternative: Searches any length of words in the longer string.
Since you've haven't picked an answer from all the strpos answers (most of which should work with just two words, try this function of mine which exceeds word limits. It can find any varying length of words from the longer string (but doesn't use strpos). I think with strpos, you would have to know the number of words to determine how many || you should use or make use of a loop (sort of). This method eliminates all that and gives you a more flexible way to reuse your codes. I thinks codes should be flexible, reusable and dynamic. Test it and see if it does what you want!
function findwords($words, $search) {
$words_array = explode(" ", trim($words));
//$word_length = count($words_array);
$search_array = explode(" ", $search);
$search_length = count($search_array);
$mix_array = array_intersect($words_array, $search_array);
$mix_length = count($mix_array);
if ($mix_length == $search_length) {
return true;
} else {
return false;
}
}
//Usage and Examples
$words = "This is a long string";
$search = "is a";
findwords($words, $search);
// $search = "is a"; // returns true
// $search = "is long at"; // returns false
// $search = "long"; // returns true
// $search = "longer"; // returns false
// $search = "is long a"; // returns true
// $search = "this string"; // returns false - case sensitive
// $search = "This string"; // returns true - case sensitive
// $search = "This is a long string"; // returns true
$a = 'how are be';
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo 'contains';
}
Try:
if (strpos($a,'are') !== false || strpos($a,'be') !== false)
echo 'what you want';
if ((strpos($a,'are') !== false) || (strpos($a, 'be') !==false) {
echo 'contains';
}
Is this what you want?
if ((strpos($a,'are') !== false) || (strpos($a,'be') !== false)) {
echo 'contains';
}
if (strpos($a,'are') !== false || strpost($a, 'be') !== false) {
echo "contains";
}
Brain Candy:
If the first one returns true, it'll skip the second check. So both can be true. If the first one is false, ONLY then will it check the second. This is called a short circuit.
if(strstr($a,'are') || strstr($a,'be')) echo 'contains';
Hum, like this?
if (strpos($a,'are') || strpos($a, 'be') {
echo 'contains';
}

How to return a boolean if a string contains one of an array of substrings?

I'm struggling with a simple function that loops through an array and returns true only if it finds a given substring in one of the array's elements.
For some reason, I'm ALWAYS getting false... even when the $email parameter is contains one of the valid domains. Ex: scoobydoo#domain1.com.
function check_email($email) {
$whitelist_domains = array(
'#domain1.com',
'#domain2.com',
'#domain3.com'
);
$output = FALSE;
foreach ($whitelist_domains as $domain) {
$pos = strpos( $email, $domain );
if ( $pos ) {
$output = TRUE;
}
}
return $output;
}
you are not breaking the loop if you find the domain, so what you are getting is actually the result for the LAST string checked only.
just add break; after $output = TRUE;
From the official doc of strpos:
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
And make sure to add a break after you set $output to true.
This is a good function to use the === operator with as it makes sure the value and type are equal (1==true, but 1!==true)
if (strpos( $email, $domain )!==false) {
$output = TRUE;
}
Change
if ( $pos ) {
to
if ( $pos !== false) {
this is because is strpos returns 0, that will equate to false, even though the string was found.
Here are two direct/common methods that have different advantages:
Method #1: non-regex approach
function check_email1($email){
$whitelist_domains=['#domain1.com','#domain2.com','#domain3.com'];
foreach($whitelist_domains as $domain){
if(strpos($email,$domain)!==false){
return true; // allow quick return (exit loop & function asap)
}
}
return false; // default response
}
Method #2: regex approach
function check_email2($email){
$whitelist_pattern='/#(?:domain1\.com|domain2\.com|domain3\.com)$/'; // condense if possible /#domain[123]\.com$/
return (bool)preg_match($whitelist_pattern,$email); // convert 0 or 1 output to boolean (false/true)
}
Demo Link
Input / Function Call:
$emails=['user#domain1.com','bad#bad.com'];
foreach($emails as $email){
echo "$email\n";
var_export(check_email1($email));
echo "\n";
var_export(check_email2($email));
echo "\n\n";
}
Output:
user#domain1.com
true
true
bad#bad.com
false
false
Advantages/Disadvantages:
strpos() in the majority of situations will outperform regex functions. Your default method should be to use string functions and only change to regex when string functions are less efficient or too convoluted to code. A related page: Which is more efficient, PHP string functions or regex in PHP?
Looping $whitelist_domains in #1 makes for a clunkier looking code block compared to #2 (which can be condensed to a one-liner if you write the pattern directly into preg_match()).
Simple/common mistakes sometimes occur when dealing with strpos(). These mistakes may include:
not checking for false in the if condition
writing the haystack and needle in the wrong order
#2 does require some knowledge about regex (escaping, character classes, alternatives, etc.) which can be a deterrent for inexperienced coders. Depending on how you write your regex pattern and how many domains will be whitelisted, #2 is likely to be harder to maintain than #1.
#2 has the added benefit of being able to check that the domain.com substring appears at the end of the word via the $ metacharacter. For this reason, regex offers stronger validation.
You should change your code in this:
function check_email($email) {
$whitelist_domains = array(
'#domain1.com',
'#domain2.com',
'#domain3.com'
);
foreach ($whitelist_domains as $domain) {
if ( strpos( $email, $domain ) !== false ) {
return true;
}
}
return false;
}
Documentation of strpos
Quoting from the manual (http://php.net/manual/en/function.strpos.php):
The !== operator can also be used. Using != would not work as expected
because the position of 'a' is 0. The statement (0 != false) evaluates
to false.
Example code
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// The !== operator can also be used. Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
?>

Categories