Вопрос по php, facebook, profile – Facebook как пользовательский профиль URL PHP
Создание сайта, и я хочу добавить URL-адрес настраиваемого профиля для всех пользователей моего сайта (например, Facebook).
На моем сайте уже есть страница, похожая наhttp: //sitename.com/profile.php ID = 100224232
Однако я хочу сделать зеркало для тех страниц, которое связано с их именем пользователя. Например, если вы идете наhttp: //sitename.com/profile.php ID = 100224232 он перенаправляет тебяhttp: //sitename.com/myprofil
Как мне это сделать с помощью PHP и Apache?
Просто взгляни на эторуководств.
Редактировать Это всего лишь краткое изложение.
0) КонтекстЯ предполагаю, что нам нужны следующие URL:
http: //example.com/profile/useri (получить профиль по идентификатору)
http: //example.com/profile/usernam (получить профиль по имени пользователя)
http: //example.com/myprofil (получить профиль текущего пользователя, вошедшего в систему)
Создайте файл .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:
In 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);
С URLhttp: //example.com/profile/1983, $ command будет содержать:
$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);
}
ЗаключитХотел бы я быть достаточно ясным. Я знаю, что этот код не симпатичен и не в стиле ООП, но он может дать некоторые идеи ...