我在使用 htaccess 和 php 开关配置 url 时感到困惑

我想用常规文件编写一个项目。索引文件有一个 php 代码,其中 URL 中打开的所有文件都是开关。例如:


索引.php


<?php 

if(isset($_GET['page'])){

   $current_page = isset($_GET['page']) ? $_GET['page'] : '';

}else{

    $current_page = 'index';

}  


$result = str_replace(".php","", $current_page);  

 

    switch($result){

       case 'welcome':

         include('sources/welcome.php');

       break;

       case 'index':

         include('sources/index.php');

       break; 

       case 'profile':

         // Here is the problem. I want to make Facebook style user profile system

         // But the switch can not see profile username because it is working just for page names not usernames

       break;

    } 


?>

就像index.php 文件中的代码一样,我使用开关来调用页面。但当用户打开个人资料页面时,一切都会改变。因为我想让会员的个人资料页面像Facebook一样。喜欢http://www.mywebproject.com/username


我创建的 htaccess 在这里:


.htaccess


RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]

RewriteRule (?:^|/)([\w-]+)/?$ profile.php?username=$1 [L,QSA]

我的问题是这样的。如何在 switch 中使用成员的用户名来调用成员的个人资料。


慕仙森
浏览 111回答 1
1回答

德玛西亚99

我如何在 switch 中使用成员的用户名来调用成员的个人资料,因为 $thePage 数组中没有每个用户名。只需将所有内容传递给index.php.htaccess:# Activate rewrite engineRewriteEngine onRewriteBase /root/# If the request is not for a valid directory, file or symlinkRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-l# Redirect all requests to index.phpRewriteRule ^(.*)$ index\.php?/$1 [QSA]您只需将其传递$_REQUEST['username']给 profile.php,然后渲染您的页面。就像是:索引.php// you can do this better, this is just an example:$request_uri = $_SERVER['REQUEST_URI'];$params_offset = strpos($request_uri, '?');$request_path = '';$request_params = [];echo 'request_uri = ', $request_uri, '<br>', PHP_EOL;if ($params_offset > -1) {&nbsp; &nbsp; $request_path = substr($request_uri, 0, $params_offset);&nbsp; &nbsp; $params = explode('&', substr($request_uri, $params_offset + 1));&nbsp; &nbsp; foreach ($params as $value) {&nbsp; &nbsp; &nbsp; &nbsp; $key_value = explode('=', $value);&nbsp; &nbsp; &nbsp; &nbsp; $request_params[$key_value[0]] = $key_value[1];&nbsp; &nbsp; }} else {&nbsp; &nbsp; $request_path = $request_uri;}echo 'request_path = ', $request_path, '<br>', PHP_EOL;echo 'request_params = ', PHP_EOL; print_r($request_params);if (preg_match('~/root/(photos|videos|albums)/([\w-]+)~', $request_uri, $match)) {&nbsp; &nbsp; print_r($match);&nbsp; &nbsp; unset($match);&nbsp; &nbsp; require_once('photos_videos_albums.php');} else if (preg_match('~/root/([\w-]+)~', $request_uri, $match)) {&nbsp; &nbsp; $username = $match[1];&nbsp; &nbsp; unset($match);&nbsp; &nbsp; require_once('profile.php');} else if ($request_path == '/root/') {&nbsp; &nbsp; echo 'HOME';&nbsp; &nbsp; exit();} else {&nbsp; &nbsp; header('HTTP/1.0 404 Not Found');&nbsp; &nbsp; echo "<h1>404 Not Found</h1>";&nbsp; &nbsp; echo "The page that you have requested could not be found.";}
打开App,查看更多内容
随时随地看视频慕课网APP