Intento explicar este problema paso a paso en el siguiente ejemplo.
0) Pregunta
trato de preguntarle como esto:
Quiero abrir la página de perfil de facebook como www.facebook.com/kaila.piyush
que llegar Identificación de url y analizarlo en el archivo profile.php y devolver los datos de la base de datos y mostrar al usuario su perfil
Normalmente, cuando desarrollamos cualquier sitio web, su enlace se parece a www.websit e.com/profile.php?id=username example.com/weblog/index.php?y=2000 & m = 11 d = 23 & & id = 5678
ahora nos ponemos al día con el nuevo estilo no nos reescribir utilizar www.website.com/username o example.com/weblog/2000/11/23/5678 como enlace permanente
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Crear un archivo .htaccess en la carpeta raíz o actualice el existente:
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
¿Qué significa eso?
Si la solicitud es para un directorio o archivo real (uno que existe en el servidor), index.php no se sirve, de lo contrario, cada URL se redirige a index.php.
2) index.php
Ahora, queremos saber qué acción para disparar, por lo que necesitamos para leer la URL:
En 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);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the 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
Ahora en el archivo profile.php, deberíamos tener algo como t la suya:
// 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);
}
Un gran recurso mod_rewrite: http://www.addedbytes.com/apache/mod_rewrite-cheat-sheet/ –
Sugeriría su tutorial antes de la cheatsheet: http://www.addedbytes.com/apache/url-rewriting-for-beginners/ –
Otra opción, si desea hacer su reescritura de URL enteramente PHP, es establecer reglas de reescritura para dirigir todas las solicitudes a una sola secuencia de comandos . Una gran ventaja de esto es que puede almacenar su código en un área no accesible para Apache, y solo su script de despacho de URL debe ser accesible para Apache. por ejemplo: RewriteCond% {REQUEST_FILENAME}! -f RewriteCond% {REQUEST_FILENAME}! -d RewriteRule. dispatch.php Esto es similar a su ejemplo de tipo de fuerza. –