Forcing file-creation in public directory? - php

Here's an idea. I'm trying to create file from PHP script. File may be created in any public place on server (in public root or in its subdirectories). Bottom of line, I want to write function like this (it must work on both unix and windows servers).
function create_file($path, $filename, $content, $overwrite=false) {
# body
...
}
Parameters:
$path - file-path (empty or ends with /)
$filename - any valid file-name (requires dot+extension)
$content - file-content (anything)
$overwrite - if set true, existing file will be overwritten (default. false).
Result:
Function returns TRUE and creates file with content, or FALSE if file-creation was not possible for any reason.
Description of problem:
I expect this function to return true and create file $filename on path $path, or false if it wasn't possible for any reason. Also if file was successfully opened for writing, need to put $content in it.
Argument $path is relative path to public directory, and $filename is any valid filename. Of course, I want to avoid creating files if path points outside of public directory. Function may be called from subdirectory-scripts like this example
# php script: /scripts/test.php
create_file('../data/', 'test.info', 'some contents');
# result file: /data/test.info
What have I tried so far?
I’ve tried doing this with fopen() and fwrite() functions and that works on some servers, and doesn’t work on some. I guess there’s problem with writing privileges and chmod() but to be honest I’m not very familiar with chmod attributes. Also I couldn't check if $path points outside of server's public directory.
In short, I want this function to create file and return TRUE if file doesn't exist, or file exists and $owerwrite=true. Otherwise, nothing happens and function returns FALSE.
Additionally, I would like to know reason why file can't be created on some path (just in theory). Incorrect path/filename is only thing I have on my mind and I'm sure there's more about this problem.
Thanks in advance for any sample/example/suggestion.
update code
So far I have this code...
function create_file($path, $filename, $content, $overwrite=false) {
$reldir = explode('/', trim(str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])), '/'));
$dirdepth = sizeof($reldir);
$rpadd = $dirdepth > 0 ? '(\.\./){0,' . $dirdepth . '}' : '';
$ptpath = '#^/?' . $rpadd . '([a-z0-9]\w*/)*$#i';
$ptname = '/^[a-z]\w*\.[a-z0-9]+$/i';
if ($res = preg_match($ptpath, $path) && preg_match($ptname, $filename)) {
$res = false;
if ($overwrite === true || !file_exists($path.$filename)) {
if ($f = #fopen($path.$filename, 'w')) {
fwrite($f, $content);
fclose($f);
$res = true;
}
}
}
return $res;
}

Some suggestions:
set the owner of the web server document root: chown -R apache:apache /var/www (i suppose /var/www is your document root and that the web server apache runs with user apache). Set the privilegies of the document root like this in order to have all directories under document look with privilegies 755 (only owner which is user apache can write in folders /var/www and sub folders)
Block paths that point out of your /var/www document root: you are under the issue known as http://en.wikipedia.org/wiki/Directory_traversal_attack. What about if the $path is something like: /var/www/../../../etc/passwd?
Basename php function can help you identifying this kind of malignous paths. Look this post: php directory traversal issue
To check wheter a file already exists or not: http://php.net/manual/en/function.file-exists.php

All file functions in php will not work properly in two circumstances
If you don't have enough user privileges for applications, then
You may not used/passed the arguements/parameters correctly .

Related

"No such file or directory" on localhost copy

