Jump to content

Variables on a PHP Include


danjacko

Recommended Posts

What i'm trying to do is have 20 HTML (href) links and a PHP include under the links. What I want is when a link is clicked the PHP include changes to a different file. Im sorry if its not very clear but i'm pretty new to PHP so don't know if its possible... Please can someone help :)

 

Link to comment
https://forums.phpfreaks.com/topic/212202-variables-on-a-php-include/
Share on other sites

What i'm trying to do is have 20 HTML (href) links and a PHP include under the links. What I want is when a link is clicked the PHP include changes to a different file. Im sorry if its not very clear but i'm pretty new to PHP so don't know if its possible... Please can someone help :)

Here's a quick example:

 

<a href="?file=file1">file 1</a>
<a href="?file=file2">file 2</a>
<a href="?file=file3">file 3</a>

<?php
if(isset($_GET['file') && file_exists("/path/to/file/".$_GET['file'].".php")) {
   include("/path/to/file/".$_GET['file'].".php");
} else {
   // do something else
}
?>

 

I have tried

 

<a href="<?php file() {return 'file.php';} ?>">file 1</a>

 

<?php include file(); ?>

 

But this failed as it wont allow me to redefine the function when i tried a different link.

 

Then I tried.

 

<a href="<?php $file='file.php' ?>">file 1</a>

 

<?php include $file; ?>

 

Yet this didn't work because it only included the last link and when i tried to click another link it wouldn't change from the last one

That will never work as it is invalid code. You'll want to use AbraCadaver example posted earlier:

What i'm trying to do is have 20 HTML (href) links and a PHP include under the links. What I want is when a link is clicked the PHP include changes to a different file. Im sorry if its not very clear but i'm pretty new to PHP so don't know if its possible... Please can someone help :)

Here's a quick example:

 

<a href="?file=file1">file 1</a>
<a href="?file=file2">file 2</a>
<a href="?file=file3">file 3</a>

<?php
if(isset($_GET['file') && file_exists("/path/to/file/".$_GET['file'].".php")) {
   include("/path/to/file/".$_GET['file'].".php");
} else {
   // do something else
}
?>

 

Thanks you so much! Worked perfectly. For anyone who reads this topic again there is a ] missing and the code i now use is

<a href="?file=file1">file 1</a>

<a href="?file=file2">file 2</a>

<a href="?file=file3">file 3</a>

 

<?php

if(isset($_GET['file']) && file_exists("/path/to/file/".$_GET['file'].".php")) {

  include("/path/to/file/".$_GET['file'].".php");

} else {

  // do something else

}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.