Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML form action using a php file outside of root directory?

I am wondering, there are a few files I have kept outside of the root directory in a different directory and I am trying to use a HTML form to post info to a php file that sits OUTSIDE the root directory

Is that possible? If so, how?

like image 433
Kalcoder Avatar asked Dec 27 '22 21:12

Kalcoder


2 Answers

Make a proxy script... something which is inside the web directory, but all it does is include the appropriate "protected" file:

DOCROOT/form_handler.php

<?php
include "../secret/form_handler.php";

DOCROOT/form.html

...
<form action="form_handler.php">
...

This is, in fact, how many sites are setup (in essence at least). It is typical to place most of your scripts outside the DOCROOT like this for in the rare case where Apache or similar does not parse your PHP (i.e. if it is misconfigured), it doesn't inadvertently send your source code.

like image 177
Chris Trahey Avatar answered Jan 12 '23 00:01

Chris Trahey


On my website, every form I start with this code:

<form action="action" method="post">
    <input type="hidden" name="i-action" value="do-whatever" />

This avoids the need for multiple proxy scripts because action.php will use the value of the hidden field to determine which php file should be called. Don't call the hidden field action if you post the form using Ajax because it can cause a conflict. Also, I have set the .htaccess file to remove the php extension, so you may need to add .php to action in your HTML code.

Here is action.php:

if (!empty($_POST['i-action']))
{
    $action = str_replace('.', '', $_POST['i-action']);
    $action = str_replace('/', '', $action);
    if (file_exists("../secret/directory/structure/$action".'.php'))
        require_once("../secret/directory/structure/$action".'.php');
}

I used str_replace to ensure hackers can't traverse to a different directory.

like image 41
Dan Bray Avatar answered Jan 11 '23 23:01

Dan Bray