$_SERVER['REQUEST_URI'] doesn't match url - php

I uploaded a new website in a sub-folder of my server documentroot (www.example.com/demos/website-name) as I've always done to show demos to my clients.
In my cms I use mod_rewrite to push all requests to index.php and an "internal" rewrite in php, so I have to retrieve the $_SERVER['REQUEST_URI'] to read it and load the correct page.
Quite randomly (and only when the cms is placed in a subfolder like this case) the REQUEST_URI doesn't match the uri in the browser but remains the previous one: for example I'm in "/cms/foo", i click a link that brings me to "/cms/bar", the page reloads but if i dump the REQUEST_URI I still get "/cms/foo".
I really can't understand how this is possible.
This is how the .htaccess looks like:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
And here it is how I retrieve the REQUEST_URI (MainConfig::ROOT_URL is the sub-folder path "/demos/website-name"):
public static function getPath()
{
if(isset(self::$cache['path'])) {
return self::$cache['path'];
}
if(isset($_SERVER['REQUEST_URI'])) {
$path = str_replace(MainConfig::ROOT_URL, '', $_SERVER["REQUEST_URI"]);
$path = explode('/', $path);
if(trim($path[1]) == '') {
$path = array();
}
unset($path[0]);
$path = array_values($path);
for($i = 0; $i < count($path); $i++) {
$fragment = $path[$i];
if(strpos($fragment, '?') !== false) {
$lastPathIndex = $i;
break;
} elseif(strpos($fragment, 'index.php') !== false) {
$lastPathIndex = $i;
break;
}
}
if(isset($lastPathIndex)) {
$lastPathElement = array();
$length = count($path);
for($i = $lastPathIndex; $i < $length; $i++) {
$lastPathElement[] = $path[$i];
unset($path[$i]);
}
$lastPathElement = str_replace('index.php', '', implode('/', $lastPathElement));
}
if(isset($lastPathElement)) {
$path[] = $lastPathElement;
}
} else {
$path = array();
}
$path = array_values($path);
self::$cache['path'] = $path;
return $path;
}

Related

How can I prevent double checks in this function?

