.htaccess rewrite with WordPress plugin - php

I am working on building a WordPress plugin for a custom WordPress multisite network and have a few files that use URL variables to load information from a second database (not the WordPress database).
In the version built outside of WordPress by navigating to http://website.com/NAME-HERE it would check to see if it is a username in my database, if not check to see if its a group in my database and load the file that corresponds to if its a username or group.
Now I'm totally lost about implementing this into WordPress Multisite. As far as I know plugins can't make .htaccess rewrites? How do I make it work on all the network sites?
If not whats the best way to accomplish this?
Do I need to place my pretty.php & .htaccess rewrites into my root directory and point the pages to the files located in the plugin? If so how does this work with multiple themes?
At this point I figured my best bet was to reach out to the StackOverflow community for assistance or direction.
.htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(\w.+)$ ./pretty.php?pretty=$1 [QSA]
ErrorDocument 404 /404.php
pretty.php
// First check if passed pretty parameter is a username.
if(checkIfUserByUsername($_GET['pretty']))
{
$_GET['username'] = $_GET['pretty'];
include("USERNAME.php");
// If not a username, check to see if it's an event.
}else if(checkIfStreamByPretty($_GET['pretty'])){
$_GET['id'] = getStreamIdFromPretty($_GET['pretty']);
include("GROUP.php");
}else{
// If it's none, redirect to the 404 page.
include("404.php");
}

There are a handful of ways you could approach this, if I am understanding what you want to achieve. You likely don't need to use any rewrites.
The easiest solution would be to add your "pretty.php" code to your header.php file in your Wordpress template. This will load on every request to the front end of the website. If you need it to load the code only on a specific page, simply check for what page you are on using is_page.
for example, in your header.php:
if(is_page("groups")){
if(checkIfUserByUsername($_GET['pretty']))
{
// the rest of your code
}
}
If you want to write a Wordpress plugin, you just need to use "add_action" in your plugin:
add_action('wp_head', 'function_containing_your_code');
Again, this will load on every page so simply check that your are on the page you want to load your code on.
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head
https://developer.wordpress.org/reference/functions/is_page/
Also, you can edit your .htaccess file just like you can edit any file that your user has permission to edit. Assuming you are running an apache server, your .htaccess file needs to have permissions that allow the file to be edited and you can edit the file with PHP. for example:
$file = fopen("/path/to/.htaccess", "a+");
fwrite($f, "RewriteRule ^(\w.+)$ ./pretty.php?pretty=$1 [QSA]");
fclose($f);
Many people would say that it is a security risk to have PHP writing to your .htaccess file. I would say that in some circumstances that is true, but certainly not always. Make you understand permissions before allowing PHP to write to your .htaccess file.

In addition to John Gile's answer please sanitize the Get parameters. You can read about some sanitizing option's here
In your questions context something like $username = sanitize_text_field( $_GET['pretty'] ); Should be sufficient. But please take a deeper look at what needs sanitizing.
Regarding your original Question the first approach John suggested seems to be the better one.
Consider the moment two separate request are requesting the same url with the same username. Since File Reading/Writing is a blocking Stream one of the requests have to wait for the stream to close and the website won't render until this happens.
If you bypass this with an additional stream or whatever your risking to end up with duplicate entries or worse a corrupted file which could lead to Server Errors.
Edit
I'am not quite sure what you are trying to achieve with including include('USERNAME.php') are you creating a dedicated php file for every user that signs up for your "multi-site network"? If that is the case I think you made wrong decisions when planing this.
Usually when you want to share, control or alter behavior depending on external resources you'd fetch data in the JSON data format.
Now if I were in your shoes I'd create a REST web service that returns the JSON depending on the username get parameter and control the output depending on the data coming in.
Creating a api is rather complex and depending on your needs you'd go with whatever tool fits these best. I personally enjoyed working with apigility for rather complex things and lumen for small things. You can also create this yourself if you choose, too.
After creating the api you then could easily get the JSON with file_get_contents() described here or use whatever rest tool you can find for php.

Related

how to Blog urls work?

Hello guys I was wondering how blog articles work I mean they are stored in a database right? so how come when I go to an articles its like this:
www.something.com/seths_blog/2015/02/shoes-that-dont-fit-and-free-salt.html
for example I mean do they use php create and create these blogs on files on there htaccess or there is a way to do it efficiently I mean they got to put in it in a Database because sorting comments and so are much more efficient rating and such or polls are well really need the answer thank you
Edit your .htaccess file to add this:
#forward all traffic to index to be handled there except resources
RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.js|\.css)$
RewriteRule (.*) index.php [QSA]
Note that any other file types you don't want to be forwarded will need to be added to the list of file types above. What this line is doing is forwarding all file requests to your index.php file except the ones you declare (like images).
Next, go to your index.php file and add this code:
echo "My URL is:" . $_SERVER['REQUEST_URI'];
This is the basic answer. Now, any question you have beyond this is a matter of basic PHP (and probably MySQL). You can manipulate that data in a limitless combination of ways.

