How to invoke a php file that is located outside public_html - php

Im creating a website and i am very OCD when it comes to security so i heard that if you store all of your .php files outside of your public_html folder and invoke them with another .php file that is inside your public_html folder then your risk of an attack is lower. Is this true, if so how would i do this. I read something about using .htaccess but I'm not sure if that was the correct way to do it. I though i could maybe use include but im not sure how include works with parameters.

There isn't a huge amount of extra protection offered by this strategy. Mainly, it ensures that if your server is misconfigured and fails to send PHP scripts to the PHP interpreter, it doesn't allow PHP code to be sent directly down to the browser.
You don't store all your PHP scripts outside document root. You typically store only files which are not intended to be accessed publicly outisde the doc root. Store your include files outside the doc root and include them as you would any file. Store files which are are public views inside the document root, as they need to be web-accessible.
There is a design pattern known as the Front Controller pattern whereby a single index page (index.php) accepts routes and includes other files as appropriate. Numerous PHP frameworks support this out of the box.

See PHP include function: http://www.php.net/manual/en/function.include.php
However, I doubt what you're trying to do will increase security. Where did you hear that it increases security?

Related

Confused On Higher Web Root Access For Secure Login

Going to try and mess around with forms of secure login now, and the php files that connect to the database are going to be stored above the web root, public_html, so they cannot be publicly accessed.
My first question is that people are saying you cannot invoke this php file with Javascript.
That makes sense because Javascript runs client-side and could expose information, but this leaves me a bit confused on how to invoke this php file securely.
Should I have another php file below the web root that invokes the content-sensitive one above the web root?
Would this be achieved with "../../some-folder-above-web-root/some-php-above-web-root.php", and if so isn't that revealing to the location of the php file in the web root? Or doesn't it's location matter since people cannot access it (.. hackers).
All in all I really just want to know how to communicate to a script above the web root, properly and securely.
Yes, you are correct. There should be a PHP file below the web root that will access the secured PHP files above the web root. In Zend Framework, there is a single index.php file, called the bootstraper, which does many things including:
set the error display level
set the include paths
define global constants
read the configuration files
load the library classes
get the front controller
configure the database connection
determine the route, per RESTful url's, and MVC
set Exception handling
call the requested controller
I would highly suggest using an MVC framework, they are industry standard, and have pre-built functionality for many common problems including secure logins. Zend Framework implements Access Control Lists style security, though you can easily role your own. Other notable frameworks are Drupal, Yii, Codeigniter, Symphony, CakePHP, and Joomla.
Other best practices for security are:
filter all file uploads based on mimetype, NOT file extension or filetype
filter all POST and GET data, based on the database table column type and length
sanitize all SQL strings before running them
change all the default login passwords on your servers, ex: Apache, MySQL, FTP, SSH, SVN, etc.
learn how to configure php.ini, httpd.conf, etc.
disable any services, modules, and plugins, not being used in your framework, PHP, Apache, and MySQL
fuzz your code
use unit tests
learn a bit about penetration testing
you can give those files READ ONLY permission for other, something like 754 (all permissions for root, read and execute for group, read only for other) for example, then you can read its contents using for example file_get_contents and a absolute path.
A common way to do this is have a config file (with the sensible info inside) outside the public web dir, read it using a absolute path, and then use it as variables.
If you want to EXECUTE a script outside the public web path you have to give EXECUTE permission to 'other' which isn't much secure.
Also regarding your question about javascript, it ins't about security: javascript code won't be executed in the server, where the file with sensible info is, it will be executed on the client browser, so there's nothing to read there.

PHP Apache - How do I create a secure working directory, invisible to web

I have created a PHP script that takes a large html file and, using DOMDocument, chops it up into smaller files. To save on script memory and without having to use a DB, I've done this sequentially and saved them as hundreds of html files. My question is, how do I make sure these files cannot be visible to the outside world, but still retain the ability to use them as resources for future processing (piece together various files and display them on a page)?
I'm using Amazon EC2 - Centos 6/Apache.
Thank you!
Put them on a directory which isn't a subdirectory of your web root directory (i.e. the publicly opened directory).
Another possible approach (if you are using Apache), is to use an .htaccess file to Deny from all in a directory.
By far the best approach is to store them outside the document root (perhaps one level below).
Otherwise, perhaps at a future point, your settings, .htaccess file httpd.conf or other elements may change and reveal the directory contents.
Storing them outside the docroot means they will never become visible.

PHP—"Defined or Exit" at the beginning of many files?

