为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕仙森 2023-10-15 10:45:41
我想用常规文件编写一个项目。索引文件有一个 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 在这里:.htaccessRewriteRule ^(.*)$ index.php?page=$1 [L,QSA]RewriteRule (?:^|/)([\w-]+)/?$ profile.php?username=$1 [L,QSA]我的问题是这样的。如何在 switch 中使用成员的用户名来调用成员的个人资料。
查看完整描述

1 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

我如何在 switch 中使用成员的用户名来调用成员的个人资料,因为 $thePage 数组中没有每个用户名。


只需将所有内容传递给index.php


.htaccess:


# Activate rewrite engine

RewriteEngine on

RewriteBase /root/


# If the request is not for a valid directory, file or symlink

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-l


# Redirect all requests to index.php

RewriteRule ^(.*)$ 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) {

    $request_path = substr($request_uri, 0, $params_offset);

    $params = explode('&', substr($request_uri, $params_offset + 1));

    foreach ($params as $value) {

        $key_value = explode('=', $value);

        $request_params[$key_value[0]] = $key_value[1];

    }

} else {

    $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)) {

    print_r($match);

    unset($match);

    require_once('photos_videos_albums.php');

} else if (preg_match('~/root/([\w-]+)~', $request_uri, $match)) {

    $username = $match[1];

    unset($match);

    require_once('profile.php');

} else if ($request_path == '/root/') {

    echo 'HOME';

    exit();

} else {

    header('HTTP/1.0 404 Not Found');

    echo "<h1>404 Not Found</h1>";

    echo "The page that you have requested could not be found.";

}


查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 61 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信