【问题标题】:Problem with redirect to other pages using URI使用 URI 重定向到其他页面的问题
【发布时间】:2019-03-26 19:39:14
【问题描述】:

我被未重定向到我创建的页面的 URI 所困扰。我有页面

  1. about.php
  2. about-culture.php
  3. contact.php
  4. index.php

索引页面工作正常,但是当我尝试重定向到其他页面时,它会引发异常

Fatal error: Uncaught Exception: No route defined for this URI. in /opt/lampp/htdocs/learnPHP/core/Router.php:21 Stack trace: #0 /opt/lampp/htdocs/learnPHP/index.php(6): Router->direct('about/about/cul...') #1 {main} thrown in /opt/lampp/htdocs/learnPHP/core/Router.php on line 21 

如果问题无法理解,我还会录制视频来描述我的问题。 https://www.useloom.com/share/5199399f3b5f42dd9c589a47dad0738f

我尝试了很多东西在代码中做出了改变。当我 var_dump() 到 uri 函数时,它会返回多个链接,这些链接是错误的 URI

我的 routes.php 文件

<?php
$router->define([
    '' => 'controllers/index.php',
    'about' => 'controllers/about.php',
    'about/culture' => 'controllers/about-culture.php',
    'contact' => 'controllers/contact.php'
]);

index.php

$database = require 'core/bootstrap.php';

require Router::load('routes.php')
    ->direct(Request::uri());

.htaccess

RewriteEngine On
AddType text/css .css
AddType text/javascript .js
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteRule ^.*$ index.php [END]

请求.php

<?php
class Request
{
    public static function uri()
    {

      $uri = (substr($_SERVER['REQUEST_URI'],10));
      $removeSlash = rtrim($uri, '/');
      return var_dump($removeSlash);

    }
}
Router.php
<?php

class Router
{
    protected $routes = [];
    public static function load($file)
    {
        $router = new static;
        require $file;
        return $router;
    }
    public function define($routes)
    {
        $this->routes = $routes;
    }
    public function direct($uri)
    {
        if (array_key_exists($uri, $this->routes)) {
            return $this->routes[$uri];
        }
        throw new Exception('No route defined for this URI.');
    }
}

 ?>

请点击链接查看生成的图片https://prnt.sc/n3ar12

【问题讨论】:

标签: php


【解决方案1】:

在视频中显示的导航中,您似乎正在做一个

<a href="">Home</a>

而不是一个

<a href="/learnPHP/">Home</a>

请在https://www.w3schools.com/html/html_filepaths.asp找到更多关于相对和绝对网址的信息

您需要编辑您的views/partials/nav.php 并链接正确的主路径,在您使用learnPHP 子文件夹时为“/learnPHP/”,如果不使用子文件夹,则为“/”。我还强烈建议对所有其他导航项使用以“/”开头的网址。

【讨论】:

  • 嗨!朋友非常感谢你我以前做过但不工作是解决这个问题的其他方法我非常感谢你
  • 不客气!如果它解决了您的问题,请投票或将此答案标记为选中。祝你学习 PHP 好运:)
  • 我仍然面临同样的问题兄弟。我克隆了作者在 GitHub 上编写和发布的代码,但没有任何改变。这里作者代码github.com/laracasts/The-PHP-Practitioner-Episode-16
猜你喜欢
  • 2019-12-30
  • 1970-01-01
  • 2017-05-01
  • 2012-03-16
  • 2023-03-22
  • 1970-01-01
  • 2018-07-10
  • 2023-04-09
相关资源
最近更新 更多