String comparing in PHP [duplicate] - php

This question already has answers here:
Equal string comparisons are failing
(2 answers)
Closed 8 years ago.
So i have been trying to compare two strings. One from a $_POST method , and one read from a text file. Although they seem to be the same when I print both of them, my strcmp() never returns 0 meaning that they are not equal. Why does my strcmp() function never return 0?
Here is the actual code :
$fileRead = 'Users.txt';
$wasRead = FALSE;
$handleRead = fopen($fileRead,'r');
$character = fread($handleRead,1);
echo"<p> ".$character." </p>";
fgets($handleRead);
while($character != 'Q')
{
$lineName = fgets($handleRead);
echo "<p> ".$lineName." </p>";
$linePassword = fgets($handleRead);
echo "<p> ".$linePassword." </p>";
$character = fread($handleRead,1);
echo"<p> ".$character." </p>";
fgets($handleRead);
$porfavor = $_POST['newUserId'];
$porfavor = strtolower($porfavor);
echo $porfavor."<br>";
echo $lineName."<br>";
//$comparison = strcmp($lineName." ",$_POST['newUserId']);
//echo $comparison;
$comparison = strcmp($porfavor,$lineName);
echo $comparison;
if($comparison == 0)
{
$character = 'Q';
echo "<p> User Already Exists </p>";
echo " Sing In";
echo "<br>";
}
}
fclose($handleRead);

You may have an invisible character in one of your strings. Try doing a var dump.
$comparison = strcmp($porfavor,$lineName);
if($comparison != 0){
echo "<pre>";
var_dump($porfavor);
var_dump($lineName);
exit;
}
some tips:
You may need to use trim() on your variables to account for whitespace;
consider using strtoupper() if either might vary in case. Keep in mind it's case sensitive.

Related

Problem during creating Pyramid Star Patterns in PHP [duplicate]

This question already has answers here:
PHP Displaying a number of asterisks depending on the number given in the input field
(4 answers)
Closed 11 months ago.
Question :
My Code :
<html\>
Enter the number of rows:
<?php
if($_POST)
{
$row = $_POST['row'];
if(!is_numeric($row))
{
echo "Make sure you enter a NUMBER";
return;
}
else
{
for($row=0;$row<=1;$row++){
for($j=0;$j<=$row;$j++){ echo "#"; } echo ""; }}}?>
The problem is it's showing only two rows
I expected as shown in the photo
$row = 10;
for($i=0;$i<=$row;$i++){
for($j=0;$j<=$i;$j++){ echo "#"; } echo "<br>"; }
You are overriding the $row variable.
Also, you don't need the else since you are returning in case the if(!is_numeric) is true;
This should do it.
if(isset($_POST['row'])) {
$rows = $_POST['row'];
if(!is_numeric($rows))
{
echo "Make sure you enter a NUMBER";
return;
}
for($row=0;$row<=$rows;$row++){
for($j=0;$j<=$row;$j++){
echo "#";
}
echo "\n";
}
}
You can make use of the PHP function str_repeat to simplify the script.
This would only take 1 loop, so you don't get confused with the variable names.
$row = 10;
$i = 1;
while ($i <= $row)
{
echo str_repeat("#", $i); echo "\n";
$i ++;
}
Working Example here.

PHP check if a string contains a specific character [duplicate]

This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 1 year ago.
I have 2 strings $verify and $test. I want to check if $test contains elements from $verify at specific points. $test[4] = e and $test[9] = ]. How can I check if e and ] in $verify?
$verify = "aes7]";
$test = "09ske-2?;]3fs{";
if ($test[4] == $verify AND $test[9] == $verify) {
echo "Match";
} else {
echo "No Match";
}
Use strpos() https://www.php.net/manual/en/function.strpos.php
https://paiza.io/projects/n10TMV4Ate8-vtzioDrsMg
<?php
$verify = "aes7]";
$test = "09ske-2?;]3fs{";
if (strpos($verify, $test[4]) !== false && strpos($verify, $test[9]) !== false) {
echo "Match";
} else {
echo "No Match";
}
?>
As of PHP8 you can use str_contains()
<?php
$verify = "aes7]";
$test = "09ske-2?;]3fs{";
if (str_contains($verify, $test[4]) && str_contains($verify, $test[9])) {
echo "Match";
} else {
echo "No Match";
}
?>
Thanks to #symlink for the code snippet I butchered

