Under htdocs folder i have created folder called PHP under that i have created file called index.php. I have written wrouting PHP code but it is not working.
index.php
<?php
echo "Welcome" . "<br>";
$routes = [];
route('/', function () {
echo "Home Page";
});
route('/login', function () {
echo "Login Page";
});
route('/about-us', function () {
echo "About Us";
});
route('/404', function () {
echo "Page not found";
});
function route(string $path, callable $callback) {
global $routes;
$routes[$path] = $callback;
}
run();
function run() {
global $routes;
$uri = $_SERVER['REQUEST_URI'];
$found = false;
foreach ($routes as $path => $callback) {
if ($path !== $uri) continue;
$found = true;
$callback();
}
if (!$found) {
$notFoundCallback = $routes['/404'];
$notFoundCallback();
}
}
http://localhost/PHP/
Welcome
Page not found
http://localhost/PHP/index.php/login/ (getting below output)
Welcome
Page not found
Expected output
Welcome
Login Page
Here wt am doing mistake, can anyone explain and update my code
Related
The following code is my template engine and it works great, with the small exception when a tpl file is not found the page should echo the error message "Error! Can't load the template file $templateFile".
namespace Template;
class Template
{
private $tags = [];
private $template;
public function __construct($templateFile)
{
$this->template = $this->getFile($templateFile);
if (!$this->template) {
return "Error! Can't load the template file $templateFile";
}
}
public function render()
{
$this->replaceTags();
echo $this->template;
}
public function set($tag, $value)
{
$this->tags[$tag] = $value;
}
public function getFile($file)
{
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
} else {
return false;
}
}
private function replaceTags()
{
foreach ($this->tags as $tag => $value) {
$this->template = str_replace('{'.$tag.'}', $value, $this->template);
}
return true;
}
}
I expect, when a matching .tpl file is not found the page should display "Error! Can't load the template file $templateFile", the actual output is a blank page.
Constructors are void function, Viod function means that can not return anything so you can't use return statement in constructor.
Instead of passing parameter in a constructor, Make a function for it and use return statement in that function
public function checkFile($filename)
{
$this->template = $this->getFile($filename);
if (!$this->template) {
return "Error! Can't load the template file $filename";
}
return true;
}
Make an Object of class and call that function
$obj = new Template;
$filexists = $obj->checkFile($filename);
if(!$filexists){
echo $filexists;
}
So my issue is, I have no idea how to handle page not found handling, Since routing runs every time a route is added if you do anything other than the first route it'll have 2 outputs.
Routes.php
Route::set('index.php', function() {
Index::CreateView('Index');
});
Route::set('test', function() {
Test::CreateView('Test');
});
?>
Routes.php (class)
<?php
class Route {
public static $validRoutes = array();
public static function set($route, $function) {
self::$validRoutes[] = $route;
$url = $_GET['url'];
if($url == $route) {
$function->__invoke();
die();
}
if(!in_array($url, self::$validRoutes)) {
Controller::CreateView("404");
die();
}
}
}
?>
I'm trying to understand how I'd even handle if its not found.
How about something like:
<?php
class Router
{
public $routes = [];
public function add($route, $function)
{
$this->routes[$route] = $function;
}
public function route($path)
{
$function =
$this->routes[$path] ??
$this->routes['404'] ?? null;
if(is_null($function))
http_response_code(404) && exit('404 Not Found.');
$function->__invoke();
}
}
$router = new Router;
$router->add('foo', function() {
echo 'bar';
});
$router->add('greeting', function() {
echo 'hello earth';
});
$router->route('greeting');
Output:
hello earth
Rather than trying to resolve your routes upon each addition, you can add them all, and then resolve/dispatch/route later.
I've simplified the Router::routes array to use the paths as keys.
When resolving, if the path cannot be found (the index does not exist) it will try and check for a '404' key in the routes array. Failing that it responds with a basic 404.
I need help with router when i enter route in href for example
Login
Register
first link i click works
url is localhost/account/login
but second time i click link url is localhost/account/account/register
function __construct(){
$arr = require 'application/config/routes.php';
foreach ($arr as $key => $val) {
$this->add($key, $val);
}
}
public function add($route, $params) {
$route = '#^'.$route.'$#';
$this->routes[$route] = $params;
}
public function match() {
$url = trim($_SERVER['REQUEST_URI'], '/');
foreach ($this->routes as $route => $params) {
if (preg_match($route, $url, $matches)) {
$this->params = $params;
return true;
}
}
return false;
}
public function run(){
if($this->match()){
$path = 'application\controllers\\'.ucfirst($this->params['controller']).'Controller';
if(class_exists($path)){
$action = $this->params['action'].'Action';
if (method_exists($path, $action)){
$controller = new $path($this->params);
$controller->$action();
}else{
View::errorCode(404);
}
}else{
View::errorCode(404);
}
}else{
View::errorCode(404);
}
}
Your URL's don't start with /, so they are relative to the current URL. Please add a / before.
Your code now:
Register
Change it to:
Register
There is "Logout" link all over the site. If we click on Logout, it will redirect to this page.
http://sitename/customer/account/logoutSuccess/
but in some phtml pages for example , in below page
http://sitename.com/marketplace/marketplaceaccount/myproductslist/
if we click on "Logout", it should logout but redirect to following url :
http://sitename.com/marketplace.
In google i found redirecting for entire site. but i need only for some pages.
I am using following code : Accountcontroller.php
require_once 'Mage/Customer/controllers/AccountController.php';
class Webkul_Marketplace_AccountController extends Mage_Customer_AccountController{
public function marketlogoutAction()
{
$this->_getSession()->logout()
->renewSession();
//add your code here
$this->_redirect('marketplace');
echo "something";
exit();
}
public function logoutAction()
{
$this->_getSession()->logout()
->renewSession();
$this->_redirect('*/*/logoutSuccess');
}
Data.php [app/code/local/Mage/Customer/Helper ]
public function getLogoutUrl()
{
$currentUrl = Mage::helper('core/url')->getCurrentUrl();
if (strpos($currentUrl,'marketplaceaccount') !== false) {
return $this->_getUrl('marketplace');
}else
{
return $this->_getUrl('customer/account/logout');
}
}
but when i log out from some phtml pages, its redirecting to the page that i required, but its not logged out.
Change your helper (Data.php) function to:
return $this->_getUrl('customer/account/marketlogout');
instead of
$this->_getUrl('marketplace')
Otherwise it's just redirect you to the marketplace url
use this code..
data.php
public function getLogoutUrl()
{
$currentUrl = Mage::helper('core/url')->getCurrentUrl();
if (strpos($currentUrl,'marketplaceaccount') !== false) {
return $this->_getUrl('marketplace/account/marketlogout');
} else if (strpos($currentUrl,'mpshippingmanager') !== false) {
return $this->_getUrl('marketplace/account/mpshippingmanagerlogout');
} else if (strpos($currentUrl,'mpmassuploadaddons') !== false) {
return $this->_getUrl('marketplace/account/mpmassuploadaddonslogout');
}else if (strpos($currentUrl,'mpassignproduct') !== false) {
return $this->_getUrl('marketplace/account/mpassignproductlogout');
}else
{
return $this->_getUrl('customer/account/logout');
}
}
this is for action. add one function in Accountcontroller
public function mpmassuploadaddonslogoutAction()
{
Mage::getSingleton('customer/session')->logout();
//add your code here
$this->_redirect('mpmassuploadaddons');
}
public function mpmassuploadaddonslogoutAction()
{
Mage::getSingleton('customer/session')->logout();
//add your code here
$this->_redirect('mpmassuploadaddons');
}
public function mpassignproductlogoutAction()
{
Mage::getSingleton('customer/session')->logout();
//add your code here
$this->_redirect('mpassignproduct');
} public function marketlogoutAction()
{
Mage::getSingleton('customer/session')->logout();
//add your code here
$this->_redirect('marketplace');
}
Okay, so i got class file, in which i got function -
var $text;
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
}
If i am translating via index.php like this - > echo $index->translate('search'); it translates ok, but if i am translating something in class file for example -
if ($country_rows > 0)
{
$_SESSION['country'] = $_GET['country'];
}
else
{
$_SESSION['country'] = $this->translate('all_countries');
}
}
if ($_SESSION['country'] == '')
{
$_SESSION['country'] = $this->translate('all_countries');
}
it doesn't show up.
In index.php header i got included -
require_once('class.index.php');
$index = new index;
$index->get_country();
$index->languages();
What could be the problem, and how can i fix it, so i can translate everything inside class file too? will appreciate your help!
1st guess:
no session started?
session_start();
2nd guess:
assuming that you use $this->translate() in another class, you should initiate the object first, in the following example I pass translate class to var $index;
<?
include_once('class.index.php');
class myClass {
var $index;
public function __construct() {
$index = new index();
$index->get_country();
$index->languages();
$this->index = $index;
}
public function yourFunction() {
echo $this->index->translate('all_countries');
print_r($this->index);
}
}
?>