如何使用漂亮的URL - PHP

时间:2016-09-09 08:44:07

标签: php .htaccess mod-rewrite

我跟进了多个教程如何制作漂亮的URL,但从来没有实际使它工作(多产我没有得到的东西)。

我想要的是什么:

从这样的事情:

http://www.example.com/UserName/get/7Ka2la2

我想做这样的事情:

//.htaccess
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^ index.php [L]
</IfModule>

我尝试了什么: 正如我所提到的,我尝试遵循多个教程,但没有任何方法可以帮助我。所以我自己尝试一些东西。

index.php

它的作用:

  • 检查请求文件名是否不是文件
  • 并检查它是否不是目录
  • 然后,RewriteRule调用index.php,无论URL中写的是什么

在我的<?php function parse_path() { $path = array(); if (isset($_SERVER['REQUEST_URI'])) { $path = explode('/', $_SERVER['REQUEST_URI']); } return $path; } $path_info = parse_path(); echo '<pre>'.print_r($path_info, true).'</pre>'; switch($path_info[1]) { case 'get': include 'get.php'; break; default: include '404.php'; } 文件中,它看起来像这样

get.php

所以基本上应该将url拆分为数组,然后基于URL包含右文件(在本例中为$_GET)。但是像这样我可以加载一个文件,但我的$_POST$_GET中没有任何内容使我的脚本对我无用。

问题: 我的代码将以某种方式执行我想要的操作,因此基于url加载内容,但$_POST$_GET在此处无法正常工作。所以我的问题是我做错了吗?如果是的话应该如何看起来是正确的,如果不是我如何访问$_POST$().ready(function() { $(".carousel").jCarouselLite({ visible: 2, auto: 2, scroll: 2, mouseWheel: true, timeout: 6000, speed: 800, swipe: true, circular: true, btnNext: ".next", btnPrev: ".prev", autoWidth: true, responsive: true, afterEnd: function(currentItems) { var item1 = $(currentItems[0]).index()-1; var item2 = $(currentItems[1]).index()-1; var visible = 2; var totalItem = $(".carousel").find("li").length - (visible * 2); $("#count").html("Showing "+ item1 + " and " + item2 + " of " +totalItem); } }); 变量

1 个答案:

答案 0 :(得分:2)

您可以自己设置$_GET$_POST不受重写的影响。

如果你愿意,试试这个:

<?php
function parse_path() {
  $path = array();
  if (isset($_SERVER['REQUEST_URI'])) {
    $path = explode('/', $_SERVER['REQUEST_URI']);
  }
return $path;
}

$path_info = parse_path();
echo '<pre>'.print_r($path_info, true).'</pre>';

// SET UP $_GET HERE

$_GET['user'] = $path_info[0];
$_GET['id'] = $path_info[2];

switch($path_info[1]) {
  case 'get': include 'get.php';
    break;
  default:
    include '404.php';
}

但是如果你仍然可以修改寻找$_GET的代码,你可能要考虑不要像这样使用$_GET,而是设置某种包含值的类。

您还可能需要考虑进行网址重写,以便将原始请求映射到已获取变量的内容。

例如

//.htaccess
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.+)/(.+)/(.+)$ /api/v1/$2.php?user=$1&id=$3 [L]
</IfModule>
相关问题