Codeigniter URL Dilemma - php

I am having issues with the urls. I took the .htaccess code from the user guide to remove the index.php from the url and I have removed it from the config as well. Now here is the problem. I have a controller named “main” and a function inside called “join” which simply display the view. Now if I go to http://localhost/myfolder it loads the index view just fine. However if I try to go to http://localhost/myfolder/main/join or http://localhost/myfolder/join it gives me a 404 error. But http://localhost/myfolder/index.php/main/join works however without loading any css from my header file, but the footer is still loaded. Which I am very confused about. How can I possibly fix it so it just works with main/join? I will use routing later to make it just /join however I need the css to load like it does with my “index” view but not with my “join” view. Also localhost/myfolder/main gives me a 404 error as well. All I did was take the code from the user guide and paste it in .htaccess Any help guys?

Question is little confusing but let me try to answer what I got.
Question 1. Make 'localhost/myfolder/main/join' working.
You mainly need to remove index.php. Do the following:
a. (Very important) Make sure apache's rewrite module is enabled. IF you are using wamp, go to 'Apache'>'Apache modules' and make sure 'rewrite_module' is checked.
b. In code igniter, open file application>config>config.php. Search the line:
$config['index_page'] = 'index.php';
Remove index.php from there. Line must be
$config['index_page'] = '';
c. on myfolder, make a file .htaccess and add following code there:
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
Now URL 'localhost/myfolder/main/join' must be working.
Question 2: Load CSS
To load css, user following code under head section of your view:
<?php echo link_tag('style/style.css');?>
Make sure style/style.css is present in root folder; 'myfolder' in your case.
Hope this helps,
Kapil.

Related

htaccess and POST variable issues with Codeigniter

So I am doing a bit of research on this topic, and you would think there would be an answer but there isn't, or maybe I am looking in the wrong area.
Problem
When submitting a form my post variables are empty. I am passing them through properly, the form goes where it needs to go to, and the variables and form data appear properly and with values, in the headers. I have the form helper autoloaded in the config, so everything is how it should be.
my form opener looks like this:
<form action='/Forms/form_processor/' method='post' id='testForm'>
In my Forms controller looks like this:
define('BASEPATH') OR exit('No direct script access allowed');
class Forms extends CI_Controller{
public function form_processor(){
// get variables
$name = $this->input->post('name');
// ... do stuff with variable data
}
}
I would also note that with the use of the htaccess file my config variables are:
$config['base_url'] = 'http://example.com/';
$config['index_page'] = ''; // this is to keep index.php out of the URL
Possible Cause
When using codeigniter and sitting at the home page, you get this URL:
http://example.com
That is fine, until you go to the next page, you get this URL:
http://example.com/index.php/page
It looks ugly, so for aesthetic purposes and to keep uniformity I created an htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /example.com/
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 http://example.com/
</IfModule>
and then by having this htaccess file at the base directory I get the URL to look like this:
http://example.com/page
Temp Fix and Questions Needing Answers
It was pointed out to me that because my $config['index_page'] variable is null that this is where the problems are stemming from. So I added the index.php to the beginning of my url in the form's action and it goes through.
Shouldn't the htaccess re-write handle this issue, and send it to where it is supposed to go where I have the index.php in the form's action URL or not?
Secondly, how would this affect the post variables? Because when I submit the form it still gets to where it needs to go to, it just shows null for all the variables, even though they are properly sent through the headers. This is where I am most confused.
If you need more information please let me know, but we are just trying to figure out why this is happening over here, it's kind of awkward. Thank you in advance!
Your question seems complicated. I think there might be an issue with installation steps. Remove index.php from config, set base url (also in application/config.php), set the encryption key(also there).
Check what are the session settings - did you change something there.
Also simplify htaccess (put it where is your index.php)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Is this local or server issue?
And last - try to use form helper, does it change something, whats inside console? Show more of your controller. You can check post inside one function
class Forms extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function form_processor()
{
//check if $_POST
if ($this->input->post()) {
$name=$this->input->post('name');
//process and redirect
}
$this->load->view('forms/my_form');
}
}
Also if you use xss_filtering or csrf_protection(check that in config.php) you should definitely use form helper.
/forms/form_processor/' method='post' id='testForm'>
Use base URL in form action.
If not work so use index.php after base URL.

.htaccess create user friendly url and ridirect to it

