Search code examples
phphtmlisset

PHP read file else another file


I have problem here, if I start this script, server returns no value, I know this script isn't ideal for the server optimization, but Im already without any ideas. I need solution, If I choose Czech or English from my option, server returns correct values. Folders are in same address book. Will be glad for your time and help

<select name="example">
<option value="czech" name="czlang" selected="selected">Czech</option>
<option value="eng" name="enlang">English</option>
</select>

<?php
$czfolder = fopen("cz_data.txt", "r");
$enfolder = fopen("en_data.txt", "r");

if(isset($_GET["czlang"])) {
    echo(fread($czfolder, "100"));
      fclose($czfolder); }

if(isset($_GET["enlang"])) {
    echo(fread($enfolder, "100"));
      fclose($enfolder);  
        } 
?>

Solution

  • <?php
    // suggestion: always start with php.  Wait to output 
    // anything until you are done processing everything.
    
    // avoid non-existent key on inital run. Take action only on submission.
    if(array_key_exists('example', $_GET)) {
    
      // using a switch statement is purely a matter of personal preference.
      // act on form input, then optionally die before printing form
      $choice = $_GET['example'];
      switch ($choice) {
        case 'czlang':
          print "show Czech...";
          //$czfolder = fopen("cz_data.txt", "r");
          //echo(fread($czfolder, "100"));
          //fclose($czfolder); }
          die;
    
        case 'enlang':
          print "show English...";
          //$enfolder = fopen("en_data.txt", "r");
          //echo(fread($enfolder, "100"));
          //fclose($enfolder);  
          die;
      }
    
    }
    
    // processing done; output html
    
    ?>
    <h1>Choose Language</h1>
    <form method="get">
      <select name="example">
        <option value="czlang" selected="selected">Czech</option>
        <option value="enlang">English</option>
      </select>
      <input type="submit" value="Display" />
    </form>