I am using MVC framework in my website.In my webpage URL file extension is not showing.I need to specify the file extension like
www.legacy.com/women/tops.php
but its showing only
www.legacy.com/women/tops/
for seo purpose I want to change the url with extension. But I can't change the folder or file name.
One more doubt I have that.My webpage is showing
www.legacy.com/women/tops/
like this I want to change this as www.legacy.com/women_tops.php/
Is it possible?
Thank you
Here is the code I use to associate a URL with a controller:
$arrCommands = array (
'home' => "contents",
'members' => "",
);
if ( $arrCommands[$command1] == "*" )
{
$includeFile = CONTROLLER_PATH . "/" . $command1 . "/" . $command2 . ".php";
if ( !file_exists($includeFile) )
$includeFile = CONTROLLER_PATH . "/" . $command1 . "/default.php";
}
elseif ( !array_key_exists($command1, $arrCommands) )
{
$includeFile = CONTROLLER_PATH . "/contents/" . $command1 . ".php";
if ( !file_exists($includeFile))
Header( "Location: http://metroplots.ragedev/404_error/" );
}
else
{
$includeFile = CONTROLLER_PATH . "/". $arrCommands[$command1] . "/" . $command1 . ".php";
if ( !file_exists($includeFile) )
$includeFile = CONTROLLER_PATH . "/contents/home.php";
}
include_once($includeFile);
.htaccess can do magic. Can rewrite anything to whatever you want, can get messy...
http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
You should also be able to do this in the application itself. In most good frameworks you can use customize routes, here is zend example.
the technology your looking for is called url rewriting
the idea is taking a give url and rewriting it on the server side. lots of software use this method to not expose logic via get parameters...
e.g.
http://domain.com/blog/2
according to the server, this url is actually:
http://domain.com/index.php?cat=blog&page=2
on linux/apache servers is is achieved via modrewrite:
http://httpd.apache.org/docs/current/mod/mod_rewrite.html
using .htaccess files on the server that explain the rewrite rules and route urls.
microsoft iis servers have their own flavor (and syntax) called url rewrite:
http://www.iis.net/downloads/microsoft/url-rewrite
there are some tools out there to do this for you (here's an overview of 6 of them)
http://webm.ag/2009/12/15/6-of-the-best-mod-rewrite-generators/
but i feel like most times your best best is to manually create your own.
here's an example of the one i use on my site:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
basically this ruleset will redirect all traffic to index.php
in my MVC i have a generic controller called "url_logic" that runs first and looks at what the url is. and based upon it's logic it creates the necessary controllers to create the site (even if it's a 404 error controller).
hope that helps get you started!
also, if your using windows .htaccess files are tough to work with. i suggest naming them
htaccess.txt and when you upload them to the server rename them there.
You have to add below 2 line in htaccess
RewriteEngine On
RewriteRule ^women/tops /women_tops.php
create a index.php file, which will be read as default file for display and redirect it to your file.
What you are looking is mod_rewrite
mod_rewrite:
HIDING EXTENSION IN URL:
mod_rewrite Rewrite Rule generator will take a dynamic url given to it, and generate the correct syntax to place in a .htaccess file to allow the url to be rewritten in a spiderable format. The apache module mod_rewrite converts urls in a certain format to another format, and can be very useful in helping a site with dynamic content to be indexed.
NOTE : Before mod_rewrite put in action you should enable it in apache server.
Syntax: RewriteRule url-pattern url-new [[flag,...]]
Example: RewriteRule ^/foo/(.*)$ /bar/$1 [R,L]
Some useful links-
URL : http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
URL : http://tomclegg.net/rewriterule
have a look at this web page. i think it may have answers for you.
Thank you for every one who replayed to this question.
$xepWords = explode('_',$command1);
if($xepWords[0] == 'women')
{
$includeFile = CONTROLLER_PATH .'/women/tops.php';
}
I added this code in controller action Now its working fine
Related
It's pretty hard to explain so if somebody have a better title then be my guest..
Basically I made a website with 5 pages.
1) index.html
2) page.html
3) footer.html
4) menu.html
5) contact.html
In order to access the pages you have to type the page name at the end of the domain (I bet you knew that..)
I wanted to access the pages with a code..
for example -> mywebsite.com\?page=contact
How can I do this ?
Kind Regards,
Kobi.
why don't make a index.php with following code:
<?php
include($_GET['page'].'.html');
?>
The result will be:
calling mywebsite.com/?page=contact will open mywebsite.com/index.php?page=contact because this is default
the url will stay mywebsite.com/?page=contact
the script load the file contact.html and show it
You only need to configure whatever web server you have to look for a file called index.php whenever you don't specify any. That has been a pretty standard feature of all web servers since the early 1990s. In Apache you'll use the DirectoryIndex directive; this is what mine looks like:
<IfModule dir_module>
DirectoryIndex index.php index.html
</IfModule>
Then, write PHP code in such index.php to act as router. You should check Variables From External Sources and learn about $_GET.
However, that's probably not the best layout. Friendly URLs have been around for years:
http://example.com/contact
... and it's again mostly a web server feature. In Apache you'd use the mod_rewrite module. Here's a sample rule used by some PHP frameworks:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Requested path can be parsed out of $_SERVER['REQUEST_URI'].
Once you put your hands in the index.php file there're a lot of design patterns you can use (modern frameworks often use a third-party router and template engine) but if you're to learn from scratch and just want to get something done quickly from static HTML you can use a combination of switch statements (to create a route white list) and readfile() to inject each file into the output. (Beware that PHP include construct family will handle files as PHP code, which is not what you want.)
<?php
define('INC_PATH', __DIR__ . '/../wherever/includes/are');
switch ($_GET['page']) {
case 'contact':
case 'help':
case 'whatever':
$page = $_GET['page'];
break;
default:
$page = 'error';
}
readfile(INC_PATH . '/index.html');
readfile(INC_PATH . '/page.html');
readfile(INC_PATH . '/footer.html');
readfile(INC_PATH . '/menu.html');
readfile(INC_PATH . "/$page.html");
I want to create friendly urls for my website script only using PHP, right now im using the query style (Ex: index.php?location=register) and i would like to convert them to something like this:
https://www.sitename.com/index.php/Register
Right now im using a $_GET based function to parse and include the php script based on the $_GET value.
$includeDir = ".".DIRECTORY_SEPARATOR."assets/controllers".DIRECTORY_SEPARATOR;
$includeDefault = $includeDir."Home.php";
if(isset($_GET['ajaxpage']) && !empty($_GET['ajaxpage'])){
$_GET['ajaxpage'] = str_replace("\0", '', $_GET['ajaxpage']);
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath)) {
include($includePath);
}
else{
include($includeDefault);
}
exit();
}
if(isset($_GET['location']) && !empty($_GET['location']))
{
$_GET['location'] = str_replace("\0", '', $_GET['location']);
$includeFile=basename(realpath($includeDir.$_GET['location'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath))
{
include($includePath);
}
else
{
include($includeDefault);
}
}
else
{
include($includeDefault);
}
Kind regards!
Okay, my comment keeps growing...so I guess I'll just provide an answer...
1) This still requires server configuration. In the case of Apache, I believe it's called MultiView. This is what allows Apache to look up a directory when the first path /file.php/somepage is not found...if you don't have the right configuration, it will just give a 404 error even though file.php exists. So, if your intention is to avoid the need for server configuration, it won't work.
2) What you are doing is dangerous:
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage'].".php"));
All I have to do is know where some of your files are and I can potentially cause one of your PHP files to run...e.g. run your nightly cron every 5 minutes and overwhelm your server or some other page that might do some damage...you need some way of forcing only files with a certain name can be included...e.g.
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage']."Controller.php"));
By forcing a suffix of Controller to the filename, you just have to make sure not to use the name Controller at the end of the file name for any file you don't want to be include-able.
3) There are so many MV* style frameworks out there...and there are so many security considerations, etc., that it is not always wise to create your own until you understand many or most of them. Even if you don't like them, using those frameworks will also help you learn some best practices for creating your own.
4) Finally, what in the world is the reason to avoid using URL Rewriting. URL Rewriting is the STANDARD for both Apache and Windows to create clean URLs. There is a reason that "everybody's doing it." If it's performance, your way will actually, probably, be slower because apache first has to look to see if the path exists, then go up a directory and see if that file exists, then go up another directory and see if that file exists until it hits a match...then open that file.
Why do you need to show index.php in the URL?
I would create my URL to look like this https://www.sitename.com/register if you truly want clean URL's but you would need to use something like the rewrite.
But you would need to use .htaccess or Apache config rules such as this.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?location=$1 [L]
Then in your PHP code you can do a get on location var $_GET["location"] and then load the page from the value sent.
The result of $_GET["location"] would be register from this URL and then you will display that page.
I don't suggest using MultiViews as it can cause issues if you have file and folders with the same name. e.g. /admin and admin.php.
I have decided to build a web application using clean urls. However its seems to be quite hard for at first. I have experienced many problems during testing and I couldn't figure out how is it recommended to build Clean URLs basically.
I have finally decided to redirect everything to the index.php and process the URI from there.
This is my .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php?url=$0 [QSA]
In the PHP end I have created this, so only the URLs in the array will be passed:
$root_path = '/';
$uri = $_SERVER['REQUEST_URI'];
$url = array(
$root_path . 'login' => 'login'
);
$url_basic = array_keys($url);
$url_slash = array_keys($url);
array_walk($url_slash, function(&$value, $key) { $value .= '/'; return $value;});
if (in_array($uri, $url_basic) || in_array($uri, $url_slash)) {
$uri = rtrim($uri,'/');
require $url[$uri] . '.php';
exit();
} else {
echo 'Bad';
}
So basically if someone types: /login or /login/ they'll have the login.php required, otherwise they'll stay on the index.php page (as APACHE redirects everything else).
Question:
Let's say that the user has received an error while trying to log in. In this case I guess the best way (or if its not the best way, please tell me) to pass a $_GET variable with the name of 'error' for example. So the user would get: /login/?error=1
How is it possible to achieve that result? Because if I type that I get redirected to the index.php page. Can anyone please help me?
You can look at $_SERVER['QUERY_STRING'] at cut the query string out of $_SERVER['REQUEST_URI']:
if ($_SERVER['QUERY_STRING'])
echo substr($_SERVER['REQUEST_URI'], 0, -strlen($_SERVER['QUERY_STRING']) - 1);
The -1 is there to remove the question mark as well.
But setting the error in GET is not necessary. You can use a flash message and store the error in the session. You can find a simple way to use them here.
Maybe you should consider using a routing system as that of
Symfony: http://symfony.com/doc/current/book/routing.html
or its slimmer counterpart
Silex: http://silex.sensiolabs.org/doc/usage.html#routing
I am trying to set up a dynamic application-serving framework for a development test.
My desired outcome is that when a user goes to a URL, if it is formatted like hostname.com/somecategory/someapplicationname/ or hostname.com/somecategory/someapplicationname (without the slash at the end), it should serve the user the requested application from the database, as long as the category and application name exists as a key.
I have a special case where some applications are not in the database, and they exist on file with that same URL, so we serve the existing file with priority over any database records.
The case with dynamic content from the database works fine. The case for the existing file works 100% only if there is a slash at the end. If the slash is not there, it will serve the right file, BUT the URL looks rather odd. It'll show: hostname.com/somecategory/someapplicationname/?category=somecategory&appname=someapplicationname
So, it works, but the unexpected output makes me feel that the solution is not complete.
I am using apache mod_rewrite, and my .htaccess file is as follows:
RewriteEngine on
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ route.php?category=$1&appname=$2 [NC,L]
The PHP code specific to this case is as follows. I stripped the validation and database connection from this snippet for simplicity of reading, but the logic for this particular case is preserved.
$file = $_SERVER['DOCUMENT_ROOT'] . $_GET['category'] . "/" . $_GET['appname'] . "/index.php";
$fileNoPHP = $_SERVER['DOCUMENT_ROOT'] . $_GET['category'] . "/" . $_GET['appname'] . "/index.html";
$_fileExists = file_exists($file);
$_fileNoPHPExists = file_exists($fileNoPHP);
include_once($_fileExists ? $file : $fileNoPHP);
To be clear, my question is: Why is my existing file case appending the GET parameters to the end of the URL, ONLY when the slash at the end is not there?
Thanks for your time. If you need further information, please let me know and I will provide.
The rule that you have is not what is causing the odd looking URL:
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ route.php?category=$1&appname=$2 [NC,L]
This should be fine. Somewhere you are either generating that link or redirecting the browser to that link. If you have a rule that looks something like this:
RewriteRule route.php /%1/%2/ [R=301,L]
You need to remove the query string by adding a ? at the end:
RewriteRule route.php /%1/%2/? [R=301,L]
Or if you're using Apache 2.4, include a QSD flag in the brackets.
If that doesn't solve it, you need to add a rule to ensure a trailing slash gets appended, although it may be an issue with DirectorySlash redirecting for you (which you can turn off).
so my index.php can be this:
<?php
$restOfURL = ''; //idk how to get this
print $restOfURL; //this should print 'FOO', 'VAR3', or any string after the domain.
?>
You want to use,
<?php
$restOfURL = $_SERVER['REQUEST_URI'];
// If you want to remove the slash at the beginning you can use ltrim()
$restOfURL = ltrim($restOfURL, "/");
?>
You can find more of the predefined server variables in the PHP documentation.
Update
Based on your comment to the question, I guess you're using something like mod_rewrite to rewrite the FOO, etc and route everything to just one file (index.php). In that case I would expect the rest of the URL to already be passed to the index.php file. However, if not, you can use mod_rewrite to pass the rest of the URL as a GET variable, and then just use that GET variable in your index.php file.
So if you enable mod_rewrite and then add something like this to your .htaccess file,
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
Then the rest of the URL will be available to you in your index.php file from the $_GET['url'] variable.
Reading $_SERVER['REQUEST_URI'], as everybody has pointed out, can tell you what the URL looks like, but it doesn't really work the way you want it unless you have a way to point requests for me.com/VALUE1 and me.com/VALUE2 to the script that will do the processing. (Otherwise your server will return a 404 error unless you have a script for each value you want, in which case the script already knows the value...)
Assuming you're using apache, you want to use mod_rewrite. You'll have to install and enable the module and then add some directives to your .htaccess, httpd.conf or virtual host config. This allows you make a request for me.com/XXX map internally to me.com/index.php?var=XXX, so you can read the value from $_GET['var'].
$var = ltrim( $_SERVER['REQUEST_URI'], '/' )
http://www.php.net/manual/en/reserved.variables.server.php
Just by looking at the examples, i think you are looking for the apache mod_rewrite.
You can apply a RewriteRule via an htaccess file, for example:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^([\w]+)$ /checkin.php?string=$1 [L]
For example this url http://foo.com/aka2 will be process by checkin.php script and will have "aka2" passed as $_GET['string'].
Make no mistake, the URL will still be visible in the browser as http://foo.com/aka2 but the server will actually process http://foo.com/checkin.php?string=aka
mod_rewrite documentation
$_SERVER['REQUEST_URI']
Why bother with all the fancy mod_rewrite/query_string business? There's already $_SERVER['PATH_INFO'] available for just such data.