I see this alot appended to the url of a website, and when the step changes so does the page content. can anyone explain this to me in php.
I do not understand how it works.
The numbers of the step are $_GET variables. For example if your link is www.yourdomain.com/index.php?step=3 you can fetch this step by writing (in index.php):
<?php
$step = 0;
if (isset($_GET['step']))
$step = $_GET['step'];
?>
This declares a variable named $step and assigns the value from your URL to it (if any is set, else it's just 0).
You can then use this step variable value to show a specific page to your user. For example by fetching data on the flow from a database.
If you wan to transform this url:
www.yourdomain.com/index.php?step=3
into something nicer like
www.yourdomain.com/step/3
you will have to make use of a .htaccess file. They allow you to rewrite URL's, but as that can be pretty complicated I advise you to look around on the internet for more information about them. Such as here.
This is url rewriting.
You can do that via a .htaccess file with RewriteRule.
For exemple you can transform a url like http://example.com/a/b into something like http://example.com/script.php?arg1=a&arg2=b.
Often there is some magic URL rewriting happening behind the scenes.
This mostly just does something like this (taking your example):
request url: www.example.com/1/2/3/4
rewritten url: www.example.com/handler.php?a=1&b=2&c=3&d=4
So basically you are (often) not browsing any directories, the url YOU see is just to make it a little bit more attractive than what the SERVER sees.
Related
I am using ModRewrite as below to convert urls on my site to be SEO friendly:
RewriteRule user/(.*)/$ seo-url-user-by-name.php?username=$1
Now I am writing code for seo-url-user-by-name.php and am looking for a way in PHP to redirect to:
user.php?uid=<uid>
so that seo-url-user-by-name.php will essentially return the contents of user.php?uid=<uid> BUT without changing the address in address bar to user.php?uid=<uid>
How do I do that?
Simply include user.php in seo-url-user-by-name.php. To get the querystring right you have to overwrite the value in $_GET.
$_GET['uid'] = 'whatever you want';
include 'user.php';
You're going about it backwards. The only URLs your code should be outputting are the 'friendly' ones. Those are the urls that will appear in the produced HTML and what will show up in the user's address bar.
e.g.
Bad URL (URL #1)
This URL is fine (URL #2)
You should never output anything but URL #2's. It'll be your server's responsibility to convert that clean (and in real terms, non-existent) URL to whatever really is on the server. PHP itself should never care nor see the /user/foo URL. PHP will be invoked as /user.php?id=foo as usual, and go about its business as usual.
The remote user would never see that rewriting occurring, they'll just see a request go out for /user/foo.
I would like to be able to use jQuery $.post with url segments as follows:
www.mysite.com/stats/user1
www.mysite.com/stats is the landing page, with this code on it:
var user = //get user1 from the url;
$.post('stats.php', {username : user}, function(results){...});
The username should be posted to a PHP backend which then does some database querying.
Is this possible? I might be able to use .htaccess to redirect users from stats/user1 to stats/, but I don't have much experience in this area.
Many thanks in advance for your help.
EDIT
In response to Loopo's answer:
I can use .htaccess to rewrite incoming URLs as follows:
RewriteRule ^/stats/(.*)$ stats.php?username=$1 [L].
This would allow me to enter a URL such as mysite.com/stats/user123, which the server would interpret as mysite.com/stats?username=user123
In stats.php can I then use $user = $_GET['username']?
It seems you are mixing some concepts up.
If you want to pass data to a webserver, you can do it in two ways; POST or GET. (There is also PUT and DELETE but we'll ignore that here.)
If you are using a GET request, the data is in the URL, normally in a format like
mysite.com/mypage.php?param1=value1¶m2=value2....
the slashes normally act as a path separator to tell the webserver where to look for the resource that answers the request.
mysite.com/myapp/myfolder/resources/logo.png
would tell the server where to find and then send the file logo.png to the client.
If you want to have parameters in the path, you can also use redirection (.htaccess) to have virtual resources.
as in your example.
www.mysite.com/stats/user1
there is no stats folder with a script for every user.
You'll have to tell your webserver when someone asks for some path that looks like
/stats/<something>
the request should be served by some script (probably 'stats.php') and the parameters that are passed to the script will be <something>
in your .htaccess this might look like:
RewriteRule ^/stats/(.*)$ stats.php/$1 [L]
In a POST request the parameters are not visible in the url.
So your stats.php would have to be called without the username in the URL, but instead in the POST variables, i.e. in your case POSTing to stats.php/user1 and then including the username again in the POST variables is redundant.
So your stats.php could deal with a POST request by reading in the parameters and creating/updating a new user with the values provided in the POST parameters, while dealing with GET requests by returning the user's stats as they are now.
What I am describing is REST, see also
i want to build a website with different views, but a stable header and footer - no problem so far. But i dont like the kind of urls i got at the moment with the php GET method.
My site at the moment works like this (what istn working properly):
$_page = $_GET['p'];
if ($_page == "city-sitemap"){ include "views/city-sitemap-view.php"; }
if ($_page == "place"){ include "views/place-view.php"; }
else { include "views/index-view.php";}
this isnt a very sweet solution but i dont know a other for now. I tried to use a mvc framework but failed dramatically. So everytime i add a link i use for example this "index.php?p=place" - not very nice.
The including of the views isn very smart as well? is there a better way?
I would like to use something like the rewriteEngine that the new url is like a folder.
Can you help me to find a better solution?
Thanks a lot
Page including
For the page inclusion, you can use a simple array to dynamically allocate your page to a specific name. As so:
$pages = array('city-sitemap'=>'views/city-sitemap-view.php',
'place'=>'views/place-view.php',
)
if(array_key_exists($_GET['p'], $pages){
include $pages[$_GET['p']];
}else{
include 'views/error.php';
}
This array should be added in a general configuration file. With this configuration if you want to display your city-sitemap-view.php view, you will have to write this url: http://www.domain.com/index.php?p=city-sitemap
Url rewriting
It is possible to rewrite an URL with a .htaccess file. Here is an example of code you would can to write in your .htaccess file.
RewriteEngine On
RewriteRule ^(.*)$ index.php?p=$1 [L,QSA]
An url that looks like this:
http://www.domain.com/index.php?p=city-sitemap
will be converted to this one:
http://www.domain.com/city-sitemap
There is something called the front controller that you should look into. You can write a very simple one yourself. It works in conjunction with URL rewriting. If for example your url looks like this:
/mypage.html
the url rewriter will reroute the request to index.php .
Index.php will then look at the URL and do somehting like this:
1) break the page out into string, ignoring .html extention
preg_match("\/(.*?)\.html", $_REQUEST['URI'], $matches);
$pageClass = $matches[1];
//$pageClass = "mypage"
2) look for and load a class named "Mypage.php"
$controller = new $pageClass();
3) call the run method on the page class, passing it all the request parameters
$request = new Request($_REQUEST);
$controller->run($request);
you can then do all the page specific stuff inside your controller class that is specific to the page.
At each simple step along the way, you will find you want to do more and more things like authentication, filtering, tracking, etc. You will get end up developing a front controller that is specific to your needs, as well as a base Controller class that does a bunch of standard stuff that all your controllers have in common.
As per my comment, i really think you should consider the framework i linked, (it is very logical) or any other micro framework, but if you really wish to do this yourself then you can handle your includes like so:
<?php //index.php
$requested_page=isset($_GET['p'])?$_GET['p']:'home';
//maybe have this included from pages.php for organization
$pages=array(
'home'=>'home_content.php',
'about'=>'about_content.php',
'contact'=>'contact_content.php'
);
include "views/header.php";
if(array_key_exists($requested_page, $pages)){
include "views/".$pages[$requested_page];
}else{
header('HTTP/1.0 404 Not Found');
include "views/error404.php";
}
include "views/footer.php";
This keeps your pages in a single array, and protects against arbitrary inclusion vulnerabilities.
For nicers urls, see The other users .htaccess rewrite rules
How can I alter url or part of it using php? I lost the code that I have used and now I cannot find answer online.
I know using header('Location: www.site.com') gets redirect but how can I just show fake URL?
I don't want to use mod_rewrite now.
It is impossible in PHP, which is executed server side. Any change to the url you make will trigger a page loading.
I think it may be possible in javascript, but I really doubt this is a good idea, if you want to rewrite an url only in the user adressbar, you're doing something wrong, or bad ;)
What you've actually asked for isn't possible in using PHP (Although, in JavaScript you can use the dreadful hashbang or the poorly supported bleeding edge pushState).
However, in a comment on another answer you stated that your goal is actually friendly URIs without mod_rewrite. This isn't about showing a different URI to the real one, but about making a URI that isn't based on a simple set of files and directories.
This is usually achieved (in PHP-land) with mod_rewrite, so you should probably stick with that approach.
However, you can do it using ScriptAlias (assuming you use Apache, other webservers may have different approaches).
e.g. ScriptAlias /example /var/www/example.php in the Apache configuration.
Then in the PHP script you can read $_SERVER['REQUEST_URI'] to find out what is requested and pull in the appropriate content.
You can make somewhat SEO-friendly URLs by adding directories after the php script name so that your URLs become:
http://yoursite.com/script.php/arg1/arg2
In script.php:
<?php
$args = preg_split('#/#', $_SERVER['PATH_INFO']);
echo "arg1 = ".$args[1].", arg2 = ".$args[2]."\n";
?>
if you use some more htaccess trickery, then you can make the script.php look like something else (see #David's answer for an idea)
You can try using,
file_get_contents("https://website.com");
This is not going to redirect but fire the api and you can catch the output by assigning a variable to above function.
I'm trying to put something with this, whenever I go to a page like:
http://www.example.com/character.php?id=3
I want the mod rewrite to change it to:
http://www.example.com/character/Jim_Carrey
Which of course, the ID is the row of the character name...
For that kind of example... I've tried to work with it, but don't seem to get most of the production of htaccess because I haven't worked with .htaccess a lot really.
It's actually the other way around:
On your website, you write all your links the way you want them to look. For instance http://www.site.com/character/Jim_Carrey
In your database, you add a field,
commonly called "slug" or
"post_slug" which refers to the
Jim_Carrey" part of the url. IT MUST
BE A UNIQUE ELEMENT, much in the way
of a primary key. So make sure you
have a function that does take care
of creating the slug based on a
given string (the post title for
example) and making sure there is no
duplicate.
Then in your .htaccess (on the root folder) you do
something like
RewriteEngine On
RewriteRule ^character/([a-z0-9_\-]+)/$ character.php?slug=$1 [L,NC]
Finally, in your character.php
script, you do a database query not
against the ID, but against the
post_slug field.
If you're only using the character's name, then something like the following would do
RewriteRule ^character/(.*)$ /character.php?slug=$1
with a URL of eg http://www.example.com/character/Jim_Carrey. You'll then need to look up the character's name in the database using the slug passed in, as you won't have the ID to look it up with.
Alternatively you could include the ID in the URL if you need it, vis:
RewriteRule ^character/([0-9]+)/.*$ /character.php?id=$1
This way you could have a URL like http://www.example.com/character/3/Jim_Carrey which would include the character name (for SEO reasons etc etc), but also the ID which you could then look up directly in your database.
Edit a small PHP example for you re the first one:
<?php
// ... database connection stuff here etc
$slug = $_GET["slug"];
// IMPORTANT: perform some data sanitization here
// I'm just going to make sure it's only letters, numbers and
// hyphens/underscores as an example.
$slug = preg_replace("/[^a-zA-Z0-9\-_]+/", "", $slug);
// Now look up in your database
// Ideally you'd have a slug column to compare this with, that you can fill
// when your record is created/updated
// You'd also be best off using bound parameters here, rather than directly
// adding the data into the query string. I personally use the MDB2 PEAR
// module but feel free to use whatever you normally use.
$qry = "SELECT * FROM characters WHERE slug='" . $slug . "'";
$result = mysql_query($qry, $db);
// do something based on this result, fail if none found
// or show details if OK etc
// ...
?>
Hope this helps! As always, use bound parameters where possible for your queries, and perform sanitization of your user data well. The PEAR MDB2 module has a nice page on how to do this here.
Edit 2 a quick and dirty setup :-)
.htaccess file as follows:
RewriteEngine On
RewriteRule ^character/(.*)$ /character.php?slug=$1
Your .htaccess file would ideally be in the root of your site. Eg /home/wayne/public_html/ or wherever your index file is served from
A URL to match that would be http://www.example.com/character/Jim_Carrey - with the phrase "Jim_Carrey" appearing in your $_GET array as $_GET["slug"]. NB apologies, wrote that PHP sleepy last night above so no wonder $_POST wouldn't work as its a GET request :-) I've updated it now!
Finally you need to make sure that your host supports the use of .htaccess files. The setup of this is out of the scope of SO so any Apache configuration questions you'd be best asking over at https://serverfault.com/
I'm fairly certain you can't do this through htaccess. You'll need to do it in PHP, querying the database using the information from the url (?id=3) and then calling the Header Function using what you've learned from the database.
Sounds like you might be able to use mod_rewrite rewritemap.