PHP on windows path comes up with backward slash - php

Trying to setup a php website on my windows os. PHP code that I got from someone has lines like
$base_path = realpath('./../').'/';
This ends up with the string like c:\abc\xyz/
What settings I need to do on windows to force it to come with /. I read about DIRECTORY_SEPERATOR, but there are various places I need to worry about and hence if I could have it so that the realpath comes up with / it will be of great help to me.

A variation of Timothy's answer which uses the DIRECTORY_SEPARATOR constant instead of a conditional to simplify the function.
function platformSlashes($path) {
return str_replace('/', DIRECTORY_SEPARATOR, $path);
}
$path = "/some/path/here";
echo platformSlashes($path);

The backslash is the directory separator on the Windows platform. But from what I understand and have experienced, when resolving paths your PHP script will still work with forward slashes. As a consequence, you could write all your code with forward slashes and not worry about it. The forward/backwardslashes are really only important if you're displaying the path to the user, like in a setup/installer script (most users of a site would have no need to know about directory structures nor care what platform the service is running on). You could create a display function that would identify the platform and replace the slashes as appropriate, and then pass the paths through this before showing them. The following is an example of what I'm suggesting, though I haven't tested it.
<?php
function platformSlashes($path) {
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$path = str_replace('/', '\\', $path);
}
return $path;
}
$path = "/some/path/here";
echo platformSlashes($path);

Just do a replace on the string you have:
$base_path = realpath('./../') . '/';
$base_path_mod = str_replace('\\', '/', $base_path);

Related

XSS and file_get_contents?

My url is like page.php?path=content/x/y/z/aaa.md. Is the following php code XSS-secure?
include "Parsedown.php";
function path_purifier($path) {
if(substr($path, 0, 8) !== "content/")
return null;
if (strpos($path,'..') !== false)
return null;
return "./" . $path;
}
$parsedown = new Parsedown();
$path = $_GET['path'];
$path = path_purifier($path);
echo $parsedown->text(file_get_contents($path));
Thanks for your attention
Yes, looks secure enough, but still not perfect. You also need to call is_file() and ensure it returns true, before you call file_get_contents(). Also to make it even safer you can implement a CSRF protection on top of it.
Also, keep in mind, that some hosting providers don't allow relative paths. So if a path like '/content/x/y/file.md' might work on you local machine, keep in mind that on some hosters it will not. So you'd better always use absolute paths like __DIR__ . '/content/x/y/file.md'

PHP: Convert windows path to unix path

I'm trying to host a PHP website developed on a Mac on IIS.
I have an upload form for images. The path to the images is saved to the database in Windows style (i.e. \images\foo.jpeg). In my template I use these images as background using css. Because of the Windows-style paths the images are not displayed, cause the path is incorrect.
Question: How can I convert a Windows path to a valid URL. So \uploads\images\25.jpeg should be changed to /uploads/images/25.jpeg . Is there a function like realpath that can do this or should I take the dirty way using a str_replace or regex?
You convert all windows path to UNIX path using the following function. it's a WordPress core function and well tested
function wp_normalize_path( $path ) {
$path = str_replace( '\\', '/', $path );
$path = preg_replace( '|(?<=.)/+|', '/', $path );
if ( ':' === substr( $path, 1, 1 ) ) {
$path = ucfirst( $path );
}
return $path;
}
Example :
E:\\xampp\\htdocs\\php\\index.php
Output :
E:/xampp/htdocs/php/index.php
Try to use the DIRECTORY_SEPARATOR instead of the '/' or '\' for paths (dir constants). This constant will recognize the OS for you and will use the right separator base on that.
To change the oldpath you can try to use:
str_replace("/", DIRECTORY_SEPARATOR, 'example/bla/bla.php');
As tip: __FILE__, __DIR__ or dirname() can help you in lot of situations to get the right path on the running OS.

PHP Include based on REQUEST_URI

