PHP template lookup by current URL - php

I am looking to use some php pages I created as a template across multiple subdomain websites. I want to change minor things across each subdomain (what database is being used and some basic settings but this is not important). I do not want to copy over all files every time I want to create a new subdomain as this will be a pain when making updates. So I want to be able to push updates to my "live" site that acts as a template for all other sites.
This is my current testing layout
I have a "live" site that looks something like this:
-dashboard
-division
-division->lookup
Each of these directories have an index.php that I want included when the appropriate url is visited.
For each subdomain website, I currently have:
-.htaccess file
-errors (includes 404.php)
Within my .htaccess file, I have the 404 page as this 404.php page and that page looks like this:
if((#include "/var/www/live".$_SERVER['REQUEST_URI']."/index.php") === false){
echo "DOES NOT EXIST";}
If the url you are trying to go to exists in "live" it includes it and it basically mirrors it.
This seems to work except for when I try a url that is more than 1 directory deep. For example, if I am trying to go to test.myurl.com/division/lookup I get Google's 404 page (This test.myurl.com page can’t be found).
I am feeling like there has to be an easier way to do this and I am doing this all wrong. Where can I look to do this better? Any tips?

This will check if the file exists and should address the depth issue
<?php
$filename = $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI'];
if (is_file($filename)) {
// file exists as requested
require_once $filename;
exit;
}
http_response_code(404); // may be unnecessary
?>
<!doctype html> ... <!-- 404 page content -->

Related

Allow only signed in users to see external html site hosted on the same server and domain (in sub folder)

I have a PHP site (site A, CakePHP 2.3) with its own login system. Then I have another "site" (it's actually an html generated ebook with its own index.html) in the same server, but on a different folder, let's call it site B.
I'm trying to allow only users that have a valid session on site A (have logged in with valid credentials) to view that ebook (access that index.html file). The main idea behind this is to prevent users from directly sharing site B's URL.
This would be easy if I could check the user's session on Site A from Site B, I could just check the $_SESSION variable, but that's not possible.
What's the simplest way to accomplish this? While not preferably, it's okay if I have to edit that index.html file from site B to add any code that could help with this.
One way I thought about was to do some javascript redirect from site A to site B that includes a POST variable, if the variable doesn't exist, then nothing is shown. This would require adding some php on that index.html on site B but I'm not sure it's the best solution, I wonder if there's something better.
Also, I have 100s of these ebooks so if it's something I can apply massively it would be much better.
EDIT:
For clarification, both sites are in the same server and have same "domain". To open site B I use a symlink from site A. For example:
Site A URL: http://example.com
Site B URL: PHP Redirect from site A to '/symlink/to/siteB/location/') which in practicality takes user to http://example.com/symlink/to/siteB/location/
Create a proxy
I would use .htaccess to redirect any url pointing to pages in the book to a custom action in the CakePHP application.
This action checks for credentials and if OK then reads from disk the actual requested file and sends it to the browser. Do not redirect back or you will cause a redirect loop!
Of course you need to create a redirect that passes the original requested page as a parameter so you know what file to read.
Granted this is not supper efficient but it works. I had to solve the exact same issue in an old project.
Notes
Make sure your .htaccess rules only intercept/redirect HTML links or else you need to pay attention to setting up proper response headers for CSS or Image files.
Example of .htaccess
This needs to be in the ROOT folder of the book
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*html)$ http://[FULL_LINK_TO_CAKE_APP]/proxy/load/$1
</IfModule>
Example of the proxy controller
namespace App\Controller;
/**
* Static content controller
*
* This controller will render a html file
*
*/
class ProxyController extends AppController
{
public function load($file=null){
if( !$file ){
return $this->response->body( "Error: no file specified" );
}
//THIS NEEDS TO RESOLVE THE FULL DISK PATH OF YOUR PROTECTED FILES
$pathToFiles = WWW_ROOT . '/subfolder/';
if( file_exists( $pathToFiles . $file )){
$this->response->body( file_get_contents( $pathToFiles.$file) );
return $this->response;
}
$this->response->body('Could not load the file: ' . $pathToFiles . $file);
return $this->response;
}
}
Security
Of course I assume you have setup the Auth component correctly in your AppController so the controller above will only execute if the user is logged in!

php move user to 404 page after typing invalid url

I'm designing a website but I know if the user enters a wrong character into my url, a not found page will open for him . and I know it can be a way to hack my website. What should I do for that? for example if the user enters a ' into my url like this:
http://example.com/article.php?id=585'
He move to a not found page which I have designed it or move to the first page or the last page he was in.
Thanks.
You have to take 2 things into consideration:
Handling non-existent files
Handling non-existent article ids
Here's how to handle each case:
1) Create an .htaccess file and place it in your website root folder:
RewriteEngine on
ErrorDocument 404 /error.php # change this to your own 404 file path
2) Open the articles.php file and add this to the top (right after checking if your ID exists)
if(!valid_id($id)) {
//if you have php 5.3- use this
header('HTTP/1.1 404 Not Found');
//if you have php 5.4+ use this
//http_response_code(404);
include('error.php'); //change this path to your own 404 file
die();
}
Obviously, valid_id() is just a function example.
You will have to create a custom 404 page. So when your website doesn't get that page, it will show your custom page.
Try this link for custom page.
By the way from id=585'(apostophe after 585), I mean you want to prevent sql injection. Right? Just sanitise the input, that is, check if id is valid for not. You can find a lot of tutorial for that, just google it.
P.S : Believe me, It would take a lot more then a 404 Page to hack your server
just use this:
Open the articles.php file and add this to the top (right after checking if your ID exists)
if(!valid_id($id)) {
header('location:error.php'); exit();//change this path to your own 404 file
}
valid_id() is just a checking function example.

