URL redirection upon parameters - php

I have a url pattern -- www.domain.info/(unique_number)
for example : http://domain.info/1211.10/09879 where 1211.10/09879 is a unique number
now ,on GET request I want to redirect this url to page.php where page.php will display unique_number's data.
where should i code for getting unique number from url?(i dont want to make directory - 1211.10/09878/)
what is the best way to achieve this ?

To achieve this you must first configure the web server in order to send all requests to the same script, assuming you are using Apache this would be something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ routing.php [QSA,L]
This will send all requests that don't point to an actual file to the routing.php script.
Now in routing.php the identifier can be accessed through the global $_SERVER['REQUEST_URI'] variable:
// assuming the whole URL is http://domain.info/1211.10/09879?someParameter=someValue
$uri = $_SERVER['REQUEST_URI'];
// remove the leading / and parameters:
$uri = substr($uri, 1);
if (strstr($uri, '?') !== false)
{
$uri = substr($uri, 0, strpos($uri, '?'));
}
// Here $uri contains "1211.10/09879" and you can carry on

Related

Create pages from databse Using php [Like what framework or cms are doing ]

Hi i have a database table and a php form in which i can insert table entry . For example i have a form in which i can add post title and post content . So in the table i have 4 column (1)post_id, (2)post_title, (3)post_content, (4)post_url. So currently i fill the form with title="red color" content="red color is so bright and attractive ". so it will store on database.
Now what i need is when there is an entry in table i have to generate page url also . Here it is example.com/red-color.
And some on can take example.com/red-color i need to display the content , and google boot need to automatically fetch through page .
I know this is some complicated process like what wordpress is doing when user insert the content to the post then it will create new page with unique url .
I need only some basic ideas for to proceed .
If anyone know please share the knowledge .
First: you need to have mechanism to redirect all you requests to your router.
In case of Apache you can add .htaccess file with next content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
In case of Nginx (part of sample config, the main logic is in #rewrite stream and try_files directive)
server {
....
location / {
index index.html index.php;
try_files $uri $uri/ #rewrite;
}
location #rewrite {
rewrite / /index.php;
}
## Execute PHP scripts
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
in index.php file you will have access to Path which was originally requested $_SERVER['REDIRECT_URL']
and here(in index.php file): (if that variable set) try to lookup value of $_SERVER['REDIRECT_URL'] in your table, in case if you find that: display title, content and so on.
In case if you can not find it - you should dispaly 404 page (with information that post wasn't found)
In simpliest approach - that is.
Good luck :)
I think you know how to create/insert post in wordpress, now the important part is you want to create custom end-points like frameworks, so in my views you should check WordPress REST API.
Adding custom endpoints, this will give you better idea about it. You can also look at woocommerce end points, how my-account page is created in woocommerce, that is also thee end-point concept.This gist has some code to create custom end point, you can look into it. I have used it in few of my projects, if you need I can share it with you.
In core PHP, you can create routes and handle requests based on URL, HTTP verbs and query parameters.
Basic Example
rotes.php
<?php
$router->define([
'project' => 'controllers/index.php',
'project/about' => 'controllers/about.php',
'project/contact' => 'controllers/contact.php',
]);
Router class
class Router
{
protected $routes = [];
public function define($routes){
$this->routes = $routes;
}
public function direct($uri){
if ( array_key_exists($uri, $this->routes) ){
return $this->routes[$uri];
}
throw new Exception('No routes defined!');
}
public static function load($file){
$router = new static;
require $file;
return $router;
}
}
index.php
<?php
require 'core/bootstrap.php';
require Router::load('routes.php')->direct(Request::uri());
boostrap.php
<?php
$app = [];
$app['config'] = require 'config.php';
require 'core/Router.php';
require 'core/Request.php';
require 'core/database/Connection.php';
require 'core/database/QueryBuilder.php';
$app['database'] = new QueryBuilder(
Connection::make($app['config']['database'])
);
Request Class
<?php
class Request
{
public static function uri(){
return trim($_SERVER['REQUEST_URI'], '/');
}
}
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /project/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
#RewriteRule ^(.*)project/(.*)$ /index.php [L,R=301]
</IfModule>
If you look boostarp.php that will give you folder structure and I hope this will give you idea about routing and MVC.
You may like to remove project/ if you do not want it inside folder or you have created a virtual host (in your local machine).
Have you checked this link https://developer.wordpress.org/reference/functions/wp_insert_post/, Also make sure the pemalink structure is set in wp-admin
$color = "red color" ;
$content = "red color is so bright and attractive ";
$slug = "red-color";
$postarr = array('post_title' => $color,
'post_content' => $content,
'post_name' => $slug
);
// The post ID on success. The value 0 or WP_Error on failure.
wp_insert_post($postarr)
First, for "Clean URL", you need edit .htaccess file :
RewriteEngine On
RewriteRule ^([^/]*)$ /showpage.php?page=$1 [L]
Script showpage.php :
<?php
IF (isset($_GET["page"]))
{
$URL=$_GET["page"];
$DTB->new mysqli($Mysql_Server,$Mysql_User,$Mysql_Password,$Mysql_Database);
$PageData = $DTB->query("SELECT * FROM table WHERE post_url ='URL' LIMIT 1");
IF ($PageData->num_rows>0)
{
$Data=$PageData->fetch_array();
echo('... html code of header etc.');
echo('<body>'.$DATA["post_content"].'</body>');
echo('... html code of footer etc.');
}
else
{
// show error404.page or redirect to index
}
}
?>
I cant help you with google bot "readable", maybe this ?
https://support.google.com/webmasters/answer/76329?hl=en

URL redirect to GET variables

In a PHP website I want to set a redirect if there are variables in the URL inside a specific folder (.com/promo/).
When a user visits:
www.example.com/promo/Marco-Aurelio
Redirect to:
www.example.com/promo/?user=Marco-Aurelio
What PHP code or htaccess rules would you use?
function RedirectToFolder(){
//lets get the uri
$uri = $_SERVER["REQUEST_URI"];
//remove slashes from beginning and ending
$uri = trim($uri,"/");
//lets check if the uri pattern matches the uri or not
//if it doesnt match dont continue
if(!preg_match("/promo\/(.+)/i,$uri)){
return false;
}
//lets now get the last part of the uri
$explodeUri = explode("/",$uri);
$folderName = end($explodeUri);
//lets get the new url
$redirectUrl = "http://www.example.com/promo/?user=$folderName";
Header('Location:'.$redirectUrl);
exit();
}//end function
So just call the function after the php opening tag
RedirectToFolder();
Create .htaccess in the apache DirectoryRoot containing the following:
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/promo/(?![?])(.+)
RewriteRule ^ /promo/?user=%1 [L]
So that the url
http://www.example.com/promo/Marco-Aurelio
Will be redirected to
http://www.example.com/promo/?user=Marco-Aurelio

How to process Clean URLs and Queries?

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

Create blog post links similar to a folder structure

I am currently working on a blog where I would like to create links to my individual articles in the following form:
http://www.mysite.com/health/2013/08/25/some-random-title
------ -----------------
| |
category title
However I have no idea how to achieve this.
I have found something that would give me the URI.
$uri = $_SERVER["REQUEST_URI"];
I would then go ahead and extract the needed parts and make requests against the database.
This may seem a very very dumb question, but I do not know how to look this up on google (I tried...) but how exactly am I going to handle the link ?
I try to explain it step-by-step:
User clicks on article title -> the page reloads with new uri --> Where am I supposed to handle this new uri and how ? If the request path looked like this:
index.php?title=some-random-article-title
I would do it in the index.php and read the $_GET array and process it accordingly. But how do I do it with the proposed structure at the beginning of this question ?
You will need a few things:
Setup an .htaccess to redirect all request to your main file which will handle all that, something like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
The above will redirect all request of non-existent files and folder to your index.php
Now you want to handle the URL Path so you can use the PHP variable $_SERVER['REQUEST_URI'] as you have mentioned.
From there is pretty much parse the result of it to extract the information you want, you could use one of the functions parse_url or pathinfo or explode, to do so.
Using parse_url which is probably the most indicated way of doing this:
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "https" : "http";
$url = $s . '://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
var_dump(parse_url($url));
Output:
["scheme"] => string(4) "http"
["host"] => string(10) "domain.com"
["path"] => string(36) "/health/2013/08/25/some-random-title"
["query"] => string(17) "with=query-string"
So parse_url can easily break down the current URL as you can see.
For example using pathinfo:
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$path_parts['dirname'] would return /health/2013/08/25/
$path_parts['basename'] would return some-random-title and if it had an extension it would return some-random-title.html
$path_parts['extension'] would return empty and if it had an extension it would return .html
$path_parts['filename'] would return some-random-title and if it had an extension it would return some-random-title.html
Using explode something like this:
$parts = explode('/', $path);
foreach ($parts as $part)
echo $part, "\n";
Output:
health
2013
08
25
some-random-title.php
Of course these are just examples of how you could read it.
You could also use .htaccess to make specific rules instead of handling everything from one file, for example:
RewriteRule ^([^/]+)/([0-9]+)/([0-9]+)/([0-9]+)/([^/]+)/?$ blog.php?category=$1&date=$2-$3-$4&title=$5 [L]
Basically the above would break down the URL path and internally redirect it to your file blog.php with the proper parameters, so using your URL sample it would redirect to:
http://www.mysite.com/blog.php?category=health&date=2013-08-25&title=some-random-title
However on the client browser the URL would remain the same:
http://www.mysite.com/health/2013/08/25/some-random-title
There are also other functions that might come handy into this for example parse_url, pathinfo like I have mentioned early, server variables, etc...
This is called Semantic URLs, they're also referred to as slugified URLs.
You can do this with the .htaccess command RewriteURL
Ex:
RewriteURL ^(.*)$ handler.php?path=$1
Now handler.php gets /health/2013/08/25/some-random-title and this is your entry point.

retrieve subdomain as a get variable

Hi guys I'm setting up mywebapplication to give unique urls for users such as uniquename.mysite.com, anotheuniqname.mysite.com etc.
I want to be able to in a php script grab the subdomain part of the url. Would be nice if I can get it as a GET variable - I think it can be done with htaccess. Any ideas?
$subdomain = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], '.'));
To make sure there's a valid subdomain:
$urlExplode = explode('.', $_SERVER['HTTP_HOST']);
if (count($urlExplode) > 2 && $urlExplode[0] !== 'www') {
$subdomain = $urlExplode[0];
}
else {
// treat as www.mysite.com or mysite.com
}
I would try this (at the beginning of your PHP code):
$_GET['subdomain'] = substr($_SERVER['SERVER_NAME'], 0, strrpos($_SERVER['SERVER_NAME'], '.'));
Explanation: strrpos find the last occurance of '.' in the accessed domain, substr then returns the string up to this position. I assigned the return value to a $_GET var so you can use it as if it were a normal URL-parameter.
Put this in your bootstrap file:
$tmp = explode(".", $_SERVER["HTTP_HOST"], 2);
$_GET["subdomain"] = $tmp[0];
Ali - don't you mean a $_SERVER variable as $_GET would be related to the querystring ??
if so, then you could try:
$_SERVER['HTTP_HOST']
jim
[edit] - see http://roshanbh.com.np/2008/05/useful-server-variables-php.html for a few examples that may help
Do you want something along the lines of:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[a-z0-9-]+\.yoursite\.com$
RewriteRule !^index\.php$ index.php [L]
you could then get the subdomain using
<?php
preg_match('/^http:\/\/([a-z0-9-]+)\.yoursite.com$', $_SERVER['HTTP_HOST'], $matches);
$_GET['username'] = $matches[1];
?>
If you really want to use mod_rewrite in your .htaccess file, you could do something like this (assuming your script is index.php in this example):
RewriteEngine On
# Prevent people from going to to index.php directly and spoofing the
# subdomain value, since this may not be a desirable action
RewriteCond %{THE_REQUEST} ^[A-Z]+\sindex\.php.*(\?|&)subdomain=
RewriteRule ^.*$ http://%{HTTP_HOST}/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^www
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^.*$ index.php?subdomain=%1
This little function will simply get your " www.website.com " or in your case " subdomain.website.com ", and then split it up in 3 parts ( 0=>"www", 1=>"website", 2=>"com" ), and then return value 1, which is either " www " or your subdomain name.
function isSubdomain()
{
$host = $_SERVER['HTTP_HOST'];
$host = explode('.',$host);
$host = (is_array($host)?$host[0]:$host);
return $host;
}
Exaple: If your website is " admin.website.com ", you will receive "admin".

Categories