A Dynamic website using PHP

I am a beginner PHP programmer. I searched google for a "Dynamic PHP website tutorials". I found some stuff. They use $_GET variable to make the website dynamic, so the URL's appear like this:
example.com/?page=home
example.com/?page=about
example.com/?page=Downloads
and so on...
But most of the dynamic websites that I found on the internet has links like this:
example.com
example.com/about
example.com/download and so on....
So how do they do so ?? Have they got folders for all the catogories ?? And Also some websites have article URLs (eg : example.com/articles/posts/2010/article1.php). It would be a reall mess if they've got folders for all items. If not then How ?? Can someone give an example please ?
If you're using apache then read: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
If you're using IIS then read: http://www.iis.net/downloads/microsoft/url-rewrite
In order to use the $_GET variable, it must be in the query string (or being routed through some other means that isn't 'default').
For example, the URLs you're using would become.
example.com/?page=home
example.com/?page=about
example.com/?page=Downloads
Additionally, you can rewrite URLs using the .htaccess file (http://httpd.apache.org/docs/2.0/misc/rewriteguide.html)
You are interested in page routing.
htaccess and MVC routing may start you down the correct path :)
To echo everyone else, it's called a url rewite.
For example, the url
http://example.com/index.php?ext=blog&cat=news&date=12122012
can be rewritten as
http://example.com/blog/news/12-12-2012
This isn't automatic, it requires defining the patterns used for understanding the new URL in a file called .htaccess which usually resides in the servers root directory. Note that the preceding '.' in the filename makes it a hidden file.
When I was first getting used to PHP i found the site http://phpbuilder.com a great help. They have a lot of articles, and a forum that is fairly nice to noobies. http://devshed.com is a good site too, and has a large amount of information on subjects outside of PHP.
You can achieve that affect with folders, but most use rewrites (Apache). It's a bit too broad of a subject to go in to here, but if you just search for rewrite tutorials you'll find some pretty quickly.
The $_GET is only to get variables from the URL. While this can be used to make sites dynamic, this is a technique which is usually frowned upon.
With rewrites, you basically have a URL like /about, but the rewrite tells your server something like "act like this is actually ?page="about"), which you then use the $_GET to process.
Being PHP beginner I will not urge you to use .htaccess, As you will need to learn lot many things before you proceed further. You have 2 option to send a request one is GET and POST. You can get more information about same on internet.
Also you have an option to start your dynamic website using CMS and I will recommend you to use wordpress. CMS will have some in-built function which will help you to do your work faster. Also using their control panel you can update the URL format.
I will also urge you to go step by step and follow every tutorial that you will find on internet.
All the best
If you want to do this you have to use .htaccess file and have to load mod_rewrite in your apache server.
In you root directory create file named .htaccess
Then Write:
RewriteEngine On
RewriteRule ^(.*)\.php$ index.php?page=$1 [L,QSA]
And After that call a page
my-page.php
It will redirected as a index.php?page=my-page internally but in browser it will show as my-page.php

Dynamic Website while still being SEO compatible [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.htacces to create friendly URLs. Help needed
I would like to have create a website, which loads up content from a MySQL database via PHP, while still being optimized for search engines.
I have considered a few approaches and was looking for some advice on which way would the best.
Users on my website would fill out a form and submit it, which gets saved in the SQL database. I would like to have it so that each new page could be accessed like this:
domain.com/plugins/whatever
domain.com/plugins/anotherpagename
Some approaches:
1.
A script generates a static HTML page in the plugins folder when the form is submitted. When the page is edited (there will be a edit button), the HTML page gets overwritten with the updated information.
domain.com/plugins/whatever and domain.com/plugins/anotherpagename would all redirect to a PHP script.
However, I do not know how to create a .htaccess which would allow the PHP script to get the page name so that it can search the SQL database and bring up the correct information.
I am also unsure about how search engines would treat these pages?
Maybe someone else can come up with an even better approach for this?
Thank you in advance for your help.
You have a few options for how to do this. The simplest way that matches your requirements would be to add the following to your .htaccess file:
RewriteEngine on
RewriteRule ^/plugins/(.*)$ /yourscript.php?plugin=$1 [L]
The above pass all requests to /plugins/anything to yourscript.php, from which you can access the plugin name using $_GET['plugin'].
If "plugins" is simply an example, and you want to be able to use /anything/anything - then you may wish to look at passing all requests to your PHP script, and then parsing the requested URL.
To do that, you'd use something like this in your .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /yourscript.php [L]
To break that down, the above tells Apache to rewrite all requests where the file does not exist (i.e. images/css/js, etc.) to yourscript.php.
From there, you can access the whole URL via $_SERVER['REQUEST_URI']. Which you can break down with string functions, regular expressions, and so on.
why not make an actual directory ?
Eg.
domain.com/plugins/whatever
domain.com/plugins/anotherpagename
whatever and anotherpagename would both be directories.
Then write the html file as index.html inside the directory.
No htaccess needed and you could still access using the same url as above.
I don't know if you are using any framework. I have solution using codeigniter. The same can be simulated using other frameworks / core PHP.
codeigniter specific solution:
In config/routes.php define
$route['plugins/(:any)'] = "plugins/getPageFromDb/$1";
After this, in browser the url will be same 'domain.com/plugins/whatever' but actually control will hit 'getPageFromDb' function of the 'plugins' controller with 'whatever' as the parameter.
In 'getPageFromDb' function you should write your code to get the page from db based on the parameter 'whatever' and echo the output directly or through a view template (depending on your logic / scenario).
And for performance you may keep a static version of the html page and write a relative check in the 'getPageFromDb' function to decide whether to get the page from static or from db.
Considering the url format and the well formed HTML rendering, it should be Search Engine friendly page.

php based website that displays page content based on URL?

I would like to make a website that is php and only requires one php document to display the content. It's kinda hard to explain, so let me try my best.
Some websites use a directory based system such as this:
web.URL.com/index.htm
web.URL.com/about.htm
web.URL.com/blog.htm
and so on.
This involves creating a text file for each page.
So, the goal here is to create one page that acts like a frame, and displays content based on the Url, so it will be acting like the above method, but is only one page. I'm pretty sure you can do this, but don't know the proper way to word it or what vocabulary to use when typing it in to google.
Some questions you may have:
Q:Why not use parameters like this:
web.url.com?pgid=some+page
A: I would like the url to be as clean as possible when it comes to the visitor typing the url. For example, this is much easier to remember:
web.url.com/about
than this:
web.url.com?p=about
Q: Wordpress??
A: We want our own stuff. Wordpress is great, but not for our project.
Q: JQuery?
A: PHP please.
Thank you in advance!
With PHP alone, I don't think it's possible. However, it's likely that your webserver is running Apache, which makes this task fairly straightforward by transforming your pretty URLs into ugly URLs (with query strings) that your PHP script can handle. Your visitors have no idea this is happening; they aren't redirected or anything.
I strongly recommend you take a look at this tutorial, and its followup. The second tutorial contains the information you need for this task (starting in this section), but I strongly recommend reading the first tutorial to gain a deeper understanding of what you're doing.
Essentially, those tutorials will teach you how to specify (ugly, scary-looking) URL-rewriting rules in a file called .htaccess. These rules will transform (or "rewrite") your pretty URLs into less pretty ones that your PHP script can handle.
For example, yoursite.com/about would actually be accessing yoursite.com/index.php?page=about, or something along those lines.
For some sample code, here's a snippet 95% copied and pasted from this tutorial:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
As that link explains, it will forward all requests to index.php, unless an actual file or directory is being requested.
Use a RewriteRule based .htaccess. Then you can have all non-existing files redirected (internally in Apache) to a general index.php with the requested path as a query string ?p=about. The redirecting is handled internally, so http://example.com/about is the external URL to that page.
You can have a switch statement checking $_GET values and output the page based on the provided parameter. Also, you will have to add some mod_rewrite rules to route those requests.
Use PHP URL rewrite. PHP will enteprate part of your URL as query string

could somebody explain to me how to use mod_rewrite to create pretty permalinks like wordpress does?

i am writing a site from scratch using php/mysql and am using GET requests to pass data between the pages.
at the moment my links look like:
http://pkh:55/?service=213971&type=FSD
but i would like to use mod_rewrite to make them more relevant, ie:
http://pkh:55/FSD/services/football-youth-club/
i've had a look through the wordpress code but i'm none the wiser.
please help!
thanks :)
Assuming that your site is currently working by outputting and accepting the first type of link. The basic process is this...
ensure you have a method in your application for associating 'football-youth-club' to the same set of information you retrieve with '213971'. Generally this means adding a permalink field to the database table.
update processing of your $_GET information to use the permalink field in your database rather than the id. So that your links will look like...
http://pkh:55/?service=football-youth-club&type=FSD
update outputting of all links on your site so that it outputs the second format.
create the mod_rewrite rules to map this pretty format to the functionality you have implemented...
RewriteEngine On
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteRule ^([a-z-A-Z0-9-]+)/services/([a-z-A-Z0-9-]+)/? /?service=$2&type=$1
Please check this website. This is one of the greatest sites I've ever discovered. Please read thoroughly & do some testing simultaneously, so that you can get a grip of what's going around & how to get what you want.
Also make sure that the hosting server has provided permission to use HTAccess & MOD_REWRITE, because some servers don't provide this permission by default. If this is case, then you need to send a request to the server administrator right away, asking him to provide permission to use MOD_REWRITE & HTAccess.
Hope it helps.

Categories