PageHandler In php

I am currently working in a application like wordpress. i need a php class to handle the url request for eg : if u load the below url in browser
http://somename.com/myaboutpage/
the handler should load the file about-us.php from my theme folder
and if i use the below url
http://somename.com/action/login/
the handler should trigger the file login-action.php from my application core and return the values
how its possible..
i tried to study how elgg & wordpress handle the request. but i am unable to get the exact..
so please help me.
Note the pages i create will be dynamic so i need a page handler fully dynimic like word press permalink handler
Have you set a BASE_URL in an index.php file? if you have, you could check to see if that is set, if it isn't it means the user has somehow managed to navigate directly to your about-us.php file. So something like
if(!defined('BASE_URL'))
{
require('/*your index.php file*/');
header('Location: BASE_URL')
exit;
}

Email not sent when submitting form

I have a very strange issue with a website that I have created.
Basically, I have a site built with a "Poor Man's Router" so that when I go to site.com/contact, it finds index.php in that directory which has a few variables set and an include which grabs my site's skeleton (main structure). Inside the skeleton is where I have another include that grabs the content for the specific page, which is designated by the variable which is set in the index.php file that I had previously mentioned.
So the problem is that when I go to this contact page, I have an contact form on it which is supposed to send an email once it is submitted. Everything appears fine, but the PHP that is on the contact page's content file is never executed. So I seemed to have narrowed it down to an issue where if the content file is deeper than the directory of the skeleton file, it will not work. Let me show you how the directories are:
/
--skeleton.php
--/content
----contact.php
--/contact
----index.php
So it goes index.php -> skeleton.php -> contact.php
The PHP in contact.php is not working, unless I put it in the root directory. Why does it do this? I know that what I am doing is not the most ideal way, but that's not what I am asking for help with. I just need to know why the PHP is not being executed when the files are organized this way.
//INDEX.PHP
$content = 'contact.php';
include('../skeleton.php');
//SKELETON.PHP
include($site . 'content/' . $content);
//CONTACT.PHP
if($send_info == 1) {
// send email
} else {
// show form
}
Without seeing more code, one suggestion would be that your include files are referencing incorrect paths. Do you know that the skeleton.php and contact.php files are loading? Can you put some debugging lines in each file to echo an output message to show that the files are loading and where they get to? Can you change the include('filename') to require('filename') to see if they are actually getting included?

Can a Directory alone load specific query on a page?

On websites such as facebook and many others you see URLs such as www.facebook.com/username. How does a URL such as this actually load the users information from a MySQL database? and what is the actual file it is displaying on? I would assume there's not really a folder for each user that it is referring to. If my question doesn't make sense can you at least point me in the right direction to set something like this up through PHP?
Again, I want example.com/username to load my users profile. How does this work?
By using apache's .htaccess file to manage a RewriteEngine, all of your pages can be funneled through an index.php file. After confirming that the requested page is not actually a page that you've intended to be a default part of your web page, you can fall back on the code below, to discover a user account. If a user account is not discovered, then the likelihood is that the page being accessed is simply a 404, which you could then redirect to as a catch-all scenario
.htaccess file
RewriteEngine on
RewriteBase /
RewriteRule !\.(xml|js|ico|gif|jpg|png|css|swf|php|txt|html|otf)$ index.php
php logic to run after confirming the requested page, isn't something like a contact-us page, or any typical web page an end user would be attempting to access.
if(preg_match("/^\/(?P<username>[^\/]*)/", $_SERVER['REDIRECT_URL'], $matches)) {
$result = mysql_query("SELECT * FROM users WHERE username = '" . mysql_real_escape_string($matches['username']) . "'");
if($user_record = mysql_fetch_row($result)) {
echo "DO WHATEVER YOUR HEART CONTENTS HERE :)";
} else {
header("Location: error-404.php");
}
}
It is all loaded dynamically via the database. For example, my Facebook name is "benroux". In facebook's user table, there is going to be a unique column called, lets say, nickname. When I visit Facebook, they are parsing the path info and essentially calling a query in the form:
select * from user where nickname = "{$nickName}"
Now, this is an over simplified example, but I hope it gives you an idea of what is going on here. The key is that there are 2 types of url vars, the facebook.com/pagename.php?id=blah and the restful style path info vars facebook.com/pagename/var1/var2/
If you are looking to have example.com/benroux load my user page, you need to make your index.php (I'll use PHP) load the path info ( http://php.net/manual/en/function.pathinfo.php ) and then query the database as I have described above.
try to
print_r($_SERVER);
you will get that parameters. Then you just need to split them.
Something like
$directory = $_SERVER['REQUEST_URI'].split('/')[1];
So, put $directory into query

Categories