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;
Related
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.
Hello I was trying to come up with the solution to my problem, but I just was not able to. So here is my problem:
What I used was a .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.+(.*)/(.*)$ ./index.php?mesto=$1&den=$2 [QSA,NC,L]
It will display the url well. as www.site.com/CITY/DAY for example ../Prague/30.3.2014 but i need it to be more complex.
What I need is to have additional parameters, such as Bar or Restaurant in the url for example www-site.com/Prague/30.3.2014/p/bar/restaurant and other time I might have www-site.com/Prague/30.3.2014/p/pizza/bar
That part I have no idea how to do, because I have 5 different parameters
I imagine that the raw url would look this index.php?city=Prague&day=30.3.2014&p1=0&p2=0&p3=0&p4=0&p5=0 where p1 to p5 are the parameters being active (0 not 1 yes).
I don't understand how to detect what parameters are active and how to properly display the pretty url. Could you please help me?
Use
RewriteRule ^(.*)$ ./index.php [QSA,NC,L]
This will redirect all your requests to a single index.php that parses the uri with something like this:
<?php
// Example URI: /florence/30-06-2009
// Remove first slash from REQUEST_URI
$uri = substr($_SERVER['REQUEST_URI'],1);
// Get an array with portions between slashes.
$splittedURI = explode("/", $uri);
// Here you get your city (or anything else that you want)
$city = array_unshift($splittedURI); // In example, $city = "florence"
// Remaining itens in $splittedURI are the arguments/parameters to your page
// Like this:
$date = $splittedURI[0]; // In example, $date = "30-06-2009"
?>
Remember that this is just and example, and you should do additional verifications to avoid PHP exceptions.
If you need complicated routing (and if you sure you want to create your own router instead of using a ready solution as ZF, Symfony etc.) you're better off just passing the whole request uri to a php router object. There you can as complex router logic as you need.
So basically, loose the parsing in the rewrite rule:
RewriteRule ^(.*)$ ./index.php?route=$1 [QSA,NC,L]
Then you can let the index.php create a router object that can parse the route parameter and delegate the job where it needs to.
I'd recommend reading up about existing routing solutions though.
How can I make www.mydomain.com/folder/?id=123 ---> www.mydomain.com/folder/xCkLbgGge
I want my DB query page to get it's own URL, like I've seen on twitter etc etc.
This is known as a "slug" wordpress made this term popular. Anyway though.
Ultimately what you need to do is have an .htaccess file that catches all your incoming traffic then reforms it at the server level to work with your PHP in the sense, you will still keep the ?id=123 logic intact, but to the client side '/folder/FHJKD/' will be the viewable result.
here is an example of an .htaccess file I use a similar logic on.. (so does wordpress for that matter).
RewriteEngine On
#strips the www out of the domain if there
RewriteCond %{HTTP_HOST} ^www\.domain\.com$
#applies logic that changes the domain from http://mydomain.com/post/my-article
#to resemble http://mydomain.com/?id=post/my-article
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?id=$1 [QSA,L]
what this will do is take everything after domain.com/ and pass it as a variable to index.php the variable in this example would be 'id' from this you have to device a logic that best suits your sites needs.
example
<?php
//the URL for the example here: http://mydomain.com/?id=post/my-article
if($_GET['id'])
{
$myParams = explode('/', $_GET['id']);
echo '<pre>';
print_r($myParams);
echo '</pre>';
}
?>
now the logic for this would have to go much deeper, this is only pure example at a basic level, but overall and especially cause your working with a database I assume, your gonna wanna make sure the $myParams is clean of malicious code, that can inject into your PHP or Database.
The output of the above $myParams via print_r() would be:
Array(
[0] => post
[1] => my-article
)
To work with it you would need to do at the very least
echo $myParams[0].'<br />';
or you could do it like this cause most browsers will add a final /
<?php
//the URL for the example here: http://mydomain.com/?id=post/my-article
if($_GET['id'])
{
//breaks the variable apart, removes any empty array values and reorders the index
$myParams = array_values(array_filter(explode('/', $_GET['id'])));
if(count($myParams > 1)
{
$sql = "SELECT * FROM post_table WHERE slug = '".mysql_real_escape_string($myParams[1])."'";
$result = mysql_query($sql);
}
}
?>
Now this admitedly is a very crude example, you would want to work some logic in there to prevent mysql injection, and then you will apply the query like you would how you are now in pulling your articles out using just id=123.
Alternatively you could also go a completely different route, and explore the wonders of MVC (Model View Control). Something like CodeIgniter is a nice easy MVC framework to get started on. But thats up to you.
This can be achieved with mod_rewrite e.g. via the .htaccess file.
In your .htacess, you need add RewriteEngine on.
After that, you will need to do some regexs to make this little beast work. I'm assuming ?id is folder.php?id=123.
For example the folder piece: RewriteRule ^folder/([a-zA-Z0-9_-]+)/([0-9]+).html$ folder.php?id=$123
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.
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.