Is there any security risks involved in using $_SERVER['REQUEST_URI'] to include a file? Can you pass ../../.. through the request uri somehow?
What I'm thinking is something like this:
<?php
$path = $_SERVER['REQUEST_URI'];
$path = preg_replace('~\\.html?$~', '.php', $path);
include $path;
?>
This should substitute ".htm" or ".html" URIs for ".php" paths and render them. But I am concerned about security here.
$_SERVER['REQUEST_URI'] contains the requested URI path and query string as it appeared in the HTTP request line. So when http://example.com/foo/bar?baz=quux is requested and the server passes the request to the script file /request_handler.php, $_SERVER['REQUEST_URI'] would still be /foo/bar?baz=quux. I’ve used mod_rewrite to map any request to request_handler.php as follows:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /request_handler.php
So for correctness, before using $_SERVER['REQUEST_URI'] in a file system path, you would need to get rid of the query string. You can use parse_url to do so:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
But as this value comes directly from the HTTP request line without prior path resolution, it may still contain symbolic path segments like ...
However, path traversal is not even necessary as the requested URI path is already an absolute path reference and requesting http://example.com/etc/passwd should result in the inclusion of /etc/passwd.
So this is actually a local file inclusion vulnerability.
Now to fix this, requiring a certain root directory using the method that you, chowey, have presented is a good improvement. But you would actually need to prefix it with $basedir:
$path = realpath($basedir . $_SERVER['REQUEST_URI_PATH']);
if ($path && strpos($path, $basedir) === 0) {
include $path;
}
This solution provides several promises:
$path is either a valid, resolved path to an existing file, or false;
inclusion of that file does only happen if $basedir is a prefix path of $path.
However, this may still allow access to files which are protected using some other kind of access control like the one provided by Apache’s mod_authz_host module.
This does not actually answer the question...
Note that you can ensure the request uri points to an actual valid filepath in the current working directory. You can use the realpath function to normalize the path.
The following code would do the trick:
<?php
$basedir = getcwd();
$path = $_SERVER['REQUEST_URI'];
$path = preg_replace('~\\.html?$~', '.php', $path);
$path = realpath($path);
if ($path && strpos($path, $basedir) === 0) {
include $path;
} else {
return false;
}
?>
Here I used strpos to verify that the $path starts with $basepath. Since realpath will have removed any ../../.. funny business, this should safely keep you within the $basepath directory.
Indeed dont trust the $_SERVER['REQUEST_URI'] before checking the basepath.
And dont make a filter that removes ../ from the path attackers can craft a nieuw way to inject if they understand the filter proces.
I had the same question and chose to do the following basing myself on Gumbo's answer :
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path = realpath(FOLDER_ROOT . $_SERVER['REQUEST_URI_PATH']);
$directory_white_list_array = array('/safe_folder1', '/safe_folder1/safe_folder2');
if ($path && strpos($path, FOLDER_ROOT) === 0 && (in_array(dirname($path), $directory_white_list_array) && ('php' == pathinfo($path, PATHINFO_EXTENSION)))) {
include $path;
}else{
require_once FOLDER_ROOT."/miscellaneous_functions/navigation_error.php";
navigation_error('1');
}
Summary:
Added directory whitelist and .php extension restriction.

prevent /.. user input

I have a php script in a folder (I call it the root folder). The script can basically list all files in subfolders of this root folder. The user can specify which subfolder should be displayed by using GET-parameters.
script.php?foo
would display the content of
<root folder>/foo/
and
script.php?.bar
would display the content of
<root folder>/.bar/
However, users could also "cheat" and use commands like /.. to display the content of folders they souldn't be able to see.
For example with
script.php?/../..
the users could get very high in the folder hierarchy.
Do you have an idea how to prevent users of doing "cheats" like this.
For reason of simplicity, let's say the GET-parameter is stored in $searchStatement.
You could use realpath to resolve the relative path to an absolute one and then check if that path begins with your "root" folder's path:
$absolutePath = realpath(__DIR__ . '/' . trim($searchStatement, '/'));
if (strpos($absolutePath, __DIR__ .'/') !== 0) {
die('Access denied.');
}
You just should validate the input before you use it.
For example you might want to only allow the characters a-z and / to allow subdirectories. Probably you want to allow the . as well. If you make this subset small, it's easy to validate if the input is allowed or not by the allowed characters already.
At the moment you allow ., as you have noticed, you have the problem that relative paths could be created like /../../ which could be used for directory traversal attacks.
To validate if a string contains only characters of a specific range, you can validate this with a regular expression or the filter functions. If your website does not need to allow any relative path parts you can look if they exist in the path to validate the input:
$valid = !array_intersect(array('', '.', '..'), explode('/', $path));
Valid will be FALSE if there is any // or /./ or /../ part inside the path.
If you need to allow relative paths, realpath has already been suggested, so to query the input against your directory structure first. I would only use it as last resort as it is relatively expensive, but it's good to know about.
However you can resolve the string your own as well with some simple function like the following one:
/**
* resolve path to itself
*
* #param string $path
* #return string resolved path
*/
function resolvePath($path)
{
$path = trim($path, '/');
$segmentsIn = explode('/', $path);
$segmentsOut = array();
foreach ($segmentsIn as $in)
{
switch ($in)
{
case '':
$segmentsOut = array();
break;
case '.':
break;
case '..';
array_pop($segmentsOut);
break;
default:
$segmentsOut[] = $in;
}
}
return implode('/', $segmentsOut);
}
Usage:
$tests = array(
'hello',
'world/.',
'../minka',
'../../42',
'../.bar',
'../hello/path/./to/../../world',
);
foreach($tests as $path)
{
printf("%s -> %s\n", $path, resolvePath($path));
}
Output:
hello -> hello
world/. -> world
../minka -> minka
../../42 -> 42
../.bar -> .bar
../hello/path/./to/../../world -> hello/world
I can only suggest you first validate the input based on it's own data before letting touch it the filesystem, even through realpath.
Have a look at the chroot function:
bool chroot ( string $directory )
Changes the root directory of the current process to directory, and changes the current working directory to "/".
A call to that method prevents further access to files outside of the current directory.
Note however that requires root privileges.
Have you tried something with realpath, it should resolve all the /.. in your path. By testing the realpath of the arguments against your current path like:
substr($realpath, 0, strlen('/basepath/cant/go/above')) === '/basepath/cant/go/above'
you make sure that any /.. havent escaped from where you want.

