I am trying to get a PHP file to read a specific line from a text file and then use that line in a string comparison for an if statement.
The second line in the textfield will always have one of two different values. Either &activeGame=0 or &activeGame=1.
The textfile:
boardarray=["NV", "SB", "VB", "NV"]
&activeGame=1
&activePlayer=V
The PHP-file:
$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks
if ($line[1] == "&activeGame=1") {
echo "The game is active";
} else {
echo "The game is not active";
}
Since echo $line[1] outputs &activeGame=1 I know that the PHP script can read the data from the text file.
The problem is that the if function will echo "The game is not active" and I cant figure out why.
EDIT
SOLUTION:
$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks
if (trim($line[1]) == "&activeGame=1") {
echo "The game is active";
} else {
echo "The game is not active";
}
The trim function on row 5 is what was missing.
Your problem is that every line of file ends with \n.
You can see it if you var_dump($line[1]) instead of echo it.
So real value for &activeGame=1 is &activeGame=1\n.
That's definitely not equals &activeGame=1.
So, before comparing - use trim function:
$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks
$line_one = trim($line[1]);
if ($line_one == "&activeGame=1") {
echo "The game is active";
} else {
echo "The game is not active";
}
First Problem was if you echo $line[1] then its value is "&activeGame=1 " ( Notice the whitespace at end . and the optimal Solution Code that will give you desired output is as below
<?php
$theFile = "test.txt";
$line = file($theFile);
echo trim($line[1]); //This will output "&activeGame=1" without quotation marks
$a=trim($line[1]);
$truestr="&activeGame=1";
if ($a == $truestr) {
echo "The game is active";
} else {
echo "The game is not active";
}
?>
OUTPUT
'&activeGame=1'The game is active
I would use parse_str this way even if there are more variables on that line you can always get that value. http://php.net/manual/en/function.parse-str.php
$theFile = "test.txt";
$line = file($theFile);
parse_str($line[1],$output);
if ($output['activeGame'] == 1) {
echo "The game is active";
} else {
echo "The game is not active";
}
Related
I have a database where I am storing a long string in one column. I am using two different delimiters. I am using $$ to separate the 4 inputs user can input. I am using ** to separate between each time the user enters the inputs (keep up with historical). I am pulling the data and trying to display it within my php file. Here is a portion of my code. My code is working when no ** delimiter is found (only $$ is found). However, when I enter the if statement due to finding **, my code quits printing data out. I get no errors just a blank section on my page. Do I have something set wrong in the while ($lUB < $bSize){} portion?
if ($userData[$index] != "")
{
if (strpos($userData[$index], '**') != false)
{
echo "here 0";
$userDataB = explode("**", $userData[$index]);
$lUB = 0;
$bSize = count($userDataB);
while ($lUB < $bSize)
{
$dataparse = explode("$$", $userDataB[$lUB]);
echo ("<tr>");
echo("<td>");
echo $dataparse[1];
echo("</td>");
echo("<td>");
echo $dataparse[2];
echo("</td>");
echo("<td>");
echo $dataparse[0];
echo("</td>");
echo("</tr>");
unset($dataparse);
$lUB = $lUB+1;
}
}
else
{
echo "here 1";
$dataparse = explode("$$", $userData[$index]);
echo ("<tr>");
echo("<td>");
echo $dataparse[1];
echo("</td>");
echo("<td>");
echo $dataparse[2];
echo("</td>");
echo("<td>");
echo $dataparse[0];
echo("</td>");
echo("</tr>");
}
}
else
{
echo "here 2";
}
If string is at the start of another string, strpos will return 0, which is equal to false in an if block, either you should use === operator or try to use some other function.
I have a htm file that passes a variable called $team to a php file. The php file echo's 'Fred' just fine on line 3 if that is what the user inputs but an if statement which asks if $_POST["team"] == "Fred" always returns negative. Can anyone help?
<?php
echo $_POST["team"] , "<br />";
if ($_POST["team"] == "Fred"){
echo "You go for " , $_POST["team"];
}
else {
echo "You do NOT go for Fred";
}
?>
Output:
Fred
You do NOT go for Fred
I think $_POST["team"] has spaces. Try this:
<?php
echo $_POST["team"] , "<br />";
if (trim($_POST["team"]) == "Fred"){
echo "You go for " , $_POST["team"];
}
else {
echo "You do NOT go for Fred";
}
?>
Note: this code is not related to the (,) Because you using echo, not merge string
If your $_POST['team'] contains spaces, the comparison will always return false.
Try to use trim() (Documentation here). Trim remove all spaces in your string, so it will reduce chances to fall in errors like these.
<?php
$team = trim($_POST['team']);
echo $team , "<br />";
if ($team == "Fred"){
echo "You go for " , $_POST["team"];
}
else {
echo "You do NOT go for Fred";
}
?>
Let me know if it works =D
you can echo like this because merge string in php use .
if ($_POST["team"] == "Fred"){
echo "You go for " . $_POST["team"];
}
This is my code:
while($row = $result->fetch_array()){
$restext = $row['pagetext'];
echo "<br /><br />$restext <br /><br />";
$user = str_replace('[TD="align: left"]'.$uid.'[/TD]','<b>LOOLOLOOLOLOLO</b>', $restext);
if (strpos($user,'<b>LOOLOLOOLOLOLO</b>')===false) {
$test = '[TD="align: left"]'.$num.'[/TD] [TD="align: left"][/TD]';
if (strpos($test, $restext)!==false) {
echo "Base not reserved!";
}
else
echo "This base is already reserved!";
}
else
echo "You have already reserved a base!";
}
The problem is with the last part where I use this:
if (strpos($test, $restext)!==false) {
echo "Base not reserved!";
}
else
echo "This base is already reserved!";
It just doesn't work.
That code always outputs: This base is already reserved!
Even if I know it should be outputting Base not reserved!
Does anyone know why this is happening?
The debugging I have done:
I am able to echo $rextext and $test
If I change the if statement to: if (strpos($test, "blah blah the text goes here")!==false) {
It will work but I can't keep it like that because the text is dynamically pulled from the dB.
Thanks!
not sure if I can example this right...
alright what I have here now runs the loop to check the student# and email I used an $error_check = 0 and $error_check ++ to consider if there's an error. If there is then an error will show and something will be printed into an error.log if not then something like the .txt file is good will print out and prints the contents
But I just realized the script will only run properly IF there's an error in the first row of my .txt file or else if there's an error to my second+ rows of contents in my .txt file then for the correct message will print out with the first row of content AND the error message will print out too.
But of course I want it the script to run that even if the first row of contents has no error and some other rows have error then only the error message will be printed.
I think it should be something about where I put the scripts in the loop but somehow I keep on reading my script and no idea what I should change....
else //else file exist then.......else #1
{
$fileContents = file("./courses/" . $_GET["filename"]); //calls out the file into $fileContents[] array....so $fileContents[0] is like the first row of the contents
$datePrinted = false; //setting a flag first so the date will be print only once when there's error..being used later in the foreach loop
$error_message = false; //setting a flag so error message only show once and being used later in the foreach loop
$well_formed = false; //another flag to stop the looping message saying the file is correctly formed
$table = false;
$error_check = 0;
sort($fileContents);
foreach($fileContents as $row) //the contents will be then seen as $row
{
$column = preg_split("/,/", $row); //splits the row by , and name each array as $column
$error_log = fopen("./courses/path/error.log","a+") or die ("File can not be opened"); //creates/open an error.log file
if(!(isEmailAddressWellFormed($column[3])) || !(isStudentNumberWellFormed($column[0]))) //two functions calls from page4.php using preg_match to check email and student# validation
//if one of them do not validate the following will start
{
$error_check++;
if(!$error_message) //if this is false then the error message+link will show
{
echo "Errors have been found in " . $_GET['filename'] . "<br/><a href='./courses/path/error.log'>Click here for the log</a>";
$error_message = true; //since this is in a loop but doesn't need to print it out so many times so changing the value here to true so when this loop runs again if(!error_message) will not run again
}
if(!$datePrinted) //works as how error_message works. the date only print once by here
{
fwrite($error_log, date("F t, Y (h:i:s a)") . PHP_EOL);
$datePrinted = true;
}
if(!(isEmailAddressWellFormed($column[3]))) //checks again if the email is not valid then print the follow to error.log
{
fwrite($error_log, "Improper email address from" . $_GET["filename"] . " :" . PHP_EOL);
fwrite($error_log, "$column[2] $column[1] $column[3]" . PHP_EOL);
}
if(!(isStudentNumberWellFormed($column[0]))) //checks again if the student # is not valid then print the follow to error.log
{
fwrite($error_log, "Improper student numbers from" . $_GET["filename"] . " :" . PHP_EOL);
fwrite($error_log, "$column[2] $column[1] $column[0]" . PHP_EOL . "\n");
}
}
elseif($error_check == 0)
{
if(!$well_formed)
{
echo "<h1 style='color: red'>" . $_GET["filename"] . " is well formed.</h1>";
echo "<table>";
$well_formed = true;
}
echo $column[0];
echo $column[1];
echo $column[2];
echo $column[3];
}
}//closing foreach
fwrite($error_log, str_repeat("-",80) . PHP_EOL); //puts a line to separate the next error but each time the page runs this line will print even if there's no error
fclose($error_log);
if(!$table)
{
echo "</table>";
$table = true;
}
}//closing else #1
thanks in advance for people helping...thanks....
I added
$row = $column[0] . $column[1] . $column[2] . $column[3];
at the beginning of the foreach after the preg_split then at the bottom I changed to...
elseif($error_check == 0)
{
$row.=$row;
}
}//closing foreach
fwrite($error_log, str_repeat("-",80) . PHP_EOL); //puts a line to separate the next error but each time the page runs this line will print even if there's no error
fclose($error_log);
if($error_check == 0)
{
echo "<h1 style='color: red'>" . $_GET["filename"] . " is well formed.</h1>";
echo "<table>";
echo $row;
echo "</table>";
}
}//closing else #1
?>
but now it only prints out the second row in the contents O.o only have three rows of contents at the moment for testing....am I missing something minor here?
I have this code and there is a bug in it but I cannot see where I have gone wrong. Can someone please help? The problem is that I am trying to display a certain image to corrospond with the content of text files. I think i have that part sorted but when it comes to displaying the images there is always a bug (E.G it is always green even when the if statment says otherwize.Here is the code:
<?php
if (empty($_GET['unit'])) {
$output="Please Enter A Unit Number";
echo $output;
}
else {
$filepathhalf = "/data/";
$file = "false";
$date = date("Ymd");
$unitnum = $_GET['unit'];
$ext = ".txt";
$filepath = $filepathhalf.$unitnum.$date.$ext;
echo $filepath;
echo $file;
if(file_exists($filepath))
{
$fh = fopen($filepath, 'r');
$file = fread($fh, 5);
fclose($fh);
}
echo $file; //This echo comes back as false as set but the green.png image still displays.
if ($file = "true ")
{
echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
}
else
{
echo "<img src=\"images/red.png\" width=\"15\" height=\"15\" />";
}
echo $_GET['unit'];
}
?>
There is a difference between comparing two instances and assigning one to the other.
See the below lines from your snippet and see if you might spot the error with the above clue:
if ($file = "true ")
{
echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
}
else
{
echo "<img src=\"images/red.png\" width=\"15\" height=\"15\" />";
}
Otherwise hover with your mouse over the spoiler below!
If you want an explanation regarding the issue, do the same...
$file = "true " will always evaluate to true, first it
will assign the string "true " to $file and then the value of
$file will be evaluated.
You are most probably looking for if($file == true), which will compare the value of $file to true.
You use a single =, which is used when assigning variables, not comparing them. When checking if two values are equal, use ==.
if ($file == true)
{
echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
}
hope that helps
It should be == to check condition.
if ($file != "false")
{
echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
}
not only you're using a single "=" but also you compare it to "true " (with a concatenated space!). I would change the code to:
if ($file === true)
{
echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
}