I'm trying to setup a simple php code that will read .txt files. I want the links to change $x to the desired .txt file, then print the results below the navigation. The code works if i predefine $x, but i want to make it where clicking the links defines $x.

I have no idea where to go from here.

<a href=" $x= a.txt "> a </a>
<a href=" $x= b.txt "> b </a>

<?
$xh = fopen($x, 'r');
$theData = fread($xh, filesize($x));
fclose($xh);
echo '<h1>$x</h1>';
echo $theData;
?>

Sorry to say, but the code you have won't work no matter what you do. PHP is a server-side language and can't interact with client-side easily.

You will need to use the _GET method. You define the file you want in the url and then php can read it from there.
Ex.

<a href="yourpage.php?file=a.txt">File 1</a>

and on the php side you need to check if the file is in the url, then if it is make sure the file is a valid one. After that you open it up and display the contents.

if ( isset( $_GET['file'] ) ) { //?file=a.txt is what this refers to.
  $file = $_GET['file'];
  if ( file_exists( $file ) ) {
    $fh = fopen( $file,'r' );
    $data = fread( $fh,filesize( $file ) );
    fclose( $fh );
    echo "<h1>" . $file . "</h1>";
    echo $data;
    //or if you have php5: echo file_get_contents( $file );
  }
  else {
    die('Invalid File');
  }
}
<a href='<?php echo $_SERVER['PHP_SELF']; ?>?x=a.txt'> a </a>
<a href='<?php echo $_SERVER['PHP_SELF']; ?>?x= b.txt'> b </a>
<?php  //hate short codes
$xh = fopen($x, 'r');
$theData = fread($xh, filesize($x));
fclose($xh);
echo '<h1>$x</h1>';
echo $theData;
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.