I have been inspecting some PHP source codes and I more often than not find files starting with
defined('__someconstant__') or exit();
I know that this prevents the file to be accessed directly if a previous file defining __someconstant__, but then I wonder if this is really necessary... Isn't there (even non-PHP based) a cleaner way of doing it without introducing this extra code in every file?
Isn't there (even non-PHP based) a cleaner way of doing it without introducing this extra code in every file?
Presence of such snippets indicate bad code structuring, namely code automatically executing in global scope. You shouldn't have this or exit(); code in pure function/class includes. It would be redundant there.
Code that does perform potentially dangerous actions shoult not be web-accessible in the first place. The or exit; approach is a workaround. It should always be accompanied by a FilesMatch and Deny from All in a .htaccess file however. Best set the whole include directory inaccessible.
To avoid those (useless) lines at the top of (nearly) each file, your could:
Store a public "controller" file (like index.php in a directory called web or public on which your web server's alias or virtual host points to
Store in other directories like lib, config, apps... all the files that should not be directly accessed through the webserver by simply typing an URL.
This is typically the structure of existing frameworks such as Symfony 1.x
Additionally you can (and certainly will, for URL rewrites) put a .htaccess file, but a server misconfiguration can incidentally disable it, so keeping source files in distinct directories is IMO better.
Adding to #NullUserException's answer...
Yes there are other ways of preventing a file from being accessed directly (.htaccess being one), but for software that is shared with a wide audience, you can't really rely on those technologies being there. You can rely on a simple condition at the top of the files though.

What is an .inc and why use it?

I often see examples in PHP that include.inc files. What is the meaning of .inc? What it is used for? What are the disadvantages and advantages of using it?
It has no meaning, it is just a file extension. It is some people's convention to name files with a .inc extension if that file is designed to be included by other PHP files, but it is only convention.
It does have a possible disadvantage which is that servers normally are not configured to parse .inc files as php, so if the file sits in your web root and your server is configured in the default way, a user could view your php source code in the .inc file by visiting the URL directly.
Its only possible advantage is that it is easy to identify which files are used as includes. Although simply giving them a .php extension and placing them in an includes folder has the same effect without the disadvantage mentioned above.
If you are concerned about the file's content being served rather than its output. You can use a double extension like: file.inc.php. It then serves the same purpose of helpfulness and maintainability.
I normally have 2 php files for each page on my site:
One named welcome.php in the root folder, containing all of the HTML markup.
And another named welcome.inc.php in the inc folder, containing all PHP functions specific to the welcome.php page.
EDIT: Another benefit of using the double extention .inc.php would be that any IDE can still recognise the file as PHP code.
Generally means that its a file that needs to be included and does not make standalone script in itself.
This is a convention not a programming technique.
Although if your web server is not configured properly it could expose files with extensions like .inc.
It's just a way for the developer to be able to easily identify files which are meant to be used as includes. It's a popular convention. It does not have any special meaning to PHP, and won't change the behaviour of PHP or the script itself.
This is a convention that programmer usually use to identify different file names for include files. So that if the other developers is working on their code, he can easily identify why this file is there and what is purpose of this file by just seeing the name of the file.
Just to add. Another disadvantage would be, .inc files are not recognized by IDE thus, you could not take advantage of auto-complete or code prediction features.
In my opinion, these were used as a way to quickly find include files when developing. Really these have been made obsolete with conventions and framework designs.
Note that
You can configure Apache so that all files With .inc extension are forbidden to be retrieved by visiting URL directly.
see link:https://serverfault.com/questions/22577/how-to-deny-the-web-access-to-some-files

using includes cross domain that contain php code - failing

I have a series of web sites all hosted on the same server with different domains. I want to host some common PHP scrips and then be able to call these from the other domains.
Im am a bit fresh with my php so pls excuse code attempts - I have tried iterations of the following which may try and help you understand what I am aiming for!
from within php tags ...
include('http://www.mydomain/common_include.php?show_section=$section');
$show_section = $_GET['show_section'];
include('http://www.mydomain/common_include.php');//Then $show_section would be available to the included file/cod
Finally I have tried pulling in the include which contains a function then trying to run that include from the parent script.
I would much prefer to keep this PHP
orientated rather than getting
involved with the server (file
systems etc (but I can change
permissions etc)
I can but would prefer not to just upload the same library to each of the domains separately
I understand PHP is run on the server hence maybe problematic to include scripts across onto another server.
Thanks in advance.
#
EDIT
OK OK - I get that its bad practice so will not do it....THANKS VERY MUCH FOR THE QUICK ANSWERS.
However is there any other recommendations of how to esentially show this basic php app on all of the sites with out haveing to add the files to the root of each site? Just to prevent massive script duplication...(thinking out loud call the scripts in from a db or anyother soloutions)
Again thanks for your assistance
That would be a huge security risk if you could just include remote PHP files to your own projects. The PHP gets parsed before the server sends it to you so cross-domain includes would only contain the output the script generates. The only way to include PHP files so that they can be executed is via local filesystem.
If you look at PHP.net's documentation about include, you can find this:
If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see List of Supported Protocols/Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.
Which pretty much explains the whole thing.
The root of the original question seemed to be the poster's concern about using a PHP script or plugin on multiple sites and then having an onerous task each time it needs to be updated. While trying to include PHP files across sites is a bad idea, it is a better plan to structure your script to be as self contained as possible. Keep the entire plugin contained in one directory.... and ensure your function calls to utilize it are as well formed as possible - clean, well named functions, uniform naming conventions and a well thought out plan for what parameters each function needs. Avoid using global variables.
Ideally you should then have quite an easy time each time you need to update the plugin/script in all locations. You can even set up an automated process that will upload the new directory containing the plugin to each site replacing the old one. And the function calls within your code should rarely if ever change.
If your script is big enough you might implement an automatic update process like the more recent versions of Wordpress use. Click a button and it updates itself. In the past, updating a dozen sites running Wordpress (as an example) was a massive pain.
That is very bad practice.
Actually you're including not PHP but just HTML code.
Include files, not urls. It is possible for the same server.
Just use absolute path to these files.
Apart from the fact that it's a bad practice you should first check if include allows URLs if you really want to do that.
If however all the sites that need to use the script, you could put the script somewhere in a directory accessible by the user that executes php and add that dir to the php.ini include_path property (can also be done at runtime)
(Or you could create a php extension and load it as extension)
If you have root rights on that server, you could just use absolute path from filesystem root, but most hostings won't let you do this.

Categories