The following code is in the index.php file of my site and runs every time a page on my website is queried. Both of these requires execute there own respective 404 error pages so dont worry about that. What is the most performance efficient way of doing this within php?
$cache = $_SERVER['REQUEST_URI'];
if(preg_match('/^\/blog/',$cache) || preg_match('/^\/portfolio/',$cache)){
define('WP_USE_THEMES', true);
// Loads the WordPress Environment and Template
require('./wordpress/wp-blog-header.php');
}else{
// Load codeigniter
require('./codeigniter/index.php');
}
$cache = $_SERVER['REQUEST_URI'];
if (0 === strpos($cache, '/blog/') ||
0 === strpos($cache, '/portfolio/'))
{
define('WP_USE_THEMES', true);
require('./wordpress/wp-blog-header.php');
}
else
{
require('./codeigniter/index.php');
}
No Regex needed and it is super fast.
Related
I have this error while I'm using this my script:
$pages = array('/about.php', '/');
//...............function text here................//
$ua = $_SERVER['HTTP_USER_AGENT'];
$mobiles = '/iphone|ipad|android|symbian|BlackBerry|HTC|iPod|IEMobile|Opera Mini|Opera Mobi|WinPhone7|Nokia|samsung|LG/i';
if (preg_match($mobiles, $ua)) {
$thispage = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
if ($thispage == $_SERVER["HTTP_HOST"].$pages) {
ob_start("text");
}
}
This script changes certain pages style depending on user's useragent. I need this script in such way. But I don't know how to make it in PHP properly. Maybe I need some "foreach ($pages as $i)"? But it didn't work in a way I made it.
You are trying to check if the "requested resource" $_SERVER["REQUEST_URI"] is in predefined list of resource paths.
Change your condition as shown below(using in_array function):
...
if (in_array($_SERVER["REQUEST_URI"], $pages)) {
ob_start("text");
}
In my MY_Controller.php, I want to detect user device and the requested domain name. Domain names I am using on same app are: www.seeme.tld and m.seeme.tld, also I am using $this->detect().
So this is what I did:
<?php
if($this->detect->isMobile() || $_SERVER['HTTP_HOST'] === MOBILE_URL){
$this->config->set_item('base_url', MOBILE_URL);
}elseif(!$this->detect->isMobile() || $_SERVER['HTTP_HOST'] != MOBILE_URL){
$this->config->set_item('base_url', WEBSITE_URL);
}
?>
I have 2 folders in application/views folder : PC(for pc users) and Mobile(for mobile users)
In order to load views, I used this code in my fetch() function:
public function fetch($view, $data = array, $other_vars = false)
{
if(base_url() === MOBILE_URL || $this->_ci->detect->isMobile()){
$f = 'Mobile/';
}elseif(!$this->_ci->detect->isMobile() || base_url() != MOBILE_URL){
$f = 'PC/';
}
return $this->_ci->load->view($f.'contents/'.$view, $data, true);
}
When I use a mobile device or the visit m.seeme.tld with a mobile device, I get mobile contents. But when I visit visit m.seeme.tld with a PC instead of getting mobile contents, I rather get PC contents. Please help me solve this issue!
Changing config array could be problematic sometimes: How to override config's array within a controller in CodeIgniter?. Also you are doing double check (in controller and in the function).
I archieve similar behaviour with doing this way:
YOURCONTROLLER.PHP __construct():
if ($this->detect->isMobile() || $_SERVER['HTTP_HOST'] === MOBILE_URL){
define('IS_MOBILE', TRUE);
}else{
define('IS_MOBILE', FALSE);
}
then you could use to load the view:
if (IS_MOBILE) {
$view_folder = 'Mobile/';
}else{
$view_folder = 'PC/';
}
$this->load->view($view_folder.$view, $data, TRUE);
Also you could add a single checkpoint to view if the if statment is working fine:
if ($this->detect->isMobile() || $_SERVER['HTTP_HOST'] === MOBILE_URL){
define('IS_MOBILE', TRUE);
log_message('debug', 'Im mobile browser: '.$this->detect->isMobile().' or the url is mobile:'.$_SERVER["HTTP_HOST"]);
}else{
define('IS_MOBILE', FALSE);
log_message('debug', 'Im pc');
}
Hope it helps to you.
// This works only replace the '===' with '='.
thanks for the help but i got it fixed. all i did was to first detect mobile users in MY_Controller.php and redirect them to MOBILE_URL then in my fetch() i did:
if($_SERVER['HTTP_HOST'] = MOBILE_URL){
$view_folder = 'Mobile/;
}else{ $view_folder = 'Frontend/;
}
and that's it,Paam it started working.
I'm currently working to make my own CRM website application and I followed Alex youtube tutorial which is the login/register using OOP.
In addition I need my index.php to be the dynamic content switcher, which I only include header and footer while the content load from a folder where it stores all the page. I believe the end result should be like www.example.com/index.php?page=profile
I look around and it seems like what I'm doing it's something similar to MVC pattern where index is the root file and all the content is loaded from view folder.
I managed to get everything done correctly but now instead of displaying the link like: www.example.com/user.php?name=jennifer
I wanted it to be www.example.com/user/name/jennifer
I try to look around phpacademy forum but the forum seems to be abandon, some search I managed to find a topic that relevant to what I want, but the code doesn't seems to be working and I got the same error with poster.
here is the code:
<?php
// Define the root of the site (this page should be in the root)
define('ROOT', rtrim(__DIR__, '/') . '/');
define('PAGES', ROOT . 'pages/');
// Define "safe" files that can be loaded
$safeFiles = ["login", "regiser", "profile", "changepassword"];
// Get URL
if(isset($_GET['page']) && !empty($_GET['page'])) {
$url = $_GET['page'];
} else {
$url = '/';
}
// Remove Path Traversal
$sanatize = array(
// Basic
'..', "..\\", '../', "\\",
// Percent encoding
'%2e%2e%2f', '%2e%2e/', '..%2f', '%2e%2e%5c', '%2e%2e', '..%5c', '%252e%252e%255c', '..%255c',
// UTF-8 encoding
'%c1%1c', '%c0%af', '..%c1%9c'
);
$url = str_replace($sanatize, '', $url);
// Prevent Null byte (%00)
// PHP 5.6 + should take care of this automatically, but PHP 5.0 < ....
$url = str_replace(chr(0), '', $url);
// Filter URL
$url = filter_var($url, FILTER_SANITIZE_URL);
// Remove any extra slashes
$url = rtrim($url, '/');
// Make lowercase url
$url = strtolower($url);
// Check current page
$path = PAGES . $url . '.php';
// If the file is in our safe array & exists, load it!
if(in_array($url, $safeFiles) && file_exists($path)) {
include($path);
} else {
echo "404: Page not found!";
}
I search around Google but I couldn't find a solution and I notice there were people asking in this forum as well hence I hope someone can assist me in this area.
Dear friends I have installed prestashop on my existing website.My current website has a login system that I have already built.
Because of installing prestashop for my system,I thought to change my existing login to prestashop login.
As for the prestashop documentation,to access prestashop cookie outside prestashop,I made a test page to retrieve cookie data as follows,
include_once('path_to_prestashop/config/config.inc.php');
include_once('path_to_prestashop/config/settings.inc.php');
include_once('path_to_prestashop/classes/Cookie.php');
$cookie = new Cookie('ps');
print_r($cookie);
But this is not working and browser says
It contains redirect loop.
I tried to disable SEO friendly url and cannonical url to no-direct as some posts suggested.
Now if I go to the test page it redirects to the prestashop index page rather displaying cookie data.
What should I do to overcome this problem?
Thank you.
When you include config/config.inc.php PrestaShop redirects to the shop domain.
The following code is causing this behavior in classes/shop/Shop.php:
$shop = new Shop($id_shop);
if (!Validate::isLoadedObject($shop) || !$shop->active)
{
// No shop found ... too bad, let's redirect to default shop
$default_shop = new Shop(Configuration::get('PS_SHOP_DEFAULT'));
// Hmm there is something really bad in your Prestashop !
if (!Validate::isLoadedObject($default_shop))
throw new PrestaShopException('Shop not found');
$params = $_GET;
unset($params['id_shop']);
$url = $default_shop->domain;
if (!Configuration::get('PS_REWRITING_SETTINGS'))
$url .= $default_shop->getBaseURI().'index.php?'.http_build_query($params);
else
{
// Catch url with subdomain "www"
if (strpos($url, 'www.') === 0 && 'www.'.$_SERVER['HTTP_HOST'] === $url || $_SERVER['HTTP_HOST'] === 'www.'.$url)
$url .= $_SERVER['REQUEST_URI'];
else
$url .= $default_shop->getBaseURI();
if (count($params))
$url .= '?'.http_build_query($params);
}
$redirect_type = Configuration::get('PS_CANONICAL_REDIRECT') == 2 ? '301' : '302';
header('HTTP/1.0 '.$redirect_type.' Moved');
header('location: http://'.$url);
exit;
}
You could override the Shop class to disable the redirect for your script.
To do this first define PS_DISABLE_SHOP_REDIRECT constant before you include config/config.inc.php:
define('PS_DISABLE_SHOP_REDIRECT', true);
Then paste the following before the previous code in the overridden class:
if (defined('PS_DISABLE_SHOP_REDIRECT')) {
$id_shop = Configuration::get('PS_SHOP_DEFAULT');
}
Among the following include methods which is the best to practice and why?
$page = $_GET['page'];
Method 1
$pages = array('home', 'blog', 'about');
if( in_array($page, $pages) )
{
include($page.'.php');
{
else
{
die('Nice Try.');
}
Method 2
if($page = 'home'){
include('home.php');
}else if($page = 'blog'){
include('blog.php');
}else if($page = 'about'){
include('about.php');
}
Method 3
if(str_replace("http://", "gth://", $page) == $page){
include_once $page;
}else{
die('Nice Try.');
}
or any other solutions? I dont prefer method 1 and 2 as it always needs to be updated everytime i add a new page.
extending/maintaining the first way is easiest, second way is worse. third way is no way to go, as it relies on user input to require pages... it is going to be a security hole
I believe that the first one is the best of the lot. You can try the second one, but it's for the freshers. And the third one is a BIG NO, because any fresher hacker could hack your "if" condition, & more loopholes will start creeping in.
As for your problem, on adding a new page to the array, every time a new page is created, for the first method, I have one solution:-
Let's say you're putting all the new pages in one folder "abc". Now just write one file code as the following, to read all the files / pages existing in that folder:-
<?php
$page = $_GET['page'];
$pages = array();
/**
* If you are using all the pages existing in the current folder you are in,
* then use the below variable as:-
* $path = ".";
*/
$path = 'abc/'; // Change the Path here, related to this Folder name
$handle = opendir($path);
while (($file = readdir($handle)) !== false) {
$pages[] = $file;
}
closedir($handle);
if( in_array($page, $pages) ) {
include($page.'.php');
}
else {
die('Nice Try.');
}
?>
So you see that the array is getting filled up dynamically, without the need to mention all the pages you create every time. And you are using the first method only. And keep the including pages in one separate folder, which you will need to include every time, in other main pages.
Hope it helps.