Custom directory viewer (php) - php

I started a little project a few days ago, a directory viewer. (Not a redesigned htaccess thing.)
It's written in PHP and works great except for a few little things.
I have one file (masterfile) where all parts of the viewer (css, php, ..) come together and build the final viewer. Whenever you access a directory without an index.php, index.html, etc. in it, you should end up in this masterfile and see your directory (-content).
Example: example.com/css/ => You're in css dir => Show custom dir viewer (css folder)
Idea: Disable .htaccess indexing which produces an 403 error, redirect this error to masterfile.
Options -Indexes
ErrorDocument 403 /masterfile.php
This does work, however it lists the content of the masterfile directory and not the content from original folder (example: /css/) Ideas?
Possible solution (I don't like): Put a file, that includes this "masterfile", in EVERY directory and name it index.php
I hope you guys have some ideas, I appreciate any help!

You can put something like this at the top of masterfile.php:
$parsed = parse_url($_SERVER['REQUEST_URI']);
$files = scandir($_SERVER['DOCUMENT_ROOT'].$parsed['path']);
maybe with some adjustment depending of your server configuration. The parse_url stuff is to remove eventual GET and/or segments.

Related

How to remove "wp-content/uploads/2019/10" from media file URL?

For a current project, I am supposed to remove "/uploads/2019/10" from specific media file URLs. For instance, I need this, "https://www.mywebsite.com/wp-content/uploads/2019/10/myAwesomedoc.pdf", to be "https://www.mywebsite.com/myAwesomedoc.pdf". How can I accomplish this?
BACKGROUND: This needs to be done only for PDFs on the site. So far, I've tried redirects, through plugins (Pretty Link) and via .htaccess file per the direction of a peer but this didn't work because redirects don't change the actual "home" URL.
I've read elsewhere that in wp-config.php that I can insert code like define( 'UPLOADS', 'files' ); but this would affect all files, not to mention I would need to relocate all PDFs to this new folder called "files".
Lastly, I'm aware that under Settings>Media , I can disable the uploads folder from sorting in YYYY/MM format.
Here are an example of what I produced in .htaccess for redirects
# New redirects
redirect 307 /wp-content/uploads/2019/10/myAwesomedoc.pdf /myAwesomedoc.pdf
This wasn't fruitful as, unlike redirect plugins, this made the file system look for a file called "myAwesomedoc.pdf" in the root file, which of course didn't exist.
After the "redirect link" method wasn't satisfactory, I attempted to go the "wp-config.php" route and with what I found, I wasn't able to find a way to only change the various paths a PDF file may have on this website [e.g., "https://www.mywebsite.com/wp-content/uploads/2019/10/myAwesomedoc.pdf", "https://www.mywebsite.com/projects/assignments/myAwesomedoc.pdf", "https://www.mywebsite.com/products/documents/myAwesomedoc.pdf"].
I appreciate any help I may get on this.
I guess you got confused between Redirection and Url rewriting!
There is a possible way of doing that with .Htaccess by matching pdf extensions with regex and pointing them to the real path in media directory.
But some anomalies would happen cause of different dates patterns used by wordpress!
I think Redirection wouldn't solve the issue unless files are already moved to root directory.
How about you write your own plugin for this feature?
Would this feature be shared with other users (editors, contributors...)?
For PDF files you don't any media processing functionalities (resizing...)
So The plugin would:
- upload files "Safely" to root folder.
- List only pdf files
It depends on how you are publishing those PDFs.. If they are meant for download only then you just share their links.
Otherwise with a viewer or extra information , you could define a custom post type for those docs and use custom fields...
Then you redirect old files urls to new location.

Use predefined index if none detected?

I made an auto file indexer in PHP. I have to put the "index.php" file (my file indexer) in each of the folders so I can see the files in the current folder, which is cool.
Sadly, im able to see the file "index.php" in the list, a thing that I dont want to see.
I used the following to exclude the "index.php" file from the array of shown files:
$files = array_diff($files, ["index.php", "RESSOURCES"]);
(whoops, I lied. It also excludes the "RESSOURCES" folder.)
Sadly, the fact that I have to put the "index.php" in all of the folders is quite limiting. Its becoming a real problem since I have about a hundred folders and subfolders on there...
So my question is:
What can I put inside my .htaccess file so it solves my problem (im using apache 2.4)
I already tried putting:
ErrorDocument 404 /Home/index.php
But it always shows the files located at /Home/ instead of the files located where the error occured.
Any tips?
Cheers.

How to execute a custom php file with a wordpress website

I have installed wordpress blog in my domain(Ex: http://mywordpresswebsite.com). Now i have a php file called serve.php in the root like http://mywordpresswebsite.com/serve.php.
Now if i open the url in browser its saying page not found.
then i have added RewriteRule ^serve.php$ serve.php [L] in htaccess code, still its saying page not found.
Please give me a solution for this as soon as possible, thanks in advance.
Wordpress templates are located in wp-content/themes/yourthemename/. Easy way to load a custom php file is to put serve.php in that folder and to make that file a page template by putting comment below at the beginning of the file:
<?php
/*
Template Name: Serve
*/
Now go to admin->pages, create a new page and assign that page template from the template dropdown. Open the http://mywordpresswebsite.com/serve/ url in browser ( click on Show Page in admin bar ) and serve.php will be loaded.
Actually, if it is just plain php code that you want to run, you can simply upload the file to some accessible location on your website and specify the web path to run it.
For example, upload serve.php to your theme directory and visit:
http://mywordpresswebsite.com/wp-content/themes/<theme_name_here>/serve.php
Of course, you need to replace <theme_name_here> with the name of the theme folder.
However, if your code in serve.php is not just plain PHP, but needs to interact with Wordpress objects, the execution will produce an error. PHP does not know anything about Wordpress. To see the error, you may want to temporary enable debugging output for your site by finding the .htaccess file in its root directory and appending to it :
php_flag display_errors on
So, in case you do need to interact with your Wordpress site, you need the hack, described by Danijel

Include php files when they are in different folders

Most of my website is in my root directory. And In that directory there is "css", "functions", "images" folder. Everything works fine when I include php files within index.php or any other root file. It includes it fine and executes it fine.
But problem occurres when I made folder "blog". So this is totally new and separate root folder with CMS and its own "root" files. And I try to include css from main root directory or some php files from "functions" folder in main root directory, Everything breaks down. I know I have to include it as ../functions/myfile.com. But this files includes some other files so it just wont work properly and won't be able to include other files properly.
Is there any idea how to fix this problem?
You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.
Site 1
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';
Includes under site one would be at:
echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';
Site 2
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';
The actual code to access includes from site1 inside of site2 you would say:
include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');
It will only use the relative path of the file executing the query if you try to access it by excluding the document root and the root slash:
//(not as fool-proof or non-platform specific)
include('../includes/file_from_site_1.php');
Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.
Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:
<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>
You should use:
<a href='/contact/'>Contact</a>
For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt file for ONLY site1:
User-agent: *
Disallow: /blog/
Other possibilities:
Look up your IP address and include this snippet of code:
function is_dev(){
//use the external IP from Google.
//If you're hosting locally it's 127.0.01 unless you've changed it.
$ip_address='xxx.xxx.xxx.xxx';
if ($_SERVER['REMOTE_ADDR']==$ip_address){
return true;
} else {
return false;
}
}
if(is_dev()){
echo $_SERVER['DOCUMENT_ROOT'];
}
Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.
If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:
if(is_dev()){
echo "<script>".PHP_EOL;
echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
echo "</script>".PHP_EOL;
}
If I understand you correctly, You have two folders, one houses your php script that you want to include into a file that is in another folder?
If this is the case, you just have to follow the trail the right way.
Let's assume your folders are set up like this:
root
includes
php_scripts
script.php
blog
content
index.php
If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:
include("../../../includes/php_scripts/script.php");
The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.
i had the same issue and found a code on https://css-tricks.com/php-include-from-root/ that fixed it
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/common/header.php";
include_once($path);
?>
None of the above answers fixed this issue for me.
I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.

using htaccess to hide database passwords

I have a php class that connects to a database which has the password to the database hard coded into it. I do NOT have have access to folders outside the webroot. Reading this forum and others it seemed that creating a htaccess file with
order allow,deny
deny from all
in the directory with my php classes would do the trick. however after doing some quick testing it seems this also blocks the public files which need access to the database to generate the site. to be clear this is the structure i want:
index.php (public file which calls on php classes that access the database)
php_classes/DatabaseConnect.php (contains the password to the database. i want to hide this from everything that is not uploaded onto mysite --- or better yet only to specific files i name)
...
thanks,
brook
Do not place your PHP code in the webroot. Frameworks will typically use this technique where they only put a bootstrap file in the webroot...you can do that same and place your PHP file with sensitve information above your web root so it cannot be browsed.
Your bootstrap file would #require_once '../safe_dir_above_webroot'.
If you're worried about others seeing the login details to your database, rest assure that it cannot be seen if inserted between PHP tags.
.htaccess is a little tricky with some servers. It seems quite a few setups hate overruling which I can understand.
Since you have suggested that you cannot access folders outside of the root directory, you may just want to do something like this.
define("include_allowed", true);
Call that in the leading file, for instance index.php. When a file is included it should check to see if include_allowed has been set true.
if (include_allowed != true) header('HTTP/1.1 404 Not Found');
This checks to see if it has been included by index.php or which ever file that has defined include_allowed true.
If it fails to return true, a 404 error is sent saying not found to trick users! :)
Since your file is PHP , it will processed by the PHP exe, before being rendered to the client. So the password should not be visible. Having said that to use htaccess to stop view a particular file you can do this
<Files php_classes/DatabaseConnect.php>
Deny From All
</Files>

Categories