代码之家  ›  专栏  ›  技术社区  ›  mk12

单击链接时执行php

  •  1
  • mk12  · 技术社区  · 15 年前

    我的网站页面是(或将要)完全相同的,除了主分区的内容。所以我想在<head>我可以 <?php $page = "home.html"?> ,其中home.html是主页主分区的裸内容(不是完整的HTML页-否<HTML>,<head>等)。因此,在<DIV id=“main”>和</DIV>内部我可以 <?php include($page);?> . 那么,我问这个问题的原因是我想在单击链接时更改$page。我该怎么做?谢谢。

    3 回复  |  直到 15 年前
        1
  •  3
  •   sholsinger    15 年前

    您可以使链接如下所示:

    <a href="mypage.php?page=other_page">Other Page</a>
    

    然后在页面顶部设置 page 的价值 $_GET['page']

    <?php
      if (isset($_GET['page']))
      {
        $page = $_GET['page'] . ".html";
      } else {
        $page = "home.html";
      }
    ?>
    
        2
  •  1
  •   Roch Christophe Calvès    15 年前

    你的链接必须像:

    home.php?page=test
    

    您将得到页面变量中的值,如下所示:

    if(isset($_GET['page']))
      $page = $_GET['page'].'.html';
    else
      $page = 'index.html';
    
        3
  •  0
  •   CodeJoust    15 年前

    你可以这样做: http://yoursite.com/index.php?page=test.html http://yoursite.com/index.php?page=test (稍后附加.html)。

    例如:

    <?php $page = preg_replace('/[^A-Za-z]/','', $_GET['page']);
    $path = 'pages/'.$page.'.html'
    if (file_exists($path)){ $output = file_get_contents($path); }
     else { header("HTTP/1.0 404 Not Found");
     $output = file_get_contents('pages/404.html'); }
    ?>
    

    (将文件的其余部分放在php之后,以便404头正常工作。)

    然后,您还可以使用Apache重写:

    Rewrite Engine On
    Rewrite Rule ^([A-Za-z]+)$ index.php?page=$1
    

    然后使用类似的链接 http://mysite.com/page_name

    然后在主分区中:

    <?php echo $output; ?>