Redirect included files - php

I have this file which stores my db info
<?php
$DBServer = 'this';
$DBUser = 'is';
$DBPass = 'my';
$DBName = 'secret';
?>
And it is included where I need it to connect to the db. My question is, how can I prevent users from going to mywebsite/db_info.php ? I know it displays a blank to them and they don't have access to the info, but I'd like to redirect them to the index page. The problem comes when this file being included in another one, it will always redirect to the index page when used(when I will connect to the db).

With apache, You can put your file in a separate folder within a .htaccess file with this content:
Order deny,allow
Deny from all
So you will have:
/yourPrivateFolder/.htacces
/yourPrivateFolder/db_info.php
This will prevent external access to your file

First, what is the point to redirect a file with important information like database access? No users should have access to this file, or even his name and path.
There are some approaches you can choose, one security option it is to allocate your db_info.php file outside the public root of your domain. Exemple:
yourdomain.com = /home/user/www/
your file should be: /home/user/db_info.php (or outsite /www/ folder!)

Related

how to show the content of a wildcard subdomain?

How can I do that when a user enters to a subdomain (I'll have wildcard subdomains), he will see what in the subfolder with the same name in the main domain? For example, if user will enter to works.domain.com, I want him to see what's in www.domain.com/works.
Here is my approach:
I have created a wildcard subdomain like *.domain.com
Created some subdomain into the wildcard directory with a index.php file as I can check preferences other information about this store -> see:
Now my intention is to provide the user what they ask for in the url
This code is written in wildcard/index.php file
<?php
//Get the store name from url
$host = $_SERVER['HTTP_HOST'];
$url = explode('.', $host)[0];
//Find the store name is it available in the database
$db = new database;
$qri = $db->query("SELECT * FROM store_info WHERE store_name='$url'");
$count = mysqli_num_rows($qri);
//If it returns true then show the reuquested store data
if($count != 0){
*I want to show here the folder data that requested in the url*
}else{
echo 'Store Not found';
}
Now my question is:
Is it the right approach to do it,so how can I show the requested folder data?
You can configure NGINX in front of your PHP server to route to particular directories with the following configuration (not tested). Configuring this in NGINX would be efficient than configuring this in PHP.
server {
server_name ~^(?<sub>[a-zA-Z0-9-]+)\.domain\.com$; # will cause the sub-domain to be placed in $sub
return 301 "http://testsite.net/${sub}${uri}";
}
Source: https://serverfault.com/questions/426673/nginx-redirect-subdomain-to-sub-directory

DIfferent login (sessions) for different folders

I have a webservice which requires a login from the user and i create the standard
$_SESSION['XXX'] variables for the user.
I wanted to create a "demo" of my application so i created another folder for it.
Same code in there and everything except the database.
Problem is that when the user logs in one of those two it can access both.
So if he logs in in the demo application which will set a session variable with that
same thing he'll be able to access the "normal" application.
How can i separate those two loggins?
Should i change my session variable for the demo or is there another way to solve it
according to the folder the files are in?
Thanks
I faced the same problem. And i also solved it. For example if you are taking 2 variables which are Name and ID from both site, you just change the variable name like below:
For Site1:
$_SESSION['username_site1'] = $username;
$_SESSION['id_site1'] = $id;
And for site2:
$_SESSION['username_site2'] = $username;
$_SESSION['id_site2'] = $id;
In this way two site will have two different session names and will never let you get into each other.
Let me know if it worked for you also.
regards.
Use different paths for the session cookie in the 2 applications.
Obviously you can't have the 2 settings in one php.ini file hence:
set the php_admin_value in a locationMatch directive in the httpd.conf (apache)
set the php_admin value in a .htaccess file
add a prepend to the PHP scripts (or amend a common include file) to set the path.
Note that if you're specifying the path in code, then session_set_cookie_params() is recommnded over ini_set(). Assuming the default config in php.ini is for the demo site (which should be using something like '/demo/' NOT '/')...
if (false===strpos($_SERVER['REQUEST_URI'], 'demo') {
// using live application
session_set_cookie_params (1200, '/live/');
}
(the above must be run before calling session_start())
You can change the path to which the session data is saved...
N.B. Ensure the folder exists and is writable by the webserver user (e.g. nobody)
<?php
$newPath = '/tmp/sessions/demo';
ini_set('session.save_path',$newPath);
?>

Storing database credentials — Best Practice for PDO

I’m looking for a best-practice on storing database credentials for use with PDO.
My DB is stored on GoDaddy, and has a couple of hundred users (maybe).
I recently converted from using mysql_* to PDO and after much Googling for an answer I’ve come to the conclusion that no clear, concise method exists.
Currently I use a config.inc file that stores the credentials as;
<?php
$strHostName = “10.10.10.10”;
$strDbName = “dbname”;
$strUserName = “dbuser”;
$strPassword = “xxx***xxx”;
?>
I do the following in my code;
<?
….stufff
require_once(‘config.inc’);
$db_found = new PDO("mysql:host=$strHostName;dbname=$strDbName;charset=utf8", $strUserName, $strPassword, array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
…lots more stuff
?>
This works fine but I’m concerned about the security of the config.inc file. Is there a preferred method to do this?
Thanks…
I'm not sure how this works really as I haven't tried it, but learned about it the other day so I thought I'd share.
With GoDaddy you can point your primary domain name at a sub-directory, therefore creating a new document root before it, so to speak.
For example, create a new directory called 'application' in your root directory, upload your application's files there and point your domain there (You may need to remove the domain name first and then add it again with the specified directory). You can then include files - your database credentials for example - from before your new document root, which is now not available to the public but available to your application.
NEW STRUCTURE
DB Credentials:
/home/www/html/someSite/dbCredentials.php
Your Website (where primary domain is now pointed):
/home/www/html/someSite/application/index.php
EXAMPLE:
In dbCredentials.php add your credentials:
<?php
$strHostName = “10.10.10.10”;
$strDbName = “dbname”;
$strUserName = “dbuser”;
$strPassword = “xxx***xxx”;
?>
On your web page, include the file and use variables as normal:
<?php
require_once ('/home/www/html/someSite/dbCredentials.php');
$db_found = new PDO("mysql:host=$strHostName..........);
?>
SOURCE:
http://support.godaddy.com/help/article/4175/specifying-a-new-default-document-root-on-your-hosting-account?pc_split_value=4&countrysite=uk
If you try it, let me know how it goes.
Make sure the password is stored in a file that is either not readable, or accessible from the web.
Storing the password in a .php file is considered safe because you can not see the contents of a .php file from the web (only it's output).
You can also store the file outside of the webroot, which makes the file wholly inaccessible from the web.
Another solution is to use the native webserver ignore rules. Files that start with a . like .password are hidden on some webservers. Specifically Apache hides all files that start with .ht. These depend on webserver vendor though so be cautious.
Storing the password in config.inc runs the risk of accidentally exposing the contents when it's in a web-accessible folder.
You don't need to worry about someone gaining access to your server and reading the password from the file because you'll have bigger problems: they have access to your server :)
You could also place the password as an environment variable on your hosting server and use getenv from your php application to read the password.

.htaccess and php includ on same server using subdomain

I have been searching all day for a solution to this and searched here.
I have a central file for including functions for all sites on the server, this looks up to the database and if valid includes the file as a .inc as the sites could be on any server so has to process over a url. So I set up a subdomain to test this and everything works fine, however if someone where to look up the link in the site they can go direct and browse the .inc file.
I've tried looking up on here how to deny someone from browsing the file if they are viewing through the browser. This works, however if the website requesting/including the functions.inc are hosted on the same server then the requesting HTTP_HOST/REFFERER becomes the subdomain and the functions.inc file is exluded.
So far I had this:-
RewriteEngine on
RewriteCond %{SERVER_NAME} !^http://(www.)?subdomainchecker.mysite.co.uk/.*$ [NC]
RewriteRule .(inc)$ - [F]
See the subdomain acts like a service. And the reason I want to do this is that I want all the php functions in one place for everyone. that way I'm only maintaining one file. One bug fix etc.
Now I thought there has to be a way to check that there is a difference when using a subdomain.
However if there is a better way???
If this doesn't work maybe I could get htaccess to include (a virtual folder) to my subdomain folder so that I don't have to go over a url... but that wont work if the site gets hosted on another server?
Or... could I do a look up straight to the DB, as the user credentials only has SELECT privileges only. Could the DB contain all the functions and output them from a text field? Or have functions listings in a DB and retrieve the function when I do a database call?
Or... could I do a php XML request and return the php functions within an XML node?
I'd rather keep the functions and classes in a file than on a DB, but I am not sure how the best way to go about it is. All I want to do is keep my php functions in one place.
If anyone has any ideas?
Thanks
Andi
Ok So I answered my own question eventually like so.
Step 1) I password protected my .inc files using .htaccess in the directory that stores my include files on my webservice (subdomain). Protecting both .inc and .php
Options -Indexes
<FilesMatch "\.(inc|php|anyext)$">
AuthType Basic
AuthName "authenticate this puppy"
AuthUserFile /[servername]/[accountusernameOnServer]/.unseenfolder/public_html/[website_authentication_folder]/.htpasswd
Require valid-user
</FilesMatch>
This folder is now password protected by the encrypted .htpassword file outside my web root.
Step 2) Back in my now protected webserivce folder contains three files (one .php / two .inc files containing my functions and application file (session variables for the site)
authenticate_some_websitesite_against_my_own_DB.php
This contains the account verification process (lookup to a database on my own server), note the host is always Localhost and I am using PHP PDO for convenience (just in case you have a Postgre database or MSSQL etc)
application_for_site.inc
This contains/sets all the site session variables (user ID etc)
a file without a name called .anyext containing my global functions for all sites
Now here is the cool thing. THE PROCESS or how I got it to work.
I put my new website in a subfolder and include a file called authentication.php in my local folder in the site. I call this in the head of index.php in the site.
This file contains my webkey, usernames and passwords to my clients table in my DB which is used to verify in the file I call from my subdomain... authenticate_some_websitesite_against_my_own_DB.php
I put all these variables in a url variable which also include my username and password to my protected subdomain.
So now it looks something like this: Of course I set the variables above
$link = "authenticate_anewsite.php";
// Create Website check link criteria.
$link .= "?website=" . $_SERVER['HTTP_HOST'];
$link .= "&website_folder=$website_folder";
$link .= "&webkey=$webkey";
$link .= "&username=$username";
$link .= "&password=$password";
$link .= "&base_url=$base_url";
$link .= "&DBLangtype=$DBLangtype";
$link .= "&localDBtype=$localDBtype";
$link .= "&content_folder=$content_folder";
$link .= "&google_api=$google_api";
$link .= "&menu_folder=$menu_folder";
$link .= "&news_folder=$news_folder";
$link .= "&events_folder=$events_folder";
$link .= "&documents_folder=$documents_folder";
$link .= "&uploaded_images_folder=$uploaded_images_folder";
$link .= "&gallery_folder=$gallery_folder";
//// Do not delete required to access the link below
$PHP_AUTH_USER = "website_user"; /// Do NOT AMEND THIS
$PHP_AUTH_PW = "passw0rd"; /// Do NOT AMEND THIS
$path = "http://$PHP_AUTH_USER:$PHP_AUTH_PW#www.websitecheck.mydomain.com/"; /// Do NOT AMEND THIS LINK
$authCHK = $path . $link;
/// going to check that we connect
$handle = curl_init($authCHK);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
/// If server can't connect
if($httpCode == 401) {
//set error handler
set_error_handler("customError", E_ALL);
/* Handle 404 here. */
trigger_error("<strong style='color:red;'>Error: SERVER - $httpCode</strong> $website failed to connect to authenticate site.<br />Connection string..:\n $authCHK");
// error_function(error_level,error_message,error_file,error_line,error_context)
} else {
require_once($authCHK);
} // end if
curl_close($handle);
Now the file successfully includes the .php file from the server because the username and password to it are parsed in the url.
in the authenticate_anewsite.php I just included (actually I did a require_once) this is the bit that authenticates my website against my clients table which runs these checks:
The MySQL database username and password are stored in this file. This account has only the priveliges of select.
checks clients for existence of a webkey which I give them
check the username against the clients table
checks the password
paid = true
active = true
So the SQL looks like this:
SELECT * FROM clients where paid=1 and active=1 and webkey = '$webkey' and username = '$username' and password = '$password'
If the required checks are verified then the num of records is 1, if this is >0 then my authenticate_anewsite.php includes the other two .inc files like this (the folder username and password have already been verified in the call.
if ($count_check > 0) {
$appliation = $path . 'application_for_my_site.inc';
$appliation = file_get_contents($appliation);
echo $appliation;
$functions = $path . '.anyext';
$functions = file_get_contents($functions);
echo $functions;
} else {
// redirect to the holding page
//header('Location: $base_url/500.shtml');
}
At this point its probably ok to set a session variable to not keep checking the database every time the index.php page is called from the actual site.
OK so this actually works although a little Archaic.
The advantages of all this:
Functions and application are served from one file in a central location (one bug fix can fix all sites)
Doesn't matter if the website is hosted on my server or on another
A user cannot browse the files directly, because htaccess has password protected them
Even if a user were to browse the subdomain/webservice in the browser by putting the link together with the folder username and password the browser, it doesn't server the PHP as is server sided script. It wont be able to see my username and database password, sql, or the name of the files I'm calling in by viewing source
I have my functions in a file with no file name and an extension that I have made up this is the purpose of the .anyext (htaccess treats this the same and protects it, but because its an extension that I made up it makes it harder to guess, and generally invisible)
indexes have been switched off so general browsing is not allowed on my webservice
OK so it took me two days to come up with this solution. I hope that my idea will help save someone a lot of time!
Bless You :o)
Andi Lee Davis

Create personal page for every user, PHP

What I want to do is to create a web page for every user when they signup on my page.
For Example: www.someweb.com/username, and this will be their webpage.
I know that this can be done easily with mkdir() and other related functions, but the problem is that my root folder is not chmod 777 and I don't want to chmod 777 this root folder because of security reasons.
What is the best way to do this when a user registers on my web page.
You don't make physical directories for each user, you use URL rewriting. Take a look at this source:
HTML Source : HTML Tutorials, URL Rewriting
Most likely you don't need to create these directories in real.
Just make it virtual.
Pass a username using query string, like this:
www.someweb.com/index.php?user=username
And personalize this page according to particular username.
After that you can do some rewrite magic and make a page address like this www.someweb.com/username but all pages will remain virtual
Use mod_rewrite to make a request to /username actually be ?user=username. You can then get the appropriate user's data and display it in a template.
if you want to create personal page for each user after signup
->when a new user do the signup at ur site then create a new directory with the name of username at the location of user folder like
/user/username/
create a file under this directory with name of index by using create file function
/user/username/index
write the following code using read/write operations if ur using php
<?php
$myfile = fopen("\user\$_SESSION["username"].php", "w") or die("Unable to create file!");
$str = "<?php
\$p_username = ".$_SESSION['username'].";
include('../user-profile.php');
?>";
fwrite($myfile, $str);
fclose($myfile);
?>
this user-profile will have the functionality to retrieve the user info from the database with the help of variable $p_username. in this way an user can also visit the profile of other user

Categories