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\" />";
}
Related
Trying to display a corresponding image based on $enrollment_points equalling one of 3 values; 1000, 750 or 500.
With $enrollment_points setup successfully in a vars.php file, it only returns/displays the first image from the if statement, even though $enrollment_points = 750. It does not seem to get past the if statement or evaluate the integer from the $enrollment_points string.
I can't figure out why?
thanks in advance
<?php
if ($enrollment_points = "1000") {
echo "<img src='../1_LandingPage_Content/images/offers/1000_enrollment_700x600_.png' alt='' />";
} elseif ($enrollment_points = "750") {
echo "<img src='../1_LandingPage_Content/images/offers/750_enrollment_700x600_.png' alt='' />";
} elseif ($enrollment_points = "500") {
echo "<img src='../1_LandingPage_Content/images/offers/500_enrollment2_700x600_.png' alt='' />";
} else {
echo "<img src='../1_LandingPage_Content/images/offers/enrollment_700x600_.png' alt='' />";
}
?>
i expect the corresponding image file to be displayed based on the value of $enrollment_points.
To compare for equality, you should use == and not =
So change it to
if ($enrollment_points == "1000") {
echo "<img src='../1_LandingPage_Content/images/offers/1000_enrollment_700x600_.png' alt='' />";
EDIT:
For your question about == or ===. == compares value only. === compares the value AND type. See below:
1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // type is ignored, so true.
One "=" is use for assign value, Two "==" and three "===" use for compare.
<?php
if ($enrollment_points == "1000") {
echo "<img src='../1_LandingPage_Content/images/offers/1000_enrollment_700x600_.png' alt='' />";
} elseif ($enrollment_points == "750") {
echo "<img src='../1_LandingPage_Content/images/offers/750_enrollment_700x600_.png' alt='' />";
} elseif ($enrollment_points == "500") {
echo "<img src='../1_LandingPage_Content/images/offers/500_enrollment2_700x600_.png' alt='' />";
} else {
echo "<img src='../1_LandingPage_Content/images/offers/enrollment_700x600_.png' alt='' />";
}
?>
You are setting the variables inside your if statement rather than comparing:
if($enrollment_points = "750")
change to:
if($enrollment_points == "750")
Remember, one "=" for setting, two or three for comparing
If you are assigning the value of 1000 to $enrollment_points variable then yes thats the case but if you want them to equal, as in equality statement use the '==' sign.
Use == for if statement, not =. http://php.net/manual/en/language.operators.comparison.php
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";
}
a current project of mine is giving me some trouble. The web page in question is supposed to display text from a text file followed by an accompanying image from a directory.
Currently, the output is text 1, image 1, text 2, image 1, text 1, image 2, text 2, image 2
My code so far:
foreach ($DirEntries as $Entry)
{
if((strcmp($Entry, '.') != 0) && (strcmp($Entry, '..') != 0))
{
$inputFile = fopen("imagelist.txt", "r");
if ($inputFile)
{
while (($line = fgets($inputFile)) !== false)
{
echo "Name, description, and file name:<br />" . $line."<br>";
echo "<img src=\"files/" . $Entry . "\" ><br /><br />\n";
}
}
else
{
echo "There was an error in the opening file";
}
fclose($inputFile);
}
}
closedir($DirOpen);
?>
Any help would be greatly appreciated.
Your problem appears to be the nested while loop since you're dealing with a one to one relationship.
This should solve the problem for you:
$inputFile = fopen("imagelist.txt", "r");
// probably better to check for file readability before looping the directory items.
if (!$inputFile) {
echo "There was an error in the opening file";
}
else {
foreach ($DirEntries as $entry)
{
if($entry === '.' || $entry === '..')
{
continue; // using a continue helps keeps the code indentation levels down.
}
// assuming that each line corresponds to an image in the same order
if (($line = fgets($inputFile)))
{
echo "Name, description, and file name:<br />" . $line."<br>";
echo "<img src=\"files/" . $entry . "\" ><br /><br />\n";
}
else
{
echo "Image '$entry' has no metadata";
}
}
fclose($inputFile);
}
closedir($DirOpen);
Good luck!
With another coder's help, I have PHP code that creates a photo gallery with auto-created thumbnail images of any image files in the directory. (It's open source, so anyone else is free to use and modify as they desire.)
I use it as a stock photo library and the file names include the keywords for that image. For example, one might be businessman-tie-suit-briefcase-office-meeting.jpg.
I've been trying to add a keyword search input that looks at the file names, but cannot figure out how to proceed. I've built keyword searches for a database, but this directory file name search is new to me.
Here's the relevant code of the page:
<?
$gallery = $_GET["gallery"];
$dir = $dir.$gallery."/";
//Put files into an array
// create a handler to the directory
$dirhandler = opendir($dir);
// read all the files from directory
$nofiles=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$nofiles++;
$files[$nofiles]=$file;
}
}
//close the handler
closedir($dirhandler);
//Back button to appear at the top of each page to go to the previous directory if not on the main page
if ($gallery !="" or $keyword !="")
{
echo "<div><a href='javascript:history.go(-1)'><img src='images/up.png' border='0'></a></div>";
}
// BEGINNING ADD FOR KEYWORD SEARCH
// KEYWORD SEARCH BOX- create text box to search entire directory for that keyword and display page in grid pattern with results
?>
<div style='position:relative; left:10px;'>
<form action='index_search.php?keyword=$keyword' method='get' name='search'>
<input type='text' name='keyword' size='25'>
<input type='submit' value='Search Keyword'>
</form>
</div>
<?
//*************************************************************************//
// PERFORM KEYWORD SEARCH
if ($keyword !="")
{
echo "<div class='keytext'>Keyword search: <b>" . $keyword . "</b><br/></div>";
/*********************************************************************************************************/
/* ***** THIS IS WHERE THE SEARCH OF DIRECTORY FILES NEEDS TO OCCUR AND OUTPUT RESULTS AS $files */
/* get results where $file LIKE %$keyword%; */
/*********************************************************************************************************/
//Show images
foreach ($files as $file)
{
if ($file!="."&&$file!="..")
{
$extention = explode('.', $file);
if ($extention[1] != "")
{
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group'' href='$dir$file' return false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'/>";
echo"</a><br/>";
$file_name = current(explode('.', $file));
echo substr($file_name,0,21);
echo "</div>";
}
}
}
}
else { // starts the split from keyword or no keyword
//***********************************************************************//
// sort folder names alphabetically, ignore case
natcasesort($files);
//Show the folders
foreach ($files as $file){
if ($file!="."&&$file!="..")
{
sort($files); //Sorts the array (file names) alphabetically -- not the directory/folder names
$extention = explode('.', $file);
if ($extention[1] == "")
{
echo "<div class='imgwrapper'>";
echo "<a href='?gallery=$gallery/$file'>";
echo "<img src='images/folder.jpg' border='0'>";
echo "<div class='folder'>";
echo current(explode('.', $file));
echo "</a>";
echo "</div>";
echo "</div>";
}
}
}
?>
<div style="clear:both"></div>
<?
//Show images
foreach ($files as $file){
if ($file!="."&&$file!="..")
{
$extention = explode('.', $file);
if ($extention[1] != "")
{
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group'' href='$dir$file' return false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'/>";
echo"</a><br/>";
echo "<div class='title'>";
$file_name = current(explode('.', $file));
echo substr($file_name,0,125);
echo "</div>";
echo "</div>";
}
}
}
}
?>
I have the area commented out where I believe the search string would be executed, as the display code is already there. I've tried a few things that didn't work, so didn't bother listing any of it.
Any ideas if I'm going about this the wrong way?
Thanks in advance.
if ($extention[1] != "")
{
if(stripos($file, $keyword) !== false)
{...
}
}
See (stripos() manual)
I was able to get this resolved from some outside help.
if ($file!="."&&$file!="..")
{
sort($files); //Sorts the array (file names) alphabetically -- not the directory/folder names
$extention = explode('.', $file);
if ($extention[1] == "")
{
$dir = "pics/";
$dir = $dir.$file."/";
$dirhandler = opendir($dir);
// read all the files from directory
$nofiles=0;
$files2=array();
while ($file2 = readdir($dirhandler)) {
if ($file2 != '.' && $file2 != '..')
{
$nofiles++;
$files2[$nofiles]=$file2;
}
}
closedir($dirhandler);
sort($files2); //Sorts the array (file names) alphabetically -- not the directory/folder names
//Show images
foreach ($files2 as $file2){
if ($file2!="."&&$file2!="..")
{
$extention = explode('.', $file2);
if ($extention[1] != "" && stripos($file2,$keyword)!==false)
{
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group'' href='$dir$file2' return false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file2&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'/>";
echo"</a><br/>";
echo "<div class='title'>";
$file2_name = current(explode('.', $file2));
echo substr($file2_name,0,125);
echo "</div>";
echo "</div>";
}
}
}
}
I'm currently making a droplist but in the droplist let's say I only want to include only .txt extension files so any other extensions like .php .jpg or any other extensions will not be in in the droplist. How can I do that as simple as possible?
Another question is I want to make a warning IF the folder does not have any .txt extension files an error message will show. So even if there are other .jpg .php or any other files inside as long as there's no .txt file in the folder a warning will show.
Anyone able to give me a hand?
This is what I have done but it only shows a drop-list with no .txt at the end but it will still show other random files in the drop-list though.
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if(($list == ".") || ($list == ".."))
{
continue;
}
echo "<option value=\"";
echo basename($list,".txt");
echo "\">";
echo basename($list,".txt");
echo "</option>";
}
echo "</select>";
echo "</form>";
editted added the substr with $hasTxt
<?php
if(!(is_dir("./aaa")))
{
die("Must create a <strong>aaa</strong> folder first, sorry");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select name=\"aaa\">";
$aaa_files = scandir("./aaa");
$hastxt = false;
foreach($aaa_files as $file_list)
{
if(($file_list == ".") || ($file_list == ".."))
{
continue;
}
if(strlen($file_list)>4 && strtolower(substr($file_list, -4))!='.txt')
{
continue;
}
else
{
$hastxt = true;
echo "<option value=\"";
echo basename($file_list,".txt");
echo "\">";
echo basename($file_list,".txt");
echo "</option>";
}
}
echo "</select>";
echo "<br/><input type=\"submit\">";
echo "</form>";
if($hastxt == false)
{
echo "Must create text files first, sorry";
die();
}
?>
This is what happens for the script that I have now if the folder does not have any txt files.
This is what I actually want if there's no txt file but of course without the arrow
For the first part, just like you continue on directories . and .., you can continue on non-text files:
if(strlen($list)>4 && strtolower(substr($list, -4))!='.txt') continue;
For the warning part, put a flag before the foreach
$hasTxt = false;
And set it to true whenever you get input you don't ignore (ie. after the if(unwanted) continue;)
$hasTxt = true;
Finally, after the foreach check the value of $hasTxt and use it as you prefer.
You could use PHP's substr() function to test the filenames:
if(substr($filename, -3) == 'txt') {
// show file
}
See here: http://php.net/manual/en/function.substr.php
Try this , Hope it will work you
<?php
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
$i =0;
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
$i++;
}
}
if($i == 0){
die("the folder does not have any .txt extension files");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
echo "<option value=\"".substr($list,0, -4)."\">".substr($list, 0,-4)." </option>";
}
}
echo "</select>";
echo "</form>";
?>