Include page depending url (php) - php

I'm looking for a php code that include php file depending the page url. (I know wordpess do something similar)
I got this stupid code, but I'm sure I'm missing something..
$url = explode('/', trim(($_SERVER['REQUEST_URI']), '/'));
if ($url[0]==urlencode ('news))
require_once 'cpt/category/news-page.php';
if ($url[0]==urlencode ('home))
require_once 'cpt/category/home-page.php';

$current_url = $_SERVER['REQUEST_URI'];
if (strpos($current_url,"my-current-url")) {
require_once 'cpt/category/news-page.php';
}else if(strpos($current_url,"my-current-url")){
require_once 'cpt/category/news-page.php';
}
Here is a short example it might help you.
I've se the url of the page as $current_url. and we do a simple IF string poses something like "your url" and if it does then it does what you need.
Hoped that it helps, pretty sure you can set it up to work for you.

The best way is to use an Front Controller Pattern. All requests go through index.php, and then you can use a routing component to parse the url for you. See http://symfony.com/doc/current/components/routing.html for a good router. It ships with Symfony, but will work independently.

You could use some things like this: yoururl.php?act=news&para=latest
if($_GET['act']=='news')
{
require_once("cpt/category/news-page.php");
}

Related

How to write a PHP redirect script

How do I create a PHP script that will redirect to a custom URL when link added in the URL. For instance, when a user visits this:
http://mydomain.com/link.php?=http://www.google.com
It should redirect them instantly to google.
Ideally, is it possible to ensure that the click itself came locally?
I am aware that this is most likely a very basic PHP code but note that my knowledge of it is very limited which is restricting me from writing it.
You can use the HTTP_REFERER of $_SERVER variable to check whether it is from the local domain.
Reference: http://php.net/manual/en/reserved.variables.server.php
For redirection, try using the below
http://mydomain.com/link.php?r=http://www.google.com
header("Location:".$_GET['r']);
Reference: http://in3.php.net/manual/en/function.header.php
I hope the following works for you, you can hard code the $domain variable as mydomain.com
$url = "http://www.php.net/index.html";
$domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));
$refDomain = str_ireplace('www.', '', parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST));
if(strcmp($domain, $refDomain) == 0)
{
//your code goes here
header("Location:".$_GET['r']);
}
http://mydomain.com/link.php?url=http://www.google.com
<?php
header("Location: {$_GET['url']}");
?>
This?
Ok, I would like to add a complete answer here.
You could use header to send a redirect header like MrSil said,
header("Location: $url"); // will redirect to $url!
If you want to prevent other people from using your redirect script, you can do something like:
$ref = $_SERVER['HTTP_REFERER'];
$host = parse_url($ref, PHP_URL_HOST);
if($host !== "mydomain.com"){
// out side request
}
But then, HTTP_REFERER can be easily spoofed. So, what would be a better check?
CSRF Protection. It might look like overkill, and it is also not the perfect way to do this stuff, but it helps.
Also, I don't think a perfect solution exists.
Read this for further info about CSRF.

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.

Php page calling

What is the best way if i want do something like these;
I call it page calling.
I have an index.php which will run the config.php
And i want to have index.php as my core then do something like
index.php?customer=home or index.php?customer=viewaccount
index.php?admin=home or index.php?admin=updateproduct
then call the particular php file eg. home.php , viewaccount.php
Best regards
I really appreciate yours help.=)
It sounds like you are talking about a design pattern known as the Front Controller Pattern.
It is certainly possible to implement your own front controller, but almost every PHP framework will have this capability already. I recommend you try Zend Framework.
I wouldn't mix admin and puclic areas in the same script.
So, for the public area you can do something like
<?
if (empty($_SERVER['QUERY_STRING'])) {
$name="index";
} else {
$name=basename($_SERVER['QUERY_STRING']);
}
$file="pages/$name.htm";
if (is_readable($file)) {
include($file);
} else {
header("HTTP/1.0 404 Not Found");
readfile("404.html");
}
?>
and then address customer pages like this index.php?home, index.php?viewaccount
Best is to check the $_GET parameter against an 'whitelist' array of allowed script names. After that, you can just include the file.
if ( in_array( $_GET['admin'], array( 'home', 'updateproduct' ) ) ) {
include( $_GET['admin'] . '.php');
}
Okay I couldn't be bothered to comment all of the answers here so I'll say it to you, even though this post will probably get put down as its not a direct help.
You need to be very careful when including files from a POST or GET request. Just be aware of Remote/Local file inclusion vulnerabilities when writing code like that. index.php?page=/etc/passwd or index.php?page=www.myEvilScript.com/evil.php
Many people can get hacked this way and you don't want that to happen to you.
Always sanitize your data, so stripslashes($_GET['admin']); or whatever method you want to use.
The name for this pattern is a front controller.
You can implement the multiplexing on the webserver (e.g. using mod_rewrite) or in your PHP code.
Here's how NOT to do it:
<?php
require_once($_REQUEST['customer']);
require_once($_REQUEST['admin']);
C.