How to limit the letter count and accept only specific letters in PHP STDIN?

I want to make php fgets(STDIN). But I don't know how to restrict the input count and i don't know how to accept only specific letters. Please guide me. I write down the problems of mine. I'm the beginner in STDIN usage. It's important for me because i have to do it in my Programming Test Exam. Help me please.
Here is Problem 1
Problem 1: I want to get only 10 Letters from cmd input and these
input should be W & S.
Here is Problem 2
Problem 2 : I want to get only 3 numbers and how to restrict the cmd
input to only number.
I just realized Ive misread your question for part 2, but this will work for part one and be a good help to start problem 2:
<?php
$errorMessage = false;
$attempts = 1;
$maxAttempts = 5;
function validates($string)
{
global $errorMessage; //tell this function to use global errormessage
if (strlen($string) > 10) {
$errorMessage = 'Exceeded String Length. Please ensure no more than 10 characters are entered';
return false;
}
preg_match('/\d+/', $string, $matches);
$extractedDigits = (isset($matches[0]) ? $matches[0] : 0 );
if ($extractedDigits > 3) {
$errorMessage = 'Exceeded allowed number of digits. Please ensure no more than 3 digits are contained in the string';
return false;
}
$errorMessage = false;
return true;
}
$result = readline('please enter a valid string: ');
while (!validates($result) && $attempts < $maxAttempts) { //while fail validation and have attempted less than the max attampts
echo "\n";
echo '*******************************************';
echo "\n";
echo 'Attempts Left (' . ($maxAttempts - $attempts) . ')';
echo "\n";
$result = readline($errorMessage . '. Please try again: ');
$attempts++;
}
echo "\n";
echo '*******************************************';
echo "\n";
if ($attempts >= $maxAttempts) {
echo 'Failed, too many attempts';
} else {
echo "\n";
echo 'Success...';
echo "\n";
echo "\n";
echo $result;
echo "\n";
echo "\n";
}
echo "\n";

Identical Strings in PHP not matching [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I'm trying to compare two strings (one from my database and another supplied by the user) and see if they match! The problem I'm having is that they don't seem to match - even though the strings seems to be exactly identical?
My PHP code is below:
public function Verify($pdo, $id, $token) {
$prepsql = $pdo->prepare("SELECT * FROM Profiles WHERE id = '$id' LIMIT 1");
$prepsql->execute();
$currentrow = $prepsql->fetch();
$current = preg_replace("/[^a-zA-Z0-9]+/", "", $currentrow["token"]);
echo '<p>'.var_dump($current).'</p>';
echo '<p>'.var_dump($token).'</p>';
$token = preg_replace("/[^a-zA-Z0-9]+/", "", $token);
if ($current == null || $current = "") {
return false;
} else {
if (strcmp($token, $current) == 0) {
return true;
} else {
return false;
}
}
}
And here is the webpage output:
string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p>string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p><p>Not authenticated</p>
Not authenticated just means that this function is returning false...
What on earth am I doing wrong? As per advice given on other similar Stack Overflow answers, I've used the regex function to basically only keep alphanumeric characters but that has made no difference? It isn't a trimming issue either as that didn't work!
Any help would be much appreciated!
Thanks!
Here is your problem:
if ($current == null || $current = "") {
// ^ now `$current` is "", an empty string
You assign a new value to $current, an empty string.
You probably want something like:
if ($current == null || $current == "") {
// ^^ now you are comparing

Function to validate username and password not working [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {

Categories