i tryed to search everywhere for this problem but i didnt found nothing.
I want to make make a url seo friendly so i used this code:
RewriteEngine on
RewriteRule ^Homepage index.php [NC,L]
Then i want to redirect to it so i tryed to write this code:
RewriteRule ^index.php$ http://localhost/siti/socialmark/Homepage [R=301,L]
The error it's a loop of redirections, can someone help me?
SORRY FOR MY BAD ENGLISH!
The rewrite rules don't just make the URL string look different, it actually directs the user to the file at the end of the path even if you don't see it in the address bar. If Homepage is a directory containing index.php, even if that php file name doesn't appear in the URL, then it's causing a loop because it's directing you to a directory with an index.php.
The rule is executed every time that page loads. So, you're redirecting to a page which runs the redirect script, so it runs the rule to redirect again, and that causes the loop. What you want to do is create a condition that says "Don't run this code if the requested page is http://localhost/siti/socialmark/Homepage"
Something like this (you may have to adjust it)
RewriteBase /
RewriteCond %{REQUEST_URI} !=/siti/socialmark/Homepage
RewriteRule ^Homepage index.php [NC,L]
For more details, see the caveats and example here:
http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_l

URL Routing using RewriteRule

I am trying to create my own PHP MVC framework for learning purpose. I have the following directory structure:
localhost/mvc:
.htaccess
index.php
application
controller
model
view
config/
routes.php
error/
error.php
Inside application/config/routes.php I have the following code:
$route['default_controller'] = "MyController";
Now what I am trying to achieve is when any user visits my root directory using browser I want to get the value of $route['default_controller'] from route.php file and load the php class inside the folder controller that matches with the value .
And also if any user tries to visit my application using an url like this: localhost/mvc/cars, I want to search the class name cars inside my controller folder and load it. In case there is no class called cars then I want to take the user to error/error.php
I guess to achieve the above targets I have to work with the .htaccess file in the root directory. Could you please tell me what to code there? If there is any other way to achieve this please suggest me.
I have tried to use the .htaccess codes from here, but its not working for me
It all sounds well and good from a buzzword standpoint, but to me this is all a little confusing because I see PHP's model as an MVC model already. It's providing the API for you to program with and deliver your content to your web server Apache and your database (something like MySQL). It translates the code(model) for you into HTML(view) ... provided that's what you intend, and you're supplying code as the user input (control). Getting too wrapped up in the terminologies gets a little distracting and can lead to chaos when you bring someone in to collaborate who isn't familiar with your conventions. (This should probably never be used in a production environment for a paying gig.)
I can tell you that on the page that you referenced they guy's .htaccess file needs a little work. The [L] flag tells mod_rewrite that this is the last command to process when the rule returns true. So you would either need to do this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Or the following... but he was using a passthru flag which means that he is implying there are other things that could be processed prior to the last rule (eg. might be rewrite_base or alias), but that's not actually the case with his .htaccess file since it's a little bare. So this code would work similar to the code above but not exactly the same. They can't be used together though, and really there would be no need to:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?url=$1
</IfModule>
The difference is the in the way it's processed. On the first .htaccess example you're passing any file to index.php regardless of whether it exists or not. You can [accidentally] rewrite a path that has a real file so that the real file is never accessed using this method. An example might be you have a file called site.css that can't be accessed because it's being redirected back to index.php.
On the second ruleset he's at least checking to see if the server doesn't have a file or a directory by the name being requested, then they're forwarding it to index.php as a $_GET variable (which seems a little pointless).
The way I typically write these (since I know mod_rewrite is already loaded in the config) is to to this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule .* index.php
In my PHP code I pull the $_SERVER['REQUEST_URI'] and match it against a list of URIs from the database. If there's a match then I know it's a real page (or at least a record existed at some point in time). If there's not a match, then I explode the request_uri and force it through the database using a FULLTEXT search to see what potentially might match on the site.
Note: if you blindly trust the request_uri and query the database directly without cleaning it you run the risk of SQL injection. You do not want to be pwnd.
<?php
$intended_path = $_SERVER['REQUEST_URI'];
if(in_array($intended_path,$uris_from_database)){
//show the page.
} else {
$search_phrase = preg_replace('!/!',' ',$intended_path);
$search_phrase = mysqli_real_escape_string($search_phrase);
$sql = "SELECT * FROM pages WHERE MATCH (title,content) AGAINST ('$search_phrase');"
}
Sorry if this sounds a bit pedantic, but I've had experience managing a couple of million dollar (scratch) website builds that have had their hurdles with people not sticking to a standard convention (or at least the agreed upon team consensus).

Pretty URLs from DB

I am working on creating page links from DB like the following example.
Current page:
www.example.com/page.php?pid=7
In the DB it is saved as title "contact-us" under category "Company Info"
I want it to be like:
www.example.com/company-info/contact-us.html
I have tried different solution and answers but did not got any luck. I am not sure, where will be the PHP part and which rules to write for .htaccess files.
In apache (or .hataccess) do something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /proxy.php?_url=$1 [QSA,L]
So in a nutshell, if the resource being requested doens't exist, redirect it to a proxy.php file. From there $_REQUEST['_url'] will be the url the user was requesting.
Then create proxy.php in your home directory and add whatever logic you'd like to load the correct content.
If you use this from .htaccess, then you may need to add RewriteBase / to your config.
If you want to find this page by url, you will probably do this through php and .htaccess. Make a .htaccess that calls page.php for each and every request. You don't need the pid=7, because, well, how should the .htaccess know it is 7, right? :)
In page.php, you take the original url and split it on the slashes, so you get the category (company-info) and the page itself (contact-us.html). Then, you can look these up in the database. This is in a nutshell how many software works, including Wikipedia (MediaWiki) and CodeIgnitor.
Mind that 'company-info' isn't the same as 'Company Info'. You'll have to specify the url-version in the database to be able to use it for look-up.