EDIT: I'm pretty sure the issue has to do with the firewall, which I can't access. Marking Canis' answer as correct and I will figure something else out, possibly wget or just manually scraping the files and hoping no major updates are needed.
EDIT: Here's the latest version of the builder and here's the output. The build directory has the proper structure and most of the files, but only their name and extension - no data inside them.
I am coding a php script that searches the local directory for files, then scrapes my localhost (xampp) for the same files to copy into a build folder (the goal is to build php on the localhost and then put it on a server as html).
Unfortunately I am getting the error: Warning: copy(https:\\localhost\intranet\builder.php): failed to open stream: No such file or directory in C:\xampp\htdocs\intranet\builder.php on line 73.
That's one example - every file in the local directory is spitting the same error back. The source addresses are correct (I can get to the file on localhost from the address in the error log) and the local directory is properly constructed - just moving the files into it doesn't work. The full code is here, the most relevant section is:
// output build files
foreach($paths as $path)
{
echo "<br>";
$path = str_replace($localroot, "", $path);
$source = $hosted . $path;
$dest = $localbuild . $path;
if (is_dir_path($dest))
{
mkdir($dest, 0755, true);
echo "Make folder $source at $dest. <br>";
}
else
{
copy($source, $dest);
echo "Copy $source to $dest. <br>";
}
}
You are trying to use URLs to travers local filesystem directories. URLs are only for webserver to understand web requests.
You will have more luck if you change this:
copy(https:\\localhost\intranet\builder.php)
to this:
copy(C:\xampp\htdocs\intranet\builder.php)
EDIT
Based on your additional info in the comments I understand that you need to generate static HTML-files for hosting on a static only webserver. This is not an issue of copying files really. It's accessing the HMTL that the script generates when run through a webserver.
You can do this in a few different ways actually. I'm not sure exactly how the generator script works, but it seems like that script is trying to copy the supposed output from loads of PHP-files.
To get the generated content from a PHP-file you can either use the command line php command to execute the script like so c:\some\path>php some_php_file.php > my_html_file.html, or use the power of the webserver to do it for you:
<?php
$hosted = "https://localhost/intranet/"; <--- UPDATED
foreach($paths as $path)
{
echo "<br>";
$path = str_replace($localroot, "", $path);
$path = str_replace("\\","/",$path); <--- ADDED
$source = $hosted . $path;
$dest = $localbuild . $path;
if (is_dir_path($dest))
{
mkdir($dest, 0755, true);
echo "Make folder $source at $dest. <br>";
}
else
{
$content = file_get_contents(urlencode($source));
file_put_contents(str_replace(".php", ".html", $dest), $content);
echo "Copy $source to $dest. <br>";
}
}
In the code above I use file_get_contents() to read the html from the URL you are using https://..., which in this case, unlike with copy(), will call up the webserver, triggering the PHP engine to produce the output.
Then I write the pure HTML to a file in the $dest folder, replacing the .php with .htmlin the filename.
EDIT
Added and revised the code a bit above.

PHP is_dir defective

Strange behaviour, exentially:
(the name of the folder depends on the date - the purpose is a hit counter of the website, broken down by day)
if (!is_dir($folder)) { // first access in the day
mkdir($folder);
}
Well: on the server in internet all works well.
But when i try in local, with the server simulator of Easy PHP, happens that:
(a) The first time, no problem. The folder doesn't exists and it is created.
(b) subsequently, for example to a page refresh, the program flow again goes in the IF (!!!) generating the error (at line of mkdir) of kind: "Warning: mkdir(): No such file or directory in [...]".
All parent part of the directory $folder exists.
Thanks
.
Try using a recursive directory creation function:
function mkdir_r($dirName, $rights = 0777)
{
$dirs = explode(DIRECTORY_SEPARATOR , $dirName);
$dir = '';
if (strpos($dirs[count($dirs) - 1], '.')) {
array_pop($dirs);
}
foreach ($dirs as $part) {
$dir .= $part . DIRECTORY_SEPARATOR ;
if (!is_dir($dir) && strlen($dir) > 0) {
mkdir($dir, $rights);
}
}
}
This way all directories up to the directry you wanted to create are created if they don't exist.
mkdir doesn't work recursively unfortunately.
If anyone faces the issue; Use the native clearstatcache() function after you delete the file.
I'm quoting the interesting part of the original documentation
You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return false until you create the file. If you create the file, it will return true even if you then delete the file. However unlink() clears the cache automatically.
For further information here is the documentation page: https://www.php.net/manual/en/function.clearstatcache.php

fopen(); "Remote host file access not accepted" on a local file?

