Search code examples
phphtmltext

When a file is not found, anything below the error is a no show, how can I fix this?


As of right now this code works some what, but I need some help to fix the issue with it. I insured this php code into middle of my webpage, see example below:

Page title here
Nar bar here
Some more text here...

<?php
$file = fopen($_GET["potus"] . ".txt", "r") or exit("Oh No. The info has not been found. Please try again.");
//output a line of the file until the end is reached
while(!feof($file))
{
//will return each line with a break
echo fgets($file). '<br />';
}

?>

Footer
Support links i.e. home, about, search, etc

I hope I can explain this well. Lets say I have a text file called "abc.txt", "cbs.txt", "nbc.txt, and so on uploaded to my server that contains some information about a network like ABC, when someone enters example.com/usr?potus=abc, the site shows the tile, nav bar, some text, the contents of the text file, the footer and supporting links. No issues here anything works fine.

Now here is where the issue happens if someone just enters example.com/usr or example.com/usr?potus=mouse, only the tap part of the site show, the tile, nav bar, some text, the error ""Oh No. The info has not been found. Please try again." shows, but anything below the error does not show witch is the footer and supporting links. I have looked at a lot of resources I have tried different type of codes and they all yield to the same results. If the text file is not found, anything below the error message "Oh No. The info has... ...try again." like the footer and supporting links do not show.

I am not sure how to fix this and this script that I have now, I have made other sites as well so they all have the same issue just never found a solution.


Solution

  • You have the right idea with checking the return value of the fopen call, but as you noted, calling exit terminates the page loading.

    Instead, you can surround the relevant code in an if block:

    Page title here
    Nar bar here
    Some more text here...
    <?php
    $file = fopen($_GET["potus"] . ".txt", "r");
    if ($file) {
        //output a line of the file until the end is reached
        while(!feof($file)) {
            //will return each line with a break
            echo fgets($file). '<br />';
        }
    } else {
        echo "Oh No. The info has not been found. Please try again.";
    }
    ?>
    Footer
    Support links