How do I stop user being able to see website code - php

the dilemma I have is my website index.php calls to a template php file on a button press like this:
case 'main':
$page = getTemplate('main.php', array('user'=>$user));
echo $page;
break;
This main.php template file is in a folder in "/var/www/template/" How do I stop people going to: domain.com/template/main.php and viewing the code for that page. I think the solution would be to make the localhost be able to pull the it and display it rather than the user or something along those lines. Any help would be appreciated thank you.

Like a comment said, the PHP file will not be printed, it will print the HTML result that the php file produce.
Maybe it produces some errors indicating vulnerabilities to a potential attacker ? If that's your case, you should handle this directly into the php code or use a .htaccess at the root of your site. You can't find some help there.
How to deny access to a file in .htaccess

Managed to fix this by putting this at the top of the php page I wanted to render:
<?php
if (!isset($_GET['page'])) {
header('Location: /main');
exit();
}
?>
This means if someone goes "domain.com/template/main.php" to attempt to view the source code, it will redirect them back to the main webpage for my site. Thanks for your suggestions however.

Related

Got 404 when redirect every url to index

So, I've been trying to do the Wikipedia url thing! Like making the url readable. Tried every .htaccess code out thire and contacted the Hostinger customer services to help, and nothing works! I don't know why.
So, i move to use the PHP, and i got work great on test.php page that i use the test on, but when i move the code to index.php it doesn't.
So, the why i did it is having a page with php simple code: if url[2] has s include s.php, else include x.php. and it works great when i go to www.website.com/test.php/s it will open s.php
However, when after i move the code to index.php and then i go to website.com/s i got an error as this page is not in the srver, but if i go to website.com/index.php/s it works.
So what do think i could fix it with? Or if there is any other why to do it. Thanks in advance ☺

Include PHP file with condition opened but closed in another included PHP file

I would like to include at the beginning of my script a PHP file that open a IF condition. Then i write my script, and to finish I include another PHP file that close the conditon.
This bring me to a "Parse error: syntax error, unexpected end of file in ..." error.
This will be better to understand with this simple example :
header.php
if(aConditionalTest()) {
footer.php
} // endIf
mypage.php
include_once 'header.php';
echo 'my awesome content';
include_once 'footer.php';
FYI: I would like to do this for example :
to check everywhere that a user is authorized before displaying the content
implement a webpage caching system (see http://www.phpfastcache.com/ in "Example" section, "Caching Whole Webpage")
THANKS!
edit : Explain more precisely WHY I want to do this for using phpfastcache :
http://www.phpfastcache.com/ says :
Caching Whole Webpage PHP Cache whole web page :
You can use phpFastCache to cache the whole webpage easy too. This is simple
example, but in real code, you should split it to 2 files:
cache_start.php and cache_end.php. The cache_start.php will store the
beginning code until ob_start(); and the cache_end.php will start from
GET HTML WEBPAGE. Then, your index.php will include cache_start.php on
beginning and cache_end.php at the end of file.
That's just what I try to do!
According to their piece of code below, this brings to the situation where the condition is opened in "cache_start.php" and then closed in "cache_end.php"
cache_start.php
use phpFastCache\CacheManager;
$cache = CacheManager::Memcached();
$keyword_webpage = md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
// try to get from Cache first.
$resultsItem = $cache->getItem($keyword_webpage)
if(!$resultsItem->isHit()) {
ob_start();
cache_end.php
// GET HTML WEBPAGE
$html = ob_get_contents();
$resultsItem->set($html)->expireAfter(1800);
$cache->save($resultsItem);
}
echo $resultsItem->get();
mypage.php
include_once 'cache_start.php';
// my awesome content to cache goes here...
include_once 'cache_end.php';
myotherpage.php
include_once 'cache_start.php';
// my other great content to cache goes here...
include_once 'cache_end.php';
So the reason WHY I want to put the phpfastcache code in 2 separate files is that I have many different PHP pages to cache, so I would like to avoir repeating all this code on each page...
Hope this edit will help you better understand why I would do that, even if I understood, as I feared, that is is not possible.
Give it a try:
how can I achieve this ?
Do it the evil way and eval all instead of including :) Like
eval(file_get_contents('header.php').'<?php echo "my awesome content";?>'.file_get_contents('footer.php'));
That can be a solution, if you want to join the dark side :)
SideNote: In this solution, you have to keep an eye on global variables!!
But please, thing about the fact, that you want to spread conditions over seperate files, what in my opinion is very very very bad practise.
Did i really answer this 8]
I try it in other way.
Only rule: works only in global space (where else :-))
So you want to open an if() in cache_start.php and close it cache_end.php. (for ob_cache reasons)
But if the condition isn't changed why not doing the condition twice!
In each file test for if(condition)!
Or set up an variabale like $cach_op_started=true and test for it in the second if() in cache_end.php
Thing boths should work for you.
Its a little funny that i didnt see that solution at the first time :)
Last Note:
You can also use auto prepend and append files in PHP if you want to.
That can be configurated in php.ini.
The files will automaticly loaded before and after an script, always.
http://www.webdevsecrets.com/using-phps-auto_prepend_file-and-auto_append_file/
Have a nice time.
So I understand that the problem is that when you don't want a certain user to see the contents of a page, the rest of the page isn't loaded and that is whats causing the error?
If so, why don't you just always include the files and in the specific page you set the conditions for who can view what?
I use ob_start() in my header, and ob_end_flush in my footer which works great.
and then check with my SESSION variables on the specific page's content if the logged in user has the right to see the content, else display a message like:"You are not authorized to see this content"

