So what I am trying to do is create a website where the index.php will piece all the pages together with based upon parameters sent by query string.
I want to "rewrite" the urls from the form: http://example.com/index.php?p=cat1/page1 to something like http://example.com/cat1/page1
I am attempting to make use of .htaccess mod_rewrite rules, but have been unable to make anything work.
I know there are mountains of info on this stuff.. I have spent a few hours already reading about it and tinkering, but I feel stuck. Nothing I am doing seems to yield any results.
Mod_rewrite IS loaded on the server (says phpinfo())
My .htaccess code:
RewriteEngine On
RewriteRule ^/([home|cat1|cat2]/)?([a-zA-Z]+_?)*/?$ /index.php?p=$1/$2 [L]
My index.php code:
<?php
if (isset($_GET["p"])){
$page = htmlspecialchars($_GET["p"]);
}else{
$page = "home";
}
include('./template/header.php');
if (is_dir("./pages/$page")){
include("./pages/$page/overview.php");
}else{
if (file_exists("./pages/$page.php")){
include("./pages/$page.php");
}else{
//not found
echo '<h1 id="pageNotFound">Page Not Found</h1>';
}
}
include('./template/footer.php');
?>
Here's your .htaccess fix:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !\.(jpg|jpeg|gif|png|css|js|pl|txt)$
RewriteRule ^(home|services)/([a-zA-Z_\-]+)(\/?)$ /NEP2/index.php?p=$1/$2 [NC,QSA,L]
About the PHP, can you move the pages below the public_html folder?
Related
In Node we can get an url address with a structure like this /example/:page/:id and we can take the page and id params. Is there a possibility to do something similar using PHP? Or is it only possible using the "?" with all the wanted params after the interrogation point?
I searched for a while and I tried some configurations in the htaccess file. All of them gave some kind of error like 403, 404 or in one of the configurations the intentioned page was loaded but it didn't find the css, js and images files.
Thanks
Edit:
I will put the solution I found here because maybe it can be useful for someone someday. After looking for some routers packages, I saw them instructing to put these lines in the htaccess file:
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
I've tried something like this before and it was the one that I mentioned in the question that loaded the page but it didn't find the files like css, js, etc.
So I've decide to check the base url and I saw this was the point where the error was coming. After I changed it, the page loaded as the expected and now it's possible to get the value where the users can put a number and redirect to the page that they want (it's something like a magazine).
You can achieve it many ways.
In Laravel (see Documentation). I think every framework now has routing implemented.
Route::get('example/{page}/{id}', function ($page, $id) {
//
})->where(['page' => '[0-9]+', 'id' => '[a-z]+']);
With Mod-rewrite and then with access through $_GET parameters.
RewriteEngine on
RewriteRule ^example/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?page=$1&id=$2 [NC]
You can also redirect everything to index.php and there implement your own router. See: Redirect all to index.php using htaccess
RewriteEngine on
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
Something like this could work
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode( '/', $uri );
// all of our endpoints start with /person
// everything else results in a 404 Not Found
if ($uri[1] !== 'page') {
header("HTTP/1.1 404 Not Found");
exit();
}
For more reference visit this url
https://developer.okta.com/blog/2019/03/08/simple-rest-api-php
have you tried parse_url()?
it will return and associative array which has all the components in your URL
Solved!
first of all, I know I can use "?page=..." but I do not like that variable in my URL. Now after some searching I found a site which uses the $_GET['page'] without showing the "?page=" in the url.
But I'm having a bit of a struggle with the code. I cannot seem to get this code to work. I know it works on an other site, but not on my site. I cannot seem to find how it works on the other site.
this is the menu code:
<li>Home</li>
<li>Even voorstellen</li>
<li>De kennismaking</li>
and this is the php code:
$sExpressie = "(http:|ftp:|shttp:|www.|.php|.pl|.cgi|.asp|index.php)";
if(isset($_GET['pagina']) && eregi($sExpressie,$_GET['pagina']))
{
include("pages/home.php");
}
else
{
if(isset($_GET['pagina']) && file_exists('Pages/' . $_GET['pagina'] . ".php"))
{
include('pages/' . $_GET['pagina'] . ".php");
}
else
{
include("pages/home.php");
}
}
I don't understand how this code works. In my website the "$GET['pagina']" is never filled, which is logical. But how can it be filled in the other website?
Thanks a lot everyone!
Solution:
Add the following to your .htaccess file:
RewriteEngine On
RewriteRule ^([A-Za-z0-9-]+)/?$ pages/$1.php [NC,L]
You'll need to add the following to your .htaccess file:
RewriteEngine On
RewriteRule ^([A-Za-z0-9-]+)/?$ pages/$1.php [NC,L]
For example, if you now navigate to http://yourwebsite.com/fubar, your website will load the page located at pages/fubar.php without changing the URL.
You can use a RewriteRule within your .htaccess file.
For example:
RewriteEngine On
RewriteRule ^/(.*)$ index.php?pagina=$1 [L, QSA] #(.*) is lazy and you may want to just catch [a-z0-9].
This will "rewrite" a request like http://example.com/?pagina=even_voorstellen into something like http://example.com/even_voorstellen. Your index.php can then use $_GET['pagina'] to call the respective page.
Sample Code
Here is a sample of my .htaccess file:
RewriteEngine On
RewriteRule ^home/?$ index.php?intro=true [L]
RewriteRule ^home/([^/]*)$ index.php?location=$1&intro=true [L]
RewriteRule ^wedding/?$ wedding.php [L]
RewriteRule ^wedding/([^/]*)$ wedding.php?location=$1 [L]
And here is some sample code that is featured on both the index.php and wedding.php page:
index.php:
if(!$_GET["location"]) { $location = "London"; } else { $location = ucwords($_GET["location"]); }
[....]
<h1>Ben Pearl, <?php echo $location; ?> Magician</h1>
wedding.php:
if(!$_GET["location"]) { $location = "London"; } else { $location = ucwords($_GET["location"]); }
....
<h1><?php echo $location; ?> Wedding Magician</h1>
What is supposed to happen
The $location string should be effected by the $_GET value 'location'.
What is happening
The rewrite is working fine on index.php; if a user goes to example.com/home/place, $location is replaced by place.
However, on every other page (including the page with script pasted above), the string is replaced by "london", implying that the page hasn't received the $_GET data and the rewrite rule is not working correctly.
What's stranger is that the exact same code, unaltered, worked fine on my localhost.
Try turning off Multiviews, which turns on mod_negotiation's "fuzzy" request URI to file mapping. When mod_negotiation sees /wedding/ and then it sees that there's a file /wedding.php, it'll kick in and send the request directly there, completely bypassing mod_rewrite and your rules.
On top of your htaccess file, add:
Options -Multiviews
That may also explain why it works for the rewrite to index.php, since /home doesn't look much like /index.php (whereas if you had a home.php, mod_negotiation would try to map to that instead).
Normally, the practice or very old way of displaying some profile page is like this:
www.domain.com/profile.php?u=12345
where u=12345 is the user id.
In recent years, I found some website with very nice urls like:
www.domain.com/profile/12345
How do I do this in PHP?
Just as a wild guess, is it something to do with the .htaccess file? Can you give me more tips or some sample code on how to write the .htaccess file?
According to this article, you want a mod_rewrite (placed in an .htaccess file) rule that looks something like this:
RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1
And this maps requests from
/news.php?news_id=63
to
/news/63.html
Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccess file, put the following:
<Files news>
ForceType application/x-httpd-php
</Files>
And then the index.php can take action based on the $_SERVER['PATH_INFO'] variable:
<?php
echo $_SERVER['PATH_INFO'];
// outputs '/63.html'
?>
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like
www.website.com/profile.php?id=username
example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
Simple way to do this. Try this code. Put code in your htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteRule profile/(.*)/ profile.php?u=$1
RewriteRule profile/(.*) profile.php?u=$1
It will create this type pretty URL:
http://www.domain.com/profile/12345/
For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URI to find everything that is in URL.
There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.
One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].
You can easily extract the /path/to/your/page/here bit with the following bit of code:
$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));
From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)
It looks like you are talking about a RESTful webservice.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The .htaccess file does rewrite all URIs to point to one controller, but that is more detailed then you want to get at this point. You may want to look at Recess
It's a RESTful framework all in PHP
I have the following code:
RewriteEngine On
RewriteRule ^user/([0-9]+)/([0-9]+)/?$ template.php?user_id=$1&slide=$2 [NC,L,QSA]
So when I go to www.mydomain.com/user/7/1 it is working, and pulling from www.mydomain.com/template.php?user_id=7&slide=1
Now my question is, how do I get the slide variable to be optional. I want it to work if someone will type in /user/7/.
In my template.php file I have:
if(!$current_slide) {
header("Location: user/".$user_id."/1");
}
So if I manually go to template.php?user_id=1 it will automatically redirect to /user/7/1/ which is good, it works. But I need to modify my htaccess file so if someone types in /user/7/ it will redirect to /7/1/
Hope that makes sense.
RewriteRule ^user/([0-9]+)/?([0-9]*)/?$ template.php?user_id=$1&slide=$2 [NC,L,QSA]