I'm trying to add a trailing slash to urls using PHP. It can't be done with mod_rewrite since I have something similar to this in .htaccess:
RewriteRule ^page/(.*)$ index.php?page=$1 [L]
and I want to validate that the page exists before 301 redirect with trailing slash.
Right now I'm using this code after validation:
if(substr($_GET['page'], -1) !== '/')
header('Location: http://example.com/'.$_GET['page'].'/'.$_SERVER['QUERY_STRING'],TRUE,301);
But is there any better approach?
Simple way is that just remove the slash if available at the end of url and add it
$str = "http://yoursite.com/testpage";
OR
$str = "http://yoursite.com/testpage/";
echo rtrim($str,"/").'/';
You already have the best solution for this. I would just use $_SERVER['REQUEST_URI'] instead of the already parsed $_GET['page'] and $_SERVER['QUERY_STRING']:
if (substr($_GET['page'], -1) !== '/') {
$parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$uri = 'http://example.com'.$parts[0].'/'.(isset($parts[1]) ? '?'.$parts[1] : '');
header('Location: '.$uri, true, 301);
exit;
}
Here is my universal solution, hope it helps for somebody:
$site_adress = (((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
$whole_url = $site_adress . $_SERVER['REQUEST_URI'];
$pos = strpos($whole_url, "?");
$changed_url = FALSE;
if($pos !== FALSE && $whole_url[$pos - 1] != "/") {
$whole_url = substr_replace($whole_url, "/", $pos, 0);
$changed_url = TRUE;
} else if($pos == FALSE && substr($whole_url, -1) != '/') {
$whole_url = $whole_url . "/";
$changed_url = TRUE;
}
if($changed_url) {
header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $whole_url);
exit();
}
Related
function url(string $path = null): string
{
if (strpos($_SERVER['HTTP_HOST'], needle: "localhost")) {
if ($path) {
return CONF_URL_TEST . "/" . ($path[0] == "/" ? mb_substr($path, 1) : $path);
}
return CONF_URL_TEST;
}
if ($path) {
return CONF_URL_BASE . "/" . ($path[0] == "/" ? mb_substr($path, 1) : $path);
}
}
from what i saw this part of the code is not working
if (strpos($_SERVER['HTTP_HOST'], needle: "localhost"))
can someone give me a light please
strpos return an int so it can be 0. you can use
if (strpos($_SERVER['HTTP_HOST'], "localhost") > -1)
or
if (strpos($_SERVER['HTTP_HOST'], "localhost") !== false)
you can check for more : https://www.php.net/manual/en/function.strpos
This script is a function to define site url to send it to the big script but because it is shared hosting it gets incorrect path how can tell it the correct site path ? I wanna tell it the site url and script dir directly the script thinks this is the path /hermes/bosnaweb23a/index.php but the correct path is /index.php only.
I wanna remove /hermes/bosnaweb23a/
because /hermes/bosnaweb23a/ is the shared hosting path
<?php
function home_base_url(){
$base_url = (isset($_SERVER['HTTPS']) &&
$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';
$tmpURL = dirname(__FILE__);
$tmpURL = str_replace(chr(92),'/',$tmpURL);
$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);
$tmpURL = ltrim($tmpURL,'/');
$tmpURL = rtrim($tmpURL, '/');
if (strpos($tmpURL,'/')){
$tmpURL = explode('/',$tmpURL);
$tmpURL1 = $tmpURL[0];
$tmpURL2 = $tmpURL[1];
$tmpURL = $tmpURL1;
if(!empty($tmpURL2)) $tmpURL .= '/'.$tmpURL2;
}
if ($tmpURL !== $_SERVER['HTTP_HOST'])
$base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';
else
$base_url .= $tmpURL.'/';
$base_url = str_replace('//','/',$base_url);
$base_url = str_replace('http:/','http://',$base_url);
$base_url = str_replace('https:/','https://',$base_url);
return str_replace(dirname(__FILE__),'',$base_url);
}
$local_path = dirname(__FILE__).'/';
$sSoftware = strtolower( $_SERVER["SERVER_SOFTWARE"] );
function getSlashes() {
$sSoftware = strtolower( $_SERVER["SERVER_SOFTWARE"] );
if ( strpos($sSoftware, "microsoft-iis") !== false ) return "\\";
else return "/";
}
if ( strpos($sSoftware, "microsoft-iis") !== false ) {
$local_path = str_replace(getSlashes(), '/', dirname(__FILE__)).'/';
}
function get_domain() {
return $_SERVER['HTTP_HOST'];
}
$remote_path = home_base_url();
if((strpos($remote_path, '127.0.0.1') !== false) || (strpos($remote_path, 'localhost') !== false)) {
$find = str_replace(' ','',":\ ");
#$local_path = end(explode($find,$local_path));
define('DOCUMENT_ROOT', '/'.$local_path);
}else{
define('DOCUMENT_ROOT', '/'.$local_path);
}
?>
You could get index.php from /hermes/bosnaweb23a/index.php by using this code.
$url = explode("/", "/hermes/bosnaweb23a/index.php");
$script_name = end($url);
$script_name would be index.php.
When I rewrite my url with htaccess, I have 2 differents url.
normal url :
http://localhost/clicshopping_test/boutique/index.php/Products/Description/products_id,1
htaccess :
http://localhost/clicshopping_test/boutique/Products/Description/products_id,1
index.php/ is removed.
The problem is the link inside the website is not rewrited.
I tried to add :
$link = str_replace('index.php/', '',$link);
in this code to have the same link than as url, it does't work.
Do you have an idea for that ?
if ($search_engine_safe === true && defined('SEARCH_ENGINE_FRIENDLY_URLS') && SEARCH_ENGINE_FRIENDLY_URLS == 'true' && SEFU::start() && static::getSite() != 'ClicShoppingAdmin') {
$link = str_replace(['?', '&', '='], ['/', '/', ','], $link);
$link = str_replace('index.php/', '',$link);
}
tk.
the function about the OSCOM::link :
public static function link($page, $parameters = null, $add_session_id = true, $search_engine_safe = true) {
$page = HTML::sanitize($page);
$site = $req_site = static::$site;
if ((strpos($page, '/') !== false) && (preg_match('/^([A-Z][A-Za-z0-9-_]*)\/(.*)$/', $page, $matches) === 1) && CLICSHOPPING::siteExists($matches[1], false)) {
$req_site = $matches[1];
$page = $matches[2];
}
if (!is_bool($add_session_id)) {
$add_session_id = true;
}
if (!is_bool($search_engine_safe)) {
$search_engine_safe = true;
}
if (($add_session_id === true) && ($site !== $req_site)) {
$add_session_id = false;
}
$link = static::getConfig('http_server', $req_site) . static::getConfig('http_path', $req_site) . $page;
if (!empty($parameters)) {
$p = HTML::sanitize($parameters);
$p = str_replace([
"\\", // apps
'{', // product attributes
'}' // product attributes
], [
'%5C',
'%7B',
'%7D'
], $p);
$link .= '?' . $p;
$separator = '&';
} else {
$separator = '?';
}
while((substr($link, -1) == '&') || (substr($link, -1) == '?')) {
$link = substr($link, 0, -1);
}
// Add the session ID when moving from different HTTP and HTTPS servers, or when SID is defined
if (($add_session_id === true) && Registry::exists('Session')) {
$CLICSHOPPING_Session = Registry::get('Session');
if ($CLICSHOPPING_Session->hasStarted() && ($CLICSHOPPING_Session->isForceCookies() === false)) {
if ((strlen(SID) > 0) || (((HTTP::getRequestType() == 'NONSSL') && (parse_url(static::getConfig('http_server', $req_site), PHP_URL_SCHEME) == 'https')) || ((HTTP::getRequestType() == 'SSL') && (parse_url(static::getConfig('http_server', $req_site), PHP_URL_SCHEME) == 'http')))) {
$link .= $separator . HTML::sanitize(session_name() . '=' . session_id());
}
}
}
while(strpos($link, '&&') !== false) {
$link = str_replace('&&', '&', $link);
}
if ($search_engine_safe === true && defined('SEARCH_ENGINE_FRIENDLY_URLS') && SEARCH_ENGINE_FRIENDLY_URLS == 'true' && SEFU::start() && static::getSite() != 'ClicShoppingAdmin') {
$link = str_replace(['?', '&', '='], ['/', '/', ','], $link);
// $link = str_replace('index.php/', '',$link);
}
return $link;
}
function for HTML::link
public static function link($url, $element, $parameters = null) {
return '<a href="' . $url . '"' . (!empty($parameters) ? ' ' . $parameters : '') . '>' . $element . '</a>';
}
the call :
$products_image = HTML::link(OSCOM::link('index.php', 'Products&Description&products_id=' . $products_id), HTML::image($CLICSHOPPING_Template->getDirectoryTemplateImages() . $CLICSHOPPING_ProductsCommon->getProductsImage($products_id), HTML::outputProtected($products_name_image), (int)SMALL_IMAGE_WIDTH, (int)SMALL_IMAGE_HEIGHT));
My htaccess
Options -Indexes
Options +FollowSymlinks
#note for apache2 must be activated becarefull on apache 2.4
#AllowOverride All
#AcceptPathInfo on
#### Your config to change ###############
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
#to change in function your website
RewriteBase /test/boutique/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#to change in function your website
RewriteRule . /test/boutique/index.php [L]
#to change in function your website
#uncomment to have clear url
RewriteCond %{THE_REQUEST} /test/boutique/index\.php/(\S*)\s [NC]
RewriteRule ^ %1 [L,R=301,NE]
</IfModule>
I'm trying to force redirect to www with https from index.php but i keep getting an infinite redirect loop.
Here is my code:
index.php:
$configs = include_once($_SERVER['DOCUMENT_ROOT'] . '/application/config/maintenance.php');
if (stripos($_SERVER['SERVER_PROTOCOL'], 'https') === false && $configs['protocol'] == 'https') {
$protocol = 'https://';
$protocolRedirect = true;
} else {
$protocol = 'http://';
$protocolRedirect = false;
}
if (strtolower(substr($_SERVER['HTTP_HOST'], 0, 4)) !== 'www.') {
$url = $protocol . 'www.' . $_SERVER['HTTP_HOST'];
$wwwRedirect = true;
} else {
$url = $protocol . $_SERVER['HTTP_HOST'];
$wwwRedirect = false;
}
if ($_SERVER['REQUEST_URI'] != '/') {
$url .= $_SERVER['REQUEST_URI'];
}
if ((isset($wwwRedirect) && $wwwRedirect == true) || (isset($protocolRedirect) && $protocolRedirect == true )) {
header('Location: ' . $url);
exit();
}
maintenance.php:
return array(
'protocol' => 'https'
);
Any idea why?
Note: server is running Nginx - but i don't want to redirect thorugh it.
What I am trying to do is to display a message (1) if the current link does not contain the words "index" or "/?"
I found this to do the direct opposite:
$page = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($page, 'index.php') !== false xor strpos($page, '/?') !== false) {
echo '1';
} else {
echo '2';
}
This code displays "2" on pages where there is no "index" or "/?" in the link, but I need the opposite: display "1" where there is no "index" or "/?" in the link.
BTW I have tried all combinations: !strpos, TRUE, !==, but it doesn't seem to work for me. I need a way without the "else" in the code, otherwise I could just change up the echos.
$page = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($page, 'index.php') === false && strpos($page, '/?') === false)
{
echo"1";
}
else
{
echo"2";
}
Should display 1 if there's no index.php or /? in $page
The condition in your if statement is
if( <<COND 1>> xor <<COND 2>> )
where, xor's feature is
return TRUE if either <<COND 1>> or <<COND 2>> is TRUE, but not both.
You should instead use this:
if( strpos($page, 'index.php') !== false OR strpos($page, '/?') !== false )
Check this page for more information about logical operators.
$page = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($page, '/?') === false && strpos($page, 'index.php') === false)
{
echo "1";
}
else
{
echo "2";
}
Try this :
$page = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($page, 'index.php') === false || strpos($page, '/?') === false)
{
echo"1";
}
else
{
echo"2";
}