doudou1309 2015-03-09 19:50
浏览 23
已采纳

PHP mvc路由问题与链接

I'm just beginning with PHP, and started with YouTube tutorial about mvc. All went well, but when I started to develop my own application I encountered a problem with routing (I think).

My base application has URL: localhost/mvc/public/.

With the tutorial I created a class which starts a default home controller and index action when those are not specified. So localhost/mvc/public/ is equivalent to localhost/mvc/public/home/index.

In my view I have:

<p>You need to <a href="profile/login">log in</a> or <a href="profile/register">register</a></p>

So when I start with url localhost/mvc/public/ and then click on a link, it goes to localhost/mvc/public/profile/login and everything works fine. But if I write url localhost/mvc/public/home/index and then click a link I go to localhost/mvc/public/home/profile/index which obviously doesn't work. So my question is - how to solve this problem?

If someone is interested, I can post my code.

  • 写回答

1条回答 默认 最新

  • doushuichong2589 2015-03-09 20:00
    关注

    profile/register is a relative path, so it is added to the path you already had. Because /home/index doesn't have a trailing /, the browser assumes home is the path and index is a file or resource name, so home is kept and profile/register is added to it.

    Solution: change the paths to /profile/register (with a leading /) in your links. The / at the beginning tells the browser to add the path after the bare domain name, instead of choosing a path relative to the current one.

    Probably better: add a 'basepath' setting to your application by which it knows what the base path is. In your code you can use this base path when generating paths, for instance:

    <a href="<?=$basepath?>profile/register">
    

    If you installed the application in the root, you can set basepath to /. In your case, you could set it to /mvc/public/.

    Instead of a variable, you can create a function for it too to wrap the setting. If you search for "CodeIgniter base path" you will find plenty of examples of how CodeIgniter (a popular MVC framework) handles this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题