【发布时间】:2015-04-18 14:16:50
【问题描述】:
我无法从 codeigniter 中的 url 获取参数值。
例如:localhost/log/job/php 这里log/ 是我的文件夹,job/ 是我的控制器,php 是我的参数。
我想在控制器“作业”中获取此参数。 我该怎么做?
【问题讨论】:
-
您可能需要配置您的路线。
标签: codeigniter
我无法从 codeigniter 中的 url 获取参数值。
例如:localhost/log/job/php 这里log/ 是我的文件夹,job/ 是我的控制器,php 是我的参数。
我想在控制器“作业”中获取此参数。 我该怎么做?
【问题讨论】:
标签: codeigniter
你可以使用$this->uri->segment(n);
您需要对路由进行一些更改,以允许代码点火器在您的控制器中接收参数
$route['uri-(:any)/(:num)'] = "controller/function/$1/$2";
或
$route['uri-(:any)'] = "controller/function/$1";
在你的控制器中做一些改变
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class controller extends CI_Controller
{
function function($parameter1 = null, $parameter2 = null)
{
........
}
}
参考这个http://www.codeigniter.com/userguide2/libraries/uri.html
【讨论】:
您可以使用$this->uri->segment(n)。
【讨论】:
假设你的参数总是在最后:
$segs = $this->uri->segment_array();
echo end($segs);
编辑:为了澄清其他要点。首先你需要设置你的application/config/routes.php:
$route['Youruri-(:any)/(:num)'] = "yourcontroller/yourfunction/$1/$2";
$route['Youruri-(:any)'] = "yourcontroller/yourfunction/$1";
在控制器application/controllers/yourcontroller.php中需要定义一个函数:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Yourcontroller extends CI_Controller {
function yourfunction($brand = null, $page = null) {
// http://www.yoursite.com/Youruri-Microsoft
// or http://www.yoursite.com/yourcontroller/yourfunction/Microsoft
// do some stuff for get products of this $brand (Microsoft)
if($page != null) {
// http://www.yoursite.com/Youruri-Intel/2
// or http://www.yoursite.com/yourcontroller/yourfunction/Intel/2
// do some other stuff get products of this $brand (Intel) of $page (2)
}
}
}
【讨论】:
你得到它:
$this->uri->segment(n);
其中 n = 1 表示控制器,n = 2 表示方法,n = 3 表示参数等等。
你需要 n = 3 来获取参数。
在您的路径 localhost/log/job/php 中,您的方法名称丢失。
即使你的方法名是index,那么你的路由也会是localhost/log/job/index/php
如果您需要从 url 中删除 index.php,那么您将使用 localhost/log/index.php/job/index/php 获取参数
要删除 index.php,您需要按照以下步骤创建 .htaccess 文件:
创建一个 .htaccess 文件,其中包含 index.php 文件的内容
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
确保 apache 可以访问这个 .htaccess 文件。为此,请编辑 apache 配置文件。如果你使用ubuntu,那么它是/etc/apache2/sites-available/default,然后将AllowOverride none更改为AllowOverride all,用于目录和www目录。
<Directory />
Options FollowSymLinks
AllowOverride all
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
</Directory>
如果没有,则启用 mod rewrite,使用以下命令:
`sudo a2enmod rewrite`
最后别忘了重启apache。
希望这会有所帮助。
【讨论】:
用途:
$param = $this->uri->segment(3);
在您的文件夹中添加 .htaccess(您的情况是 "log"):
RewriteEngine On
RewriteBase /log/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /log/index.php/$1 [L]
【讨论】: