Extract URL slug using PHP. Building a URL shortener - php

I'm building a URL shortening web app using PHP. I am able to generate shorter URLs successfully. But I'm not able to redirect the users when they visit the shortened URL.
If the user enters https://example.com/aBc1X, I'd like to capture the aBc1X. I'll then query the database to find the original URL and then redirect.
My question is, how can I extract the aBc1X from the above URL?
P.S. I'll use either Apache or Nginx.

Two things to do for you.
First you have to redirect all traffic to one file which will be your router file. You can do this by placing a few rules in .htaccess file. I will put there some generic rules to start with (this one come from Wordpress):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^redirect\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /redirect.php [L]
</IfModule>
They tell that everywhere url points to which isn't file or directory will run file redirect.php. You may want to tweak that settings to your needs.
Then in redirect.php you can capture url by looking inside $_SERVER['REQUEST_URI'].
For url http://example.com/any-url-i-want you would have
$_SERVER['REQUEST_URI'] == '/any-url-i-want.
Now the only thing you need is to find the url in database, and do a redirect.
I guess you can handle string operations at this point, either by using parse_url, regular expressions, or simple string cutting.

You want to use;
$_SERVER['REQUEST_URI'];
That will return what you're looking for.
You can see the documentation here

To parse the url
$url = "https://example.com/aBc1X";
$path = ltrim(parse_url($url, PHP_URL_PATH), '/');
Then $path will be aBc1X as desired. Note that any query following a ? will be omitted in this solution. For more details have a look at the documentation of the parse_url function.

Related

changing php function calling URL with mod_rewrite

I've already search for an answer here, but couldn't find an exact answer.
I've got a php application (it uses CodeIgniter) which is connected to our companys Management Database. The application provides information out of the database in xml form so that our internal mediawiki's can receive those and build Info-Boxes (as example) out of them.
I have the following link to my data in xml format:
https://example.com/controller/function/databaseID/short_name or
https://example.com/App/makeInfoBox/258/Applicationname
which contains Infromation as following:
-<infobox>
<id>258</id>
<short_name>Applicationname</short_name>
<long_name>Long Applicationname</long_name>
<app_number>334</app_number>
<status>End of life</status>
...
</infobox>`
I now want mod_rewrite to change the url to:
https://example.com/appInfoBox.xml?id=258&short_name=Applicationname
I've got something like this:
RewriteCond %{QUERY_STRING} ^id=([0-9]+)\&short_name=(.*)$
RewriteRule ^appInfoBox\.xml$ App/makeInfoBox/%1/%2
I'm really not good in mod_rewrite and this code I got is based on a older version of a used .htaccess file.
Any Suggestions? Thanks!
You must capture the relevant parts of the request (...) and use this in the substitution $...
RewriteRule ^App/makeInfoBox/(.+?)/(.+)$ /appInfoBox.xml?id=$1&short_name=$2 [L]
Use the following directives in the .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/App/makeInfoBox/([0-9]+)/(.*)$
RewriteRule ^(.*)$ /appInfoBox.xml?id=%1&short_name=%2 [QSA,R=302]
The .htaccess file should be present in the root folder of example.com.
The RewriteCond directive will check whether the request matches the pattern /App/makeInfoBox/(any-number)/(any-number-of-characters).
IF this is true the RewriteRule directive will map the request to example.com/appInfoBox.xml?id=(any-number)&short_name=(any-number-of-characters) using the QSA flag.
The R=302 flag will cause an external redirect and the end user will be able to see the new URL with query string on the browser.
If you don't want to display the URL with query string to end users, just remove the R=302 flag.
Using your example, now if you will access https://example.com/App/makeInfoBox/258/Applicationname it will redirect to https://example.com/appInfoBox.xml?id=258&short_name=Applicationname

Build PHP page based on url

If you have a url such as the one as follows:
http://www.example.com/400x200
is it possible to create a page which echos out 400x200 when the user visits that url using php?
I know how to echo the path - that is easy enough (ltrim($_SERVER['PATH_INFO'], '/')), but do not know how to create the page dynamically.
Any help would be much appreciated, thanks in advance
The request URI (/400x200) is stored in the server superglobal: $_SERVER["REQUEST_URI"].
You need to take that and route the URI accordingly. The simplest possible scenario: in your index.php, place this code:
$uri = trim($_SERVER["REQUEST_URI"],"/");
if (preg_match("/\d+x\d/")) {
list($width,$height) = explode("x",$uri);
// some logic with the above vars, e.g. include a view script
}
What this does is check whether the URI has the format {number}x{number}, extracts both numbers and stores them in the variables $width and $height. You can then do whatever you like with the variables.
In order to make the request always point to the file containing this code, edit your .htaccess and put in something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
(the .htaccess code is copied from the default Zend Framework project, in case anyone asks).
You may want to look at Apache Rewrites for rewriting your URL:
http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
Do not know what do You mean by creating the page dynamically but I guess that using of mod_rewrite is what You need.
In Your .htaccess file You have to create some rules that will rewrite the URL to something distinguishable by Your PHP script - like from URL
http://www.example.com/400x200
to get
http://www.example.com/index.php?param=400x200
And then You can in Your index.php script do echo $_GET['param'];...
Google something about PHP and mod_rewrite: http://www.google.com/#q=PHP+mod_rewrite
Assuming you're using Apache, this can be done using something called URL rewriting. Create a file called .htaccess in your document root, and add this:
# Turn URL rewriting on
RewriteEngine on
Options +FollowSymlinks
# Rewrite rule
RewriteRule ^(\d+x\d+)/?$ index.php?dimensions=$1 [L]
The first two lines turn the rewrite engine on, and the third line defines a RewriteRule. The first part ^(\d+x\d+)/?$ is a regular expression that the part of the URL after the domain will be matched against.
The second part index.php?dimensions=$1 is the URI that will be rewritten to. The client doesn't see this, but PHP will.
If I do a print_r($_GET) in index.php with the URL http://localhost/400x300, I get this:
Array ( [dimensions] => 400x300 )
This is from the standard $_GET superglobal array in PHP and can be used as normal. URL rewriting leaves the URL as it is in the browser, yet allows you to turn it into one usable by PHP with a query string.
To make your script a bit easier to use, you could split the expression up to get separate X and Y values:
RewriteRule ^(\d+)x(\d+)/?$ index.php?x=$1&y=$2 [L]
Which will give an array like this:
Array ( [x] => 400, [y] => 300 )
Make it a GET variable like
http://www.example.com?size=400x200
Then you can retrieve the String with
$size = $_GET['size'];
What I'd recommend you to do is to get the values based on split or explode()
$lw = $size.explode('x',$size);
$length = $lw[0];
$width = $lw[1];
//Manipulate the values accordingly like
echo $length.'x'.$width;

Can't access post or get from a php page after redirecting

I'am redirecting about 100 hmtl pages to a single PHP page (example.php) using .htaccess. It is working perfectly.
I've pagination on that page (example.php) but I am using the original HTML page URL (example.html?page=2&limit=20)
so example.html, example1.html, example2.html, example3.html are all redirecting to example.php.
The address bar is still showing ".html" URL but due to .htaccess redirection the example.php is rendering.
when is click on a pagination link (example.html?page=2&limit=20) the browser address bar shows correct .html URL and query string.
I've tried to get the values of page, and limit using $_GET and $_REQUEST in (example.php) but i am not successful.
Please help me in reading the (example.html?page=2&limit=20) query string parameeters .
Edit Code ported from comments:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^page-(.*)$
RewriteRule ^page-(.*)$ size-content.php?sef=$1 [L]
Add the QSA flag, which means "query-string append" to be sure the existing query string is ported into the rewritten URL.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^page-(.*)$
RewriteRule ^page-(.*)$ size-content.php?sef=$1 [L,QSA]
.htaccess modify your server configuration.
if you are making redirection then you change your request.
Try mod_rewrite if you are using Apache of course.
RewriteEngine On
RewriteRule ^example\.html\?(.*) example.php?$1
Mod rewrite is module to Apache. It is not allowed on most free hostings.
Yasir - you can resolve this problem by two ways:
1) Re-write rules for .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^page-(.).html(.)/(.)$
RewriteRule ^page-(.).html(.)/(.)$ size-content.php?sef=$1&page=$2&limit=$3 [L]
This rule will handle: page-example.html?page=2&limit=20
I hope - you will easily understand the above rule.
Note: Keep one thing in your mind that every link should be in same pattern if you change rule in htaccess.
2) You can resolve this problem on your "size-content.php"
Suppose page-example.html?page=2&limit=20
$_GET['sef'] = example.html?page=2&limit=20 [according to you .htaccess]
Now you can parse this string via explode function
Thanks

Use SO's URL format for $_GET

StackOverflow has a very neat, clean URL format. It looks the same as a directory structure, but there can't be a directory for each question on here! My question is this:
How can I get http://www.site.com/sections/tutorials/tutorial1, for example, to stay like that in the address bar, but convert it to a $_GET request for PHP to mess around with?
I could use a .htaccess file, but I don't want the URL being rewritten - I'd like it to remain clean and friendly. Is my only option here to use PHP's string splitting functions to get some pretend $_GET data?
Thanks,
James
What about this, using .htaccess to split the URL up, the URL won't change but instead point to index.php with various $_GET variables, this could could be increased to cover more URL sections.
# turn rewriting on
RewriteEngine on
# get variables in this order, [object], [object,action], [object,action,selection]
RewriteRule ^([^/\.]+)/?$ /index.php?object=$1 [L,NC,QSA]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /index.php?object=$1&action=$2 [L,NC,QSA]
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ /index.php?object=$1&action=$2&selection=$3 [L,NC,QSA]
A PHP Rest framework could do this for you, so I refer you to this question. Most of the frameworks won't load the data from $_GET, but will offer a similar and equally convenient way to read it.
It's actually a RESTful way of building your URI's. Not only SO applies this pattern. I recommend to not re-invent the wheel by taking a look at this question.
In addition you could switch over to a RESTful framework such as CakePHP or CodeIgniter, which are configured by default to use the RESTful pattern.
$_GET does not contain the path compontents from the URL, only the parameters that eventually follow the ?. You could use
$parts = explode('/', pathinfo($_SERVER['REQUEST_URI'], PATHINFO_DIRNAME));
var_dump($parts);
However it seems you should have a read on URL rewriting e.g. with mod_rewrite. "I don't want the URL being rewritten - I'd like it to remain clean and friendly" ... The rewriting happens on the server. The user never sees the "ugly" result.
If you don't want to use mod rewrite the best solution would be using regular expressions agains the $_SERVER['REQUEST_URI'] variable.
i.e:
preg_match('|/(.*)/(.*)|', $_SERVER['REQUEST_URI'], $match);
$_GET['param1'] = $match[1];
$_GET['param2'] = $match[2];
If you want to setup a capture all php script. IE if the script request doesn't exist use a default script, use mod-rewrite to redirect everything to one script i.e. the zend framework (and most of the PHP MVC framework) use this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
I think that could be a bit cumbersome.

In PHP, how can I get any string after the domain to be a php variable? Ex: me.com/FOO, me.com/VAR3

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.

Categories