.htaccess doesn't work with CSS files - php

I have a .htaccess file with these rules:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
I also have a Router.php file:
<?php
class Router
{
function __construct()
{
print_r($_GET);
$this->request = $_GET['url'];
$this->request = rtrim($this->request, "/");
$this->params = explode("/", $this->request);
print_r($this->params);
$this->controller = $this->params[0];
if ($this->controller == "index.php")
$this->controller = "Index";
$this->controller = ucfirst($this->controller);
$file = 'controllers/' . $this->controller . '.php';
if (file_exists($file)) {
require_once $file;
$this->connection = new $this->controller($this->params);
} else {
$file = 'controllers/PageNotFound.php';
$this->controller = "PageNotFound";
require_once $file;
$this->connection = new $this->controller();
}
}
}
and header.php
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<link href="resources/style.css" rel="stylesheet" type="text/css">
<title>System stypendialny</title>
</head>
<body>
I have a problem with the .htaccess file. When I use this version of the file and I try this http://localhost/scholarship_system/ URL in the browser I see this:
Array ( )
Notice: Undefined index: url in C:\xampp\htdocs\scholarship_system\libs\Router.php on line 8
Array ( [0] => )
But when I remove this line (RewriteCond %{REQUEST_FILENAME} !-f) then the CSS file is not loaded.

You can keep your .htaccess as it is. If you remove -f condition, you're router will need to handle all requests to css, images and javascript-files as well and that's just a pain.
Set a default controller in your Router-class instead:
$this->request = isset($_GET['url'])? $_GET['url] : 'default';
then you just need to create the file controllers/default.php which will be used if the $_GET['url] isn't set.

Related

Error 403, access denied on infinityfree domain hosting

I'm currently testing my project which has MVC integrated in it upon deploying in a free hosting site i've encountered an error 403 this error didn't appear since the development stage. My current knowledge why this error occurs is maybe the type of directives i've used in my htaccess? or something maybe in the core itself any toughts or suggestions to this particular problem :)
domain/
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>
domain/public
<IfModule mod_rewrite.c>
Options -Multiviews
RewriteEngine On
RewriteBase /domain/public
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>
domain/app
Options -Indexes
domain/app/libraries/Core.php
<?php
class Core {
protected $currentController = 'Pages';
protected $currentMethod = 'index';
protected $params = [];
public function __construct(){
//print_r($this->getUrl());
$url = $this->getUrl();
// Look in BLL for first value\
if($url != NULL){
if(file_exists('../app/controllers/' . ucwords($url[0]). '.php')){
// If exists, set as controller
$this->currentController = ucwords($url[0]);
// Unset 0 Index
unset($url[0]);
}
}
// Require the controller
require_once '../app/controllers/'. $this->currentController . '.php';
// Instantiate controller class
$this->currentController = new $this->currentController;
// Check for second part of url
if(isset($url[1])){
// Check to see if method exists in controller
if(method_exists($this->currentController, $url[1])){
$this->currentMethod = $url[1];
// Unset 1 index
unset($url[1]);
}
}
// Get params
$this->params = $url ? array_values($url) : [];
// Call a callback with array of params
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}
public function getUrl(){
if(isset($_GET['url'])){
$url = rtrim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
}

PHP site run correct on the localhost:8000 but gives erreurs on XAMPP or other server. How to create .htaccess?

This is my first experience to create a site in PHP.
My project run correct on the php interne server , but not on the Xampp ni on the server ovh
ovh serveur erreur: App\Router::run(): Failed opening required '/home/myla/www/views/.php' (include_path='.:/usr/share/php': var $view false
localhost:8000 work correct: var $view post/index
XAMPP erreur : Trying to access array offset on value of type bool :
var $view false
The probleme is in the var $view in the function run().
public function run ():self
{
$match = $this->router->match();
$view= $match['target'] ;
$params= $match['params'];
$router= $this;
$isAdmin= strpos($view, 'admin/') !== false;
$isUser =strpos($view, 'user/') !== false;
if(!$isAdmin && !$isUser){
$layout = 'layouts/default';
}
if($isUser){
$layout = 'user/layouts/default';
}
if ($isAdmin) {
$layout = 'admin/layouts/default';
}
try{
ob_start();
require $this->viewPath . DIRECTORY_SEPARATOR . $view . '.php';
$content = ob_get_clean();
require $this->viewPath . DIRECTORY_SEPARATOR . $layout . '.php';
} catch (ForbiddenException $e) {
header('Location: ' . $this->url('login') . '?forbidden=1');
die();
}
return $this;
}
I use run() in the index.php :
$router = new App\Router(dirname(__DIR__) . '/views');
$router
->get('/', 'post/index', 'home')
->get('/blog/category/[*:slug]-[i:id]', 'category/show', 'category')
->get('/blog/[*:slug]-[i:id]', 'post/show', 'post')
->match('/login','auth/login','login')
->match('/register','auth/register','register')
->post('/logout','auth/logout','logout')
->run();
I try to create .htaccess to re-write the rule, but i didnt found the good configuration.
File index.php is in the folder public and folders public,src,views are in the racine of the projet .
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /public/index.php [L]
Its not work.
Can you kindly help me to configurate .htaccess
Thanks en advance.
Here is a good configuration:
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC]
RewriteRule ^ %1 [L,NE,R=302]
RewriteRule ^((?!public/).*)$ public/$1 [L,NC]

How do I get clean URLS for only 2 variables?

I've seen/read questions about clean URLs with .htaccess, but for the life of me, I cannot get them to work for my specific needs. I keep getting 404 message.
Example: www.mysite.com/article.php?id=1&title=my-blog-title
I would like for url to be: www.mysite.com/article/1/my-blog-title
Here's what I have so far in my .htaccess:
Options -MultiViews
#DirectorySlash on
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule .* http://www.%{HTTP_HOST}%{REQUEST_URI} [L]
# Rewrite for article.php?id=1&title=Title-Goes-Here
RewriteRule ^article/([0-9]+)/([0-9a-zA-Z_-]+) article.php?id=$1&title=$2 [NC,L]
#Rewrite for certain files with .php extension
RewriteRule ^contact$ contact.php
RewriteRule ^blogs$ blogs.php
RewriteRule ^privacy-policy$ privacy-policy.php
RewriteRule ^terms-of-service$ terms-of-service.php
Also, is this how I would link to article? article.php?id=<?php echo $row_rsBlogs['id']; ?>&slug=<?php echo $row_rsBlogs['slug']; ?> or article/<?php echo $row_rsBlogs['id']; ?>/<?php echo $row_rsBlogs['slug']; ?>
I'm using Dreamweaver, but I am comfortable hand coding.
Thanks in advance.
You could use a dispatcher by telling the webserver to redirect all request to e.g. index.php..
In there a dispatch instance analizes the request and invokes certain controllers (e.g. articlesControllers)
class Dispatcher
{
// dispatch request to the appropriate controllers/method
public static function dispatch()
{
$url = explode('/', trim($_SERVER['REQUEST_URI'], '/'), 4);
/*
* If we are using apache module 'mod_rewrite' - shifting that 'request_uri'-array would be a bad idea :3
*/
//array_shift($url);
// get controllers name
$controller = !empty($url[0]) ? $url[0] . 'Controller' : 'indexController';
// get method name of controllers
$method = !empty($url[1]) ? $url[1] : 'index';
// get argument passed in to the method
$parameters = array();
if (!empty($url[2])) {
$arguments = explode('/', $url[2]);
foreach ($arguments as $argument) {
$keyValue = explode('=',$argument);
$parameters[$keyValue[0]] = $keyValue[1];
}
}
// create controllers instance and call the specified method
$cont = new $controller;
if(!method_exists($cont,$method)) {
throw new MethodNotFoundException("requested method \"". $method . "\" not found in controller \"" . $controller . "\"");
}
$cont->$method($parameters);
}
}
in .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php

.css file doesn't get carried out

Style.css doesn't get carried out when url is http://example.com/mvc/login/requestsExceeded,
but it does in my login index page that is http://example.com/mvc/login,
if I add forward slash http://example.com/mvc/login/, then it doesn't work either.
mvc = site in subdirectory
login = controller
requestsExceeded = view
.css file is in http://www.example.com/mvc/views/themes/default/style.css
The file path is ok becouse i've tryed like this:
<?php if(file_exists("views/themes/{$theme}/style.css")) echo 'TEST'; ?>
<link href="views/themes/<?=$theme;?>/style.css" type="text/css" rel="stylesheet" />
and it does echo out TEST.
Here my simplified router:
<?php
$controller = "Index";
$action = "index";
$query = null;
if (isset($_GET['load']))
{
$params = array();
$params = explode("/", $_GET['load']);
$controller = ucwords($params[0]);
if (isset($params[1]) && !empty($params[1]))
{
$action = $params[1];
}
if (isset($params[2]) && !empty($params[2]))
{
$query = $params[2];
}
}
$modelName = $controller;
$controller .= 'Controller';
$load = new $controller($modelName, $action);
if (method_exists($load, $action))
{
$load->{$action}($query);
}
else
{
die('Invalid method. Please check the URL.');
}
I'm pretty sure that this is caused by .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?load=$1 [PT,L]
-I would like to restrict all access unless index.php...,
-Allow access to .css,.gz,.js and image files,
-remove the forward slash from url,
-redirect 301 to index.php,
-redirect http://example.com/mvc/home to index.php,
Help would be appreciated!
Change your import to
<link href="/mvc/views/themes/<?=$theme;?>/style.css" type="text/css" rel="stylesheet" />
If you want the same link to work from anywhere in your site, then you'd better let the path be absolute, that is start with /.

How to prevent 403, 400 errors URL forwarding?

Site works good when user enter any url which doesn't exist and forward request to error controller.
But
If you write a script in url site throw 403 error
If you write some asp codes site throw 400 error
How can i prevent this and forward them to custom 403 and 404 pages? I tried forward with htaccess but i couldn't succeed it.
Another problem:
If you write ANY ascii code in adress bar, bootstrap forward to welcome page (controller ->index.php) .How is possible?
Directory structures, htaccess and bootstrap codes are below. Thank you for any help.
Directory structure:
/config
/libs
-bootstrap.php
/controllers
/models
/views
/public_html
-index.php
htaccess
htaccess
htaccess in main directory
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public_html/ [L]
RewriteRule (.*) public_html/$1 [L]
</IfModule>
htaccess in public_html directory
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>
index.php in public_html
<?php
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(dirname(__FILE__)));
require_once (ROOT . DS . 'libs' . DS . 'bootstrap.php');
$app = new Bootstrap();
bootstrap.php in libs
<?php
class Bootstrap {
function __construct() {
$url = isset($_GET['url']) ? $_GET['url'] : null;
$url = rtrim($url, '/');
$url = explode('/', $url);
print_r($url);
if (empty($url[0])) {
require '../controllers/index.php';
$controller = new Index();
$controller->index();
return false;
}
$file = '../controllers/' . $url[0] . '.php';
if (file_exists($file)) {
require $file;
} else {
$this->error();
return false;
}
$controller = new $url[0];
// calling methods
if (isset($url[2])) {
if (method_exists($controller, $url[1])) {
$controller->{$url[1]}($url[2]);
} else {
$this->error();
}
} else {
if (isset($url[1])) {
if (method_exists($controller, $url[1])) {
$controller->{$url[1]}();
} else {
$this->error();
}
} else {
$controller->index();
}
}
}
function error() {
require '../controllers/error.php';
$controller = new Error();
$controller->index();
return false;
}
}

Categories