Fix a redirect loop?

I have the following code in my index.php page:
<?php include("/includes/widgets.php") ?>
And in my widgets.php page:
<?php
header("Location: /");
?>
What I want to achieve with this is to redirect it if the user visits it, but allow it for including.
But I get the following error:
The webpage has a redirect loop
How can I fix/prevent the redirect loop, but still redirect the user and not the server.
Place the widgets.php file in a folder not accessible to HTTP clients. I.e on apache webserver, either put it above your document root (into it's parent) or use .htaccess file to block users from it.
e.g.
deny from all
I think I know what you need :)
Change code index file to next
define("IS_INDEX", true);
include("/includes/widgets.php"
Change code for widgets.php to next
if (!defined("IS_INDEX")) {
header("Location: /");
exit();
}
The issue is you are redirecting back to the same page, which then redirect again, and again, and again.
An easy fix would be to wrap the redirect in an if, and only redirect if they aren't already on the index page; but this is just patching what looks like an architectural problem.
Something like:
if (ltrim($_SERVER['REQUEST_URI'], '/') != 'index.php')
header('Location: index.php');
One way is to check if __FILE__, which is the file loaded, regardless of included or not matches up with the file requested which is in $_SERVER['REQUEST_URI'] (or $_SERVER['PHP_SELF']).
I use this on our development site in a page that is usually included to get the output as debugging.
if(basename($_SERVER['PHP_SELF'])===basename(__FILE__)){
//do some debugging
}
Typically you wouldn't use basename, but this is on a non-public facing development site and the file has a pretty unique name so I'm not worried about the file being included with another file with the same name or anything.
One possible way is to add a parameter to the redirection, e.g.
if (!$_REQUEST['redirect'])
header("Location: /ìndex.php?redirect=1");
That way redirection can happen only once.
Another way is to stop redirection if the user already is on the /. I´d suggest to combine both.

Get Page URL In Order To Use It To Include

So I made a script so that I can just use includes to get my header, pages, and then footer. And if a file doesnt exist a 404. That all works. Now my issue is how I'm supposed to get the end of the url being the page. For example,
I want to make it so that when someone goes to example.com/home/test, it will automatically just include test.php for example.
Moral of the story. How to some how get the page name. And then use it to "mask" the end of the page so that I don't need to have every URL being something.com/home/?p=home
Heres my code so far.
<?php
include($_SERVER['DOCUMENT_ROOT'].'/home/lib/php/_dc.php');
include($_SERVER['DOCUMENT_ROOT'].'/home/lib/php/_home_fns.php');
$script = $_SERVER['SCRIPT_NAME']; //This returns /home/index.php for example =/
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/home/default/header.php');
if($_GET["p"] == 'home' || !isset($_GET["p"])) {
include($_SERVER['DOCUMENT_ROOT'].'/home/pages/home.php');
} else if(file_exists($_SERVER['DOCUMENT_ROOT'].'/home/pages/'.$_GET["p"].'.php')) {
include($_SERVER['DOCUMENT_ROOT'].'/home/pages/'.$_GET["p"].'.php');
} else {
include($_SERVER['DOCUMENT_ROOT'].'/home/default/404.php');
}
include($_SERVER['DOCUMENT_ROOT'].'/home/default/footer.php');
?>
PHP by itself wouldn't be the best choice here unless you want your website littered with empty "redirect" PHP files. I would recommend looking into the Apache server's mod_rewrite module. Here are a couple of guides to get you started. Hope this helps!
The simplest way would be to have an index.php file inside the /home/whatever folder. Then use something like $_SERVER['PHP_SELF'] and extract the name if you want to automate it, or since you are already writing the file yourself, hardcode it into it.
That however looks plain wrong, you should probably look into mod-rewrite if you are up to creating a more complex/serious app.
I would also recommend cakePHP framework that has the whole path-to-controller thing worked out.

Diplay page directly with php

What is the best way to "NOT" display a page directly in php?
Edit
There is a page = register.php
a user cant open register.php directly. Only can access from index.php > Register.php
Thanks
Any PHP files containing sensitive data, such as database password, should be stored outside of the document root and included where needed. That way, if an admin makes a serious mistake and the web server starts sending PHP unparsed, that data will be inaccessible.
Edit
You edited your question and it now seems you wish to prevent access to page without them coming from a particular page. You should be able to get some ideas from these questions:
deny direct access to a php file by typing the link in the url
preventing direct access to a php page, only access if redirected
I think you want something like this:
if ( $_SERVER['HTTP_REFERER'] != 'http://YOUR_SITE/index.php' ) {
echo "Can't access this page from this referer";
die();
}
// go on with your register.php code
You can put
die();
or
exit();
At the top of your PHP document. However, your question is unclear as to what you wish to accomplish.
You can start a session in index.php and check for a certain variable from that session in the other pages.
make a file index.php
in it put
<?php
include 'register235235235235.php';
?>
make a file register235235235235.php
put whatever you want in there
As far as securing php includes, I only secure my database.php files which contain usernames and passwords.

Categories