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 (EG 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 forif($file == true)
, which will compare the value of$file
totrue
.
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\" />";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.