I am using the Tcpdf module and PHP to create dymanic PDF invoices from an ordering system.
The script should then save the invoice into a folder called "invoices". The folder exists, and there are full permissions for "everyone" (Windows).
The code I am using is this:
$pdf->Output('invoices/Delivery Note.pdf', 'F');
This uses fopen to save the file.
However the error I am getting is: Warning: fopen(): remote host file access not supported, file://invoices/Delivery Note.pdf
This is a local file, not a remote one.
I attempted adding a / prefix like this:
$pdf->Output('/invoices/Delivery Note.pdf', 'F');
but then I get this error instead: Warning: fopen(file:///invoices/Delivery Note.pdf): failed to open stream: No such file or directory
I created the file, and left it empty, but the same error as above.
Does anyone know why I am getting this error?
From php-Script you can use:
$pdf->Output(__DIR__ . '/invoices/Delivery Note.pdf', 'F');
After upgrading to the tcpdf 6.2.6 in vtiger 6.2 I've had the same problem, sending e-mail with pdf.
So I have changed the file:
libraries/tcpdf/include/tcpdf_static.php
I have commented the code in fopenLocal() and changed the line
fopen($_SERVER['DOCUMENT_ROOT'].$filename, $mode);
see:
/**
* Wrapper to use fopen only with local files
* #param filename (string) Name of the file to open
* #param $mode (string)
* #return Returns a file pointer resource on success, or FALSE on error.
* #public static
*/
public static function fopenLocal($filename, $mode) {
// if (strpos($filename, '://') === false) {
// $filename = 'file://'.$filename;
// } elseif (strpos($filename, 'file://') !== 0) {
// return false;
// }
return fopen($_SERVER['DOCUMENT_ROOT'].$filename, $mode);
}
After changing this, it worked.
similar to user1007017, but just comment the line like shown below (tcpdf 6.2.11)
public static function fopenLocal($filename, $mode) {
if (strpos($filename, '://') === false) {
//$filename = 'file://'.$filename;
} elseif (stream_is_local($filename) !== true) {
return false;
}
return fopen($filename, $mode);
}
I suggest using the following as Gerd has also suggested but make sure you use an absolute path:
$pdf->Output(__DIR__ . '/invoices/Delivery Note.pdf', 'F');
The path must be an absolute path & not a relative path. This PHP bug report explains why: https://bugs.php.net/bug.php?id=28820
The reason relative paths are not supported with the file:// wrapper comes down to a compromise in how UNC paths are dealt with (and more specifically how / are fuzzily interpreted as \ for windows installations).
For Example:
file://foo/bar
Could be interpreted as a relative URI: foo/bar from the current working directory, OR it could be interpreted as a UNC: \foo\bar (share bar on computer foo).
For this and a few internal reasons the file:// wrapper is limited to absolute paths when called explicitly. For relative paths either use realpath() {as you did in your report}, or omit the explicit naming of the file wrapper.
You can then avoid modifying the TCPDF code and worrying about any upgrades replacing your modified code.
I found the issue was that the path for fopen has to be from the document root, and not from the PHP script location.
C:\Website\www\script\invoice\invoice.pdf
For example if the PHP script is inside the "script" folder, and you want to create the pdf inside the "invoice" folder, the script needs to have "\script\invoice\invoice.pdf".
In prestashop you can do it in this way $pdf->Output(_PS_ROOT_DIR_.'/modules/xxx/ticket.pdf', 'F');
try this
$pdf->Output($_SERVER['DOCUMENT_ROOT'].'/invoices/Delivery Note.pdf', 'F');

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.

How to check if a file has access denied and how to give rights(777) to a file in php?

I am working in php on ubuntu. When I use any image on web page which has denied access, there is warning on page. I want to check it before displaying and if it does not have rights to open then give it access to open. As we do in terminal command.
chmod 777 myimage.jpg
How to check this and give full access to a file in php.
Thanks
Check the function is_readable() and is_writable().
Example:
$filename = '/home/myuser/example.txt';
if (is_readable($filename) && is_writable($filename))
{
echo "File has read and write permissions.";
}
Use is_readable() to check whether or not the file is readable by the PHP process.
Use chmod() to change the permissions of the file.
Also, you can use is_writable() to test if you can write to the file, and file_exists() to check to see if the file even exists.
One thing you can do is use the fileowner function (and posix_getpwuid) and compare to whatever your PHP user is (often www-data).
If the users are the same you will be able to change permissions if you need to. But first check if the file is writeable anyway.
UPDATE: the chmod and chown functions return TRUE on success and FALSE on failure, so it would be a good idea to put them in an if clause. You can suppress the error output by setting error_reporting(0); at the beginning of the script, or using the # symbol like this:
if ( #chmod($filename, 0666) ) {
// do whatever with file
}
else if ( #chown($filename, 1000) ) {
chmod($filename, 0666);
// do whatever with file
}
else {
// can't change permissions
}
Doing this on the fly from PHP every time a file is referenced is a very inefficient way to manage your files. It also requires all file access to be mediated via a PHP script. Also, allowing content to be world writeable is rather messy from a security point of view.
I'd go with running an admin script once to tidy up the permissions for your existing files, then fixing the problem when new files enter the system.
Sure, if you've not got shell access / shell access as someone other than the webserver uid, then you'll have to implement this using PHP (and therefore readdir/is_readable/is_writeable).
Without knowing how files appear on your webserver its hard to recommend a specific solution.
C.
One thing you can do to make the file readable / writable is to call this function upon file / folder creation without the second argument:
function AutoChmod($path, $chmod = null)
{
if (file_exists($path) === true)
{
if (is_null($chmod) === true)
{
$chmod = (is_file($path) === true) ? 644 : 755;
if (in_array(get_current_user(), array('apache', 'httpd', 'nobody', 'system', 'webdaemon', 'www', 'www-data')) === true)
{
$chmod += 22;
}
}
return chmod($path, octdec(intval($chmod)));
}
return false;
}
Example:
AutoChmod('/path/to/file/you/just/created.txt');
This function will give appropriate permission whether you are working with SuPHP / SuExecPHP or not.
To check permissions you just need to use the functions is_readable() and is_writable().

Categories