How do I make index.php will control anything in PHP

Firstly, I don't know what to call this thing :) I want to know the key, structure and example how to achieve my goal.
Example, I don't want create separate file like register.php, login.php, about.php faq.php. Here I want the register, login about, faq ,etc will handle by index.php by example, maybe something like index.php?p=register
How do I create page something like that and what this structure called in PHP programming. Let me know.
In index.php?p=register the part after ? is called "Query String". PHP will by default parse it for you and provides the superglobal $_GET. Just try it out yourself
var_dump($_GET);
To provide a more appropriate answer using Neals code, use basename to filter out non-essential file information:
$page = isset($_GET['p'])?basename($_GET['p']):'main';
include_once "$page.php";
You could also create a "white list" to ensure that only the proper files get included:
$whiteList = array('faq', 'register', 'profile');
$page = (isset($_GET['p']) && in_array($_GET['p'], $whiteList))?basename($_GET['p']):'main';
include_once "$page.php";
Both ways should be secure, obviously, the white list will be a bit more so. This tact, depending on how you do is generally referred to as "BootStrapping" IE, one entrance page to access the rest.
UPDATE
To further the security, I would set a variable, $included would be sufficient, to add to the pages that are being included. This would prevent direct access to them (assuming that register_globals is turned off like it should be, so something like:
$whiteList = array('faq', 'register', 'profile');
$page = (isset($_GET['p']) && in_array($_GET['p'], $whiteList))?basename($_GET['p']):'main';
$included = true;
include_once "$page.php";
Then on $page.php at the top you would have something like:
<?php
if (!$included)
die('Accessing the file directly is not allowed.');
Which would prevent calls to http://yoursite.com/register.php from being allowed to dish out the file. This has it's negatives to it. Instead of putting the files you are going to be including in the webroot, I would put them outside of the webroot or in an .htaccess protected directory, which would ensure that users could not access them directly and must access them through the index.php.
I'm not sure what the whole thing is called, but if you're using index.php like that, it's called a FrontController. It's how MVC frameworks work:
/index.php?q=ctrl/action
/index.php/ctrl/action
/ctrl/action
They're all handled by/in index.php using "ctrl/action"
You want to look up php templates or even html iframe. There are several ways to do this, but some are better than others. In asp.net it's called a MasterPage. Hopefully some of these terms help you out.
If you really want to do something like this, then you can use the get field, but you need to predefine your pages, so for this request: index.php?p=my_page
<?php
$page = $_GET['p'];
$pages = array(
'my_page' => 'mypage.php',
'another_page' => 'another.php',
...
);
$include = $pages[$page];
if(!empty($include)) {
include_once($include);
} else {
echo 'No such page';
}
?>
This keeps the include completely separate from what is passed on the URL so there is no chance for risky things to get passed.

Loading CI controller in PHP on the same server

How can include CodeIgniter content in a regular PHP page on the same server but not part of the CI app?
For example I'm am trying to load a header from CI into Wordpress. Whats the best way to include a CI controller (eg; index.php/mycontroller/header/) on the same server?
From http://codeigniter.com/forums/viewthread/88635/
This is overkill, as file_get_contents($url) or similar, would be better. However, it may work for your situation:
$CI_INDEX = '/path/to/your/codeigniter/index.php';
$path = '/controller/method';
$_SERVER['PATH_INFO'] = $path;
$_SERVER['REQUEST_URI'] = $path;
chdir(dirname($CI_INDEX));
ob_start();
require($CI_INDEX);
$output = ob_get_contents();
ob_end_clean();
die($output);
Use PHP's built-in file_get_contents(). Just make sure to use the full HTTP path, not a relative path. Example:
<?php
file_get_contents('http://your.server.com/codeigniter-path/controller/');
That should do the trick.
Have you considered using an iframe in your Wordpress page?
<iframe src="http://my-site-url/index.php/mycontroller/header"></iframe>
It might be the simplest solution.
When you are trying to wrap content with HTML from an external source, this can easily be achieved by placing HTML comments (or other recognizable tags) in the target site, then using PHP to split/explode the content.
I have used this method to create several micro-sites for MSN Money which has in. Then I would simply use:
list($header_html) = explode('<!-- Header -->', file_get_contents($url));
It was slightly more complex than that, involving caching and all sorts of other madness, but at its base that is the method to use if WordPress will allow it.

Categories