file_exists() returns false, but the file DOES exist

I'm having a very weird issue with file_exists(). I'm using this function to check if 2 different files in the same folders do exist. I've double-checked, they BOTH do exist.
echo $relative . $url['path'] . '/' . $path['filename'] . '.jpg';
Result: ../../images/example/001-001.jpg
echo $relative . $url['path'] . '/' . $path['filename'] . '.' . $path['extension'];
Result: ../../images/example/001-001.PNG
Now let's use file_exists() on these:
var_dump(file_exists($relative . $url['path'] . '/' . $path['filename'] . '.jpg'));
Result: bool(false)
var_dump(file_exists($relative . $url['path'] . '/' . $path['filename'] . '.' . $path['extension']));
Result: bool(true)
I don't get it - both of these files do exist. I'm running Windows, so it's not related to a case-sensitive issue. Safe Mode is off.
What might be worth mentioning though is that the .png one is uploaded by a user via FTP, while the .jpg one is created using a script. But as far as I know, that shouldn't make a difference.
Any tips?
Thanks
file_exists() just doesn't work with HTTP addresses.
It only supports filesystem paths (and FTP, if you're using PHP5.)
Please note:
Works :
if (file_exists($_SERVER['DOCUMENT_ROOT']."/folder/test.txt")
echo "file exists";
Does not work:
if (file_exists("www.mysite.com/folder/test.txt")
echo "file exists";
Results of the file_exists() are cached, so try using clearstatcache(). If that not helped, recheck names - they might be similar, but not same.
I found that what works for me to check if a file exists (relative to the current php file it is being executed from) is this piece of code:
$filename = 'myfile.jpg';
$file_path_and_name = dirname(__FILE__) . DIRECTORY_SEPARATOR . "{$filename}";
if ( file_exists($file_path_and_name) ){
// file exists. Do some magic...
} else {
// file does not exists...
}
Just my $.02: I just had this problem and it was due to a space at the end of the file name. It's not always a path problem - although that is the first thing I check - always. I could cut and paste the file name into a shell window using the ls -l command and of course that locates the file because the command line will ignore the space where as file_exists does not. Very frustrating indeed and nearly impossible to locate were it not for StackOverflow.
HINT: When outputting debug statements enclose values with delimiters () or [] and that will show a space pretty clearly. And always remember to trim your input.
It's because of safe mode. You can turn it off or include the directory in safe_mode_include_dir. Or change file ownership / permissions for those files.
php.net: file_exists()
php.net: safe mode
Try using DIRECTORY_SEPARATOR instead of '/' as separator. Windows uses a different separator for file system paths (backslash) than Linux and Unix systems.
A very simple trick is here that worked for me.
When I write following line, than it returns false.
if(file_exists('/my-dreams-files/'.$_GET['article'].'.html'))
And when I write with removing URL starting slash, then it returns true.
if(file_exists('my-dreams-files/'.$_GET['article'].'.html'))
I have a new reason this happens - I am using PHP inside a Docker container with a mounted volume for the codebase which resides on my local host machine.
I was getting file_exists == FALSE (inside Composer autoload), but if I copied the filepath into terminal - it did exist! I tried the clearstatche(), checked safe-mode was OFF.
Then I remembered the Docker volume mapping: the absolute path on my local host machine certainly doesn't exist inside the Docker container - which is PHP's perspective on the world.
(I keep forgetting I'm using Docker, because I've made shell functions which wrap the docker run commands so nicely...)
It can also be a permission problem on one of the parent folders or the file itself.
Try to open a session as the user running your webserver and cd into it. The folder must be accessible by this user and the file must be readable.
If not, php will return that the file doesn't exist.
have you tried manual entry. also your two extensions seem to be in different case
var_dump(file_exists('../../images/example/001-001.jpg'));
var_dump(file_exists('../../images/example/001-001.PNG'));
A custom_file_exists() function inspired by #Timur, #Brian, #Doug and #Shahar previous answers:
function custom_file_exists($file_path=''){
$file_exists=false;
//clear cached results
//clearstatcache();
//trim path
$file_dir=trim(dirname($file_path));
//normalize path separator
$file_dir=str_replace('/',DIRECTORY_SEPARATOR,$file_dir).DIRECTORY_SEPARATOR;
//trim file name
$file_name=trim(basename($file_path));
//rebuild path
$file_path=$file_dir."{$file_name}";
//If you simply want to check that some file (not directory) exists,
//and concerned about performance, try is_file() instead.
//It seems like is_file() is almost 2x faster when a file exists
//and about the same when it doesn't.
$file_exists=is_file($file_path);
//$file_exists=file_exists($file_path);
return $file_exists;
}
This answer may be a bit hacky, but its been working for me -
$file = 'path/to/file.jpg';
$file = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$file;
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}else{
$exists = true;
}
apparently $_SERVER['REQUEST_SCHEME'] is a bit dicey to use with IIS 7.0 + PHP 5.3 so you could probably look for a better way to add in the protocol.
I found this answer here http://php.net/manual/en/function.file-exists.php#75064
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.
It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.
Thus:
<?PHP
// .htaccess php_value include_path '/home/user/public_html/';
// includes lies in /home/user/public_html/includes/
//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
include('includes/config.php');
}
//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
include('includes/config.php');
}
?>
Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.
In my case, the problem was a misconception of how file_exists() behaves with symbolic links and .. ("dotdot" or double period) parent dir references. In that regard, it differs from functions like require, include or even mkdir().
Given this directory structure:
/home/me/work/example/
www/
/var/www/example.local/
tmp/
public_html -> /home/me/work/example/www/
file_exists('/var/www/example.local/public_html/../tmp/'); would return FALSE even though the subdir exists as we see, because the function traversed up into /home/me/work/example/ which does not have that subdir.
For this reason, I have created this function:
/**
* Resolve any ".." ("dotdots" or double periods) in a given path.
*
* This is especially useful for avoiding the confusing behavior `file_exists()`
* shows with symbolic links.
*
* #param string $path
*
* #return string
*/
function resolve_dotdots( string $path ) {
if (empty($path)) {
return $path;
}
$source = array_reverse(explode(DIRECTORY_SEPARATOR, $path));
$balance = 0;
$parts = array();
// going backwards through the path, keep track of the dotdots and "work
// them off" by skipping a part. Only take over the respective part if the
// balance is at zero.
foreach ($source as $part) {
if ($part === '..') {
$balance++;
} else if ($balance > 0) {
$balance--;
} else {
array_push($parts, $part);
}
}
// special case: path begins with too many dotdots, references "outside
// knowledge".
if ($balance > 0) {
for ($i = 0; $i < $balance; $i++) {
array_push($parts, '..');
}
}
$parts = array_reverse($parts);
return implode(DIRECTORY_SEPARATOR, $parts);
}
I just encountered this same problem and I solved it in a mysterious way. After inserting a a filepath I copied from Windows File explorer. file_exists() keeps returning false continuously, but if I copy same path from VSCode editor it works perfectly.
After dumping variables with var_dump($path); I noticed something mysterious.
For path I copied from file explorer it shows length 94.
For path I copied from VSCode Editor it shows length 88.
Both path look same length on my code Editor.
My suggestion: if string contain hidden characters, it may fail and not work.

Categories