Here is a code to search and return the existing files from the given directories:
<?php
function getDirContents($directories, &$results = array()) {
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
if(is_file($directories[$i])) {
if(file_exists($directories[$i])) {
$path = $directories[$i];
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
} else {
$files = array_diff(scandir($directories[$i]), array('..', '.'));
foreach($files as $key => $value) {
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents([$path], $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
}
return $results;
}
echo json_encode(getDirContents($_POST['directories']));
So you can pass an array of file addresses and directories and get what ever files inside those directories, Note if you pass a file address instead of a directory address the function checks if there is such a file and if there is it returns its address in the result .
The issue is for the directories it works fine but the files repeat twice in the result and for each file the function double checks this if statement in the code:
if(is_file($directories[$i]))
Here is a result of the function note that contemporary.mp3 and Japanese.mp3
has been re checked and added to the result.
How can I solve this?
If $directories contains both a directory and a file within that directory, you'll add the file to the result for the filename and also when scanning the directory.
A simple fix is to check whether the filename is already in the result before adding it.
<?php
function getDirContents($directories, &$results = array()) {
foreach ($directories as $name) {
if(is_file($name)) {
$path = $name;
$directory_path = basename($_SERVER['REQUEST_URI']);
$new_path = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
if (!in_array($new_path, $results)) {
$results[] = $new_path;
}
} elseif (is_dir($name)) {
$files = array_diff(scandir($name), array('..', '.'));
foreach($files as $key => $value) {
$path = $name.DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents([$path], $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$new_path = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
if (!in_array($new_path, $results)) {
$results[] = $new_path;
}
}
}
}
}
return $results;
}

Php - Delete files older than 7 days for multiple folders

i would like to create a PHP script that delete files from multiple folders/paths.
I managed something but I would like to adapt this code for more specific folders.
This is the code:
<?php
function deleteOlderFiles($path,$days) {
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($path . $file);
if((time() - $filelastmodified) > $days*24*3600)
{
if(is_file($path . $file)) {
unlink($path . $file);
}
}
}
closedir($handle);
}
}
$path = 'C:/Users/Legion/AppData/Local/Temp';
$days = 7;
deleteOlderFiles($path,$days);
?>
I would like to make something like to add more paths and this function to run for every path.
I tried to add multiple path locations but it didn't work because it always takes the last $ path variable.
For exemple:
$path = 'C:/Users/Legion/AppData/Local/Temp';
$path = 'C:/Users/Legion/AppData/Local/Temp/bla';
$path = 'C:/Users/Legion/AppData/Local/Temp/blabla';
$path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
$days = 7;
deleteOlderFiles($path,$days);
Thank you for you help!
The simple solution, call the function after setting the parameter not after setting all the possible parameters into a scalar variable.
$days = 7;
$path = 'C:/Users/Legion/AppData/Local/Temp';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/bla';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/blabla';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
deleteOlderFiles($path,$days);
Alternatively, place the directories in an array and then call the funtion from within a foreach loop.
$paths = [];
$paths[] = 'C:/Users/Legion/AppData/Local/Temp';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/bla';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/blabla';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
$days = 7;
foreach ( $paths as $path){
deleteOlderFiles($path,$days);
}
It seems that you need a recursive function, i.e. a function that calls itself. In this case it calls itself when it finds a subdirectory to scan/traverse.
function delete_files($current_path, $days) {
$files_in_current_path = scandir($current_path);
foreach($files_in_current_path as $file) {
if (!in_array($release_file, [".", ".."])) {
if (is_dir($current_path . "/" . $file)) {
// Scan found subdirectory
delete_files($current_path . "/" . $file, $days);
} else {
// Here you add your code for checking date and deletion of the $file
$filelastmodified = filemtime($current_path . "/" . $file);
if((time() - $filelastmodified) > $days*24*3600) {
if(is_file($current_path . "/" . $file)) {
unlink($current_path . "/". $file);
}
}
}
}
}
}
delete_files("your/startpath/here", 7);
This code starts in your specified start path. It scans all files in that directory. If a sub directory is found, there will be a new call to delete_files, but with that sub directory as a start.

2 different urls inside a website

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>

How to make directory within directory by php loop?

How to make directory within directory by php loop?
Example: http://site_name/a/b/c/d
First create a then b within a then c within b then ....
Problem is here a,b,c,d all the folders created in root directory not one within one.
Here is my code -
<?php
$url = "http://site_name/a/b/c/d";
$details1 = parse_url(dirname($url));
$base_url = $details1['scheme'] . "//" . $details1['host'] . "/";
if ($details1['host'] == 'localhost') {
$path_init = 2;
}else {
$path_init = 1;
}
$paths = explode("/", $details1['path']);
for ($i = $path_init; $i < count($paths); $i++) {
$new_dir = '';
$base_url = $base_url . $paths[$i] . "/";
$new_dir = $base_url;
if (FALSE === ($new_dir = folder_exist($paths[$i]))) {
umask(0777);
mkdir($new_dir . $paths[$i], 0777, TRUE);
}
}
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
?>
please check this code. it will create nested folder if not exit
<?php
$your_path = "Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$array_folder = explode('/', $your_path);
$mkyourfolder = "";
foreach ($array_folder as $folder) {
$mkyourfolder = $mkyourfolder . $folder . "/";
if (!is_dir($mkyourfolder)) {
mkdir($mkyourfolder, 0777);
}
}
hope it will help you
You can actually create nested folders with the mkdir PHP function
mkdir($path, 0777, true); // the true value here = recursively
Dear friends the following answer is tested and used in my script -
<?php
$url = "http://localhost/Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$details = parse_url(dirname($url));
//$base_url = $details['scheme'] . "//" . $details['host'] . "/";
$paths = explode("/", $details['path']);
$full_dir = '';
$init = ($details['host'] == 'localhost') ? '2' : '1';
for ($i = $init; $i < count($paths); $i++) {
$full_dir = $full_dir . $paths[$i] . "/";
if (!is_dir($full_dir)) {
mkdir($full_dir, 0777);
}
}
?>

copy a php file to every directory

I've a simple problem of copying a a php folder to some directories, bu the problem is I can't the solution for that, the idea is that I've an Online Manga Viewer script, and what I want to do is I want to add comments page to every chapter, the I dea that I came with, is, I create a separate comments page file and once a new chapter added the the comments file will be copied to the folder of the chapter :
Description Image:
http://i.stack.imgur.com/4wYE0.png
What I to know is how can I do it knowing that I will use Disqus commenting System.
Functions used in the script:
function omv_get_mangas() {
$mangas = array();
$dirname = "mangas/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$mangas[] = $file;
}
}
#closedir($dir);
}
sort($mangas);
return $mangas;
}
function omv_get_chapters($manga) {
global $omv_chapters_sorting;
$chapters = array();
$chapters_id = array();
$dirname = "mangas/$manga/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$chapter = array();
$chapter["folder"] = $file;
$pos = strpos($file, '-');
if ($pos === false) {
$chapter["number"] = $file;
} else {
$chapter["number"] = trim(substr($file, 0, $pos - 1));
$chapter["title"] = trim(substr($file, $pos + 1));
}
$chapters_id[] = $chapter["number"];
$chapters[] = $chapter;
}
}
#closedir($dir);
}
array_multisort($chapters_id, $omv_chapters_sorting, $chapters);
return $chapters;
}
function omv_get_chapter_index($chapters, $chapter_number) {
$i = 0;
while (($i < count($chapters)) && ($chapters[$i]["number"] != $chapter_number)) $i++;
return ($i < count($chapters)) ? $i : -1;
}
function omv_get_pages($manga, $chapter) {
global $omv_img_types;
$pages = array();
$dirname = "mangas/$manga/$chapter/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (!is_dir($dirname . $file . '/')) {
$file_extension = strtolower(substr($file, strrpos($file, ".") + 1));
if (in_array($file_extension, $omv_img_types)) {
$pages[] = $file;
}
}
}
#closedir($dir);
}
sort($pages);
return $pages;
}
/*function add_chapter_comment($dirname){
$filename = $dirname.'comments.php';
if (file_exists($filename)) {
} else {
copy('comments.php', .$dirname.'comments.php');
}
}*/
function omv_get_previous_page($manga_e, $chapter_number_e, $current_page, $previous_chapter) {
if ($current_page > 1) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page - 1);
} else if ($previous_chapter) {
$pages = omv_get_pages(omv_decode($manga_e), $previous_chapter["folder"]);
return $manga_e . '/' . omv_encode($previous_chapter["number"]) . '/' . count($pages);
} else {
return null;
}
}
function omv_get_next_page($manga_e, $chapter_number_e, $current_page, $nb_pages, $next_chapter) {
if ($current_page < $nb_pages) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page + 1);
} else if ($next_chapter) {
return $manga_e . '/' . omv_encode($next_chapter["number"]);
} else {
return null;
}
}
function omv_get_image_size($img) {
global $omv_img_resize, $omv_preferred_width;
$size = array();
$imginfo = getimagesize($img);
$size["width"] = intval($imginfo[0]);
$size["height"] = intval($imginfo[1]);
if ($omv_img_resize) {
if ($size["width"] > $omv_preferred_width) {
$size["height"] = intval($size["height"] * ($omv_preferred_width / $size["width"]));
$size["width"] = $omv_preferred_width;
}
}
return $size;
}
And thanks for all of you!
Include the following line in all of your pages in a small php statement, if it covers two folder paths, use this. Which I think in your case it does.
<?php
include('../../header.php');
?>
And then save this in the main root directory. Which in your diagram is called "Main Folder"

Categories