PHP: variabili htaccess predefinito
-
05-10-2019 - |
Domanda
Voglio impostare una variabile di default per una query che arriva alla fine di un URL
Il file .htaccess reindirizza l'URL nel seguente modo:
http://www.server.com/folder/subfolder/index.php?page="some-page-name"
visualizzata url
http://www.server.com/folder/some-page-name
Se il nome della pagina non è impostato, come in:
http://www.server.com/folder/
il default sarebbe "indice". Ho potuto utilizzare la funzione php header("location:url")
ma che sarebbe visualizzare la parte "indice" alla fine se l'url ... che io non voglio.
contenuti htacess
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
#RewriteCond %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteBase /folder/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^.*\.css.*$ [NC]
RewriteRule ^(.*)$ subfolder/index.php/?page=$1 [L]
</IfModule>
<IfModule mod_rewrite.c>
ErrorDocument 404 /error.html
ErrorDocument 403 /error.html
</IfModule>
Soluzione
Non c'è bisogno di reindirizzare a index.php. È possibile usare qualcosa come:
header('Location: /folder/front-page');
Se si desidera solo http://example.com/folder/ mostrare la vostra pagina di indice, è potrebbe utilizzare il seguente nello script PHP:
$requested_page = filter_input(INPUT_GET, 'pageID');
$allowed_pages = array('some-page', 'some-page-name');
if($requested_page == ''){
// display your index page as ?pageID is not set or empty
}
elseif(in_array($requested_page, $allowed_pages)){
// display $requested_page
}
else{
// display a 404 Not Found error
}
Altri suggerimenti
Prova questo codice nel file PHP:
$pageID = 'index';
if(isset($_REQUEST['pageID']) && !empty($_REQUEST['pageID']))
$pageID = get_magic_quotes_gpc() ? stripslashes($_REQUEST['pageID']) : $_REQUEST['pageID'];
// Your code should now use the $pageID variable...
Che cosa questo farà è impostato $pageID
ad un valore predefinito di "indice". Quindi, se un PageID diverso è dato dal mod_rewrite, $pageID
punterà insieme a quel valore. Il codice dovrebbe quindi utilizzare il valore della $pageID
.
La tua domanda è stata troppo a lungo, non ha letto, se si desidera solo per impostare una variabile nel file .htaccess e passarlo al PHP è abbastanza facile da fare in questo modo -
Nel file .htaccess (http://httpd.apache.org/docs/2.0/mod/mod_env.html#setenv):
SetEnv default_url http://my.url/goes/here
Nello script PHP (http://www.php.net/manual/en/reserved.variables.environment.php):
header('Location: '. $_ENV['default_url']);
In alternativa, se avete i gestori ErrorDocument
, si potrebbe essere in grado di inviare semplicemente un codice di stato così (vedi la terza opzione per header()
, http://us.php.net/manual/en/function.header.php ).