How can I remove file extension from a website address?

I am designing a website. I want my website address to look like the following image:
I don't want my website to look like http://something.example/profile.php.
I want the .php extension to be removed in the address bar when someone opens my website. In other words, I want my website to be like: http://something.example/profile
As a second example, you can look at the Stack Overflow website address itself.
How can I get this done?
Just add an .htaccess file to the root folder of your site (for example, /home/domains/domain.example/htdocs/) with the following content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
More about how this works in these pages: mod_rewrite guide (introduction, using it), reference documentation
First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.
You don't hide URLs or extensions. What you do is create a NEW URL that directs to the old one, for example
The URL to put on your web site will be yoursite.example/play?m=asdf
or better yet
yoursite.example/asdf
Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /play.php [L]
Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same OR create a database table that correlates the "SEO friendly URL" with the product id. An example might be
/Some-Cool-Video (which equals product ID asdf)
The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?
I can't give you specifics of how to program this, but take the query string, strip off the end
yoursite.example/Some-Cool-Video
turns into "asdf"
Then set the m variable to m=asdf.
So both URLs will still go to the same product
yoursite.example/play.php?m=asdf
yoursite.example/Some-Cool-Video
mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)
You have different choices.
One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder.
and you can give orders to this page in this way:
Old page: http://something.example/profile.php?id=a&abc=1
New page: http://something.example/profile/?id=a&abc=1
If you are not satisfied leave a comment for complicated methods.
Here is a simple PHP way that I use.
If a page is requested with the .php extension then a new request is made without the .php extension. The .php extension is then no longer shown in the browser's address field.
I came up with this solution because none of the many .htaccess suggestions worked for me and it was quicker to implement this in PHP than trying to find out why the .htaccess did not work on my server.
Put this at the beginning of each PHP file (preferrably before anything else):
include_once('scripts.php');
strip_php_extension();
Then put these functions in the file 'scripts.php':
//==== Strip .php extension from requested URI
function strip_php_extension()
{
$uri = $_SERVER['REQUEST_URI'];
$ext = substr(strrchr($uri, '.'), 1);
if ($ext == 'php')
{
$url = substr($uri, 0, strrpos($uri, '.'));
redirect($url);
}
}
//==== Redirect. Try PHP header redirect, then Java, then http redirect
function redirect($url)
{
if (!headers_sent())
{
/* If headers not yet sent => do php redirect */
header('Location: '.$url);
exit;
}
else
{
/* If headers already sent => do javaScript redirect */
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
/* If javaScript is disabled => do html redirect */
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';
echo '</noscript>';
exit;
}
}
Obviously you still need to have setup Apache to redirect any request without extension to the file with the extension.
The above solution simply checks if the requested URI has an extension, if it does it requests the URI without the extension. Then Apache does the redirect to the file with the extension, but only the requested URI (without the extension) is shown in the browser's address field.
The advantage is that all your "href" links in your code can still have the full filename, i.e. including the .php extension.
The problem with creating a directory and keeping index.php in it is that
your links with menu will stop functioning
There will be way too many directories. For eg, there will be a seperate directory for each and every question here on stackoverflow
The solutions are
1. MOD REWRITE (as suggested above)
2. use a php code to dynamically include other files in index file. Read a bit more abt it here http://inobscuro.com/tutorials/read/16/
Actually, the simplest way to manipulate this is to
Open a new folder on your server, e.g. "Data"
Put index.php (or index.html) in it
And then the URL www.yoursite.example/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.example/data/list run that PHP file.
This way you can have full control over this, very useful for SEO.
same as Igor but should work without line 2:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Tony, your script is ok, but if you have 100 files? Need add this code in all these :
include_once('scripts.php');
strip_php_extension();
I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D
Remove a file extension through .htaccess:
Original URL: http://ravinderrathore.herobo.com/contact.php
.htaccess rule to remove .php, .html, etc. file extensions from URLs:
RewriteRule ^(.*)$ $1.php
After Rewriting: http://ravinderrathore.herobo.com/contact
RewriteEngine on
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^index(.*)?$ index.php$1 [L,QSA]
RewriteRule ^login_success(/)?$ login_success.php [L,QSA]
RewriteRule ^contact(/)?$ contact.php [L,QSA]
just nearly the same with the first answer about, but some more advantage.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
Just add up if you have a other file-extension in your sites
For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccessbut this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.
I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css,js and phpfiles even more like images or whatever you have.
Cr8Router - Simple PHP Router

Categories