フォルダなし、index.phpなし
このチュートリアルをご覧ください。
編集:
これは単なる要約です。
0)コンテキスト
次のURLが必要だと思います。
http://example.com/profile/userid(IDでプロファイルを取得)
http://example.com/profile/username (ユーザー名でプロファイルを取得)
http://example.com/myprofile(現在ログインしているユーザーのプロファイル)
1).htaccess
ルートフォルダに.htaccessファイルを作成するか、既存のファイルを更新します。
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
それは何をしますか?
リクエストが実際のディレクトリまたはファイル(サーバー上に存在するもの)に対するものである場合、index.phpは提供されません。そうでない場合、すべてのURLがindex.phpにリダイレクトされます。
2)index.php
ここで、トリガーするアクションを知りたいので、URLを読み取る必要があります。
index.phpで:
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
URL http://example.com/profile/19837の場合、$コマンドには次のものが含まれます。
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
次に、URLをディスパッチする必要があります。これをindex.phpに追加します:
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2)profile.php
これで、profile.phpファイルに次のようなものが含まれるはずです。
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
結論として
私は十分に明確だったらいいのにと思います。このコードはきれいではなく、OOPスタイルでもないことは知っていますが、いくつかのアイデアが得られる可能性があります...