Get a sub-directory folder in the URL and echo it . - php

How do I get the value of an URL eg. www.example.php/folders/crowd? I'm trying to echo out crowd with PHP. I have tried using the $_SERVER ['SCRIPTNAME'] but I really cant get it to work.

To get the current directory of the file (which is just "crowd" in your "www.example.php/folders/crowd" example), use:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))
If you just want the file, then try this:
$cur_file = $_SERVER[PHP_SELF];

You can use parse_url, because scriptname will return the real php file execution "index.php" for example.
php > var_dump(parse_url('http://www.example.php/folders/crowd', PHP_URL_PATH));
// "/folders/crowd"
But if you want just the last part you can:
$tmp = explode('/', 'www.example.php/folders/crowd');
var_dump(end($tmp));
// "crowd"
Or another way:
var_dump(basename(parse_url('http://www.example.php/folders/crowd', PHP_URL_PATH)));
// "crowd"

Maybe you want to have a look at the Apache module mod_rewrite. Many web hosting provider offer this module. If you even operate a dedicated server owned by you, it's no problem to install / enable this module.
mod_rewrite can be used to transparently "transform" request URLs to requests for defined php scripts with query string parameters derived from the original request. This is often used for SEO-friendly URLs like http://mywebpage/article/how-to-cook-pizza-123.html. In this case a script might be invoked taking only the 123 from the URL as a parameter (e.g. http://mywebpage/article/how-to-cook-pizza-123.html => /article.php?id=123).
In your case you could use a configuration like this (put this into an .htaccess file or your Apache/vhost configuration):
RewriteEngine on
RewriteRule ^folders/[A-Za-z]+$ showfolder.php?user=$1 [L]
Your showfolder.php might look like this:
<?php
if (isset($_GET['user'])) {
echo htmlentities($_GET['user']);
} else {
echo "No parameter found.";
}
?>
Any word after folders/ that consists of letters (A-Z and a-z) will be taken as the user parameter of your php script. Then you can easily echo this value, fetch it from a database or whatever. For example, a request for /folders/crowd will result in your script being executed with this parameter: showfolder.php?user=crowd. The user of your website won't see anything of this hidden internal forwarding.
If you use some other web server software (nginx, ...): There are similar modules for other web server products, too.

Related

How to take data from URL

I am developing API for my company. Normally, we use POST & GET method to send form data to other website or another page. But what I want, If we want to send data in URL like
http://www.example.com/data1/data2/data3
like that.
In that case, Data1, Data2, Data3 is our data and I want this data in PHP.
I am searching on that but I can't find what I want.
Look into Apache mod_rewrite (http://httpd.apache.org/docs/current/mod/mod_rewrite.html).
You can rewrite data1/data2/data3 into ?thing1=data1&thing2=data2&thing3=data3, then use $_GET like you usually would...
What you are looking for is called URL Rewriting which is supported by all major Web Servers like Apache and NGINX.
To read more about URL rewriting in apache go thorugh:
https://code.tutsplus.com/tutorials/using-htaccess-files-for-pretty-urls--net-6049
To read more about neat urls in NGINX go through https://serverfault.com/questions/653177/clean-url-with-several-params-in-nginx
In apache servers clean URLS can be achieved by enabling a module called mod_rewrite and a simple way to do it is using the .htaccess file.
In nginx you can use web.config file.
After having clean URL's you can use any method from GET,PUT, POST, PATCH, DELETE etc. but remember if the user enters your URL in your browser then it is always a GET request by default.
you can do it by simply fetching the entire URL and preg_split() the string as below code
$path = $_SERVER['REQUEST_URI']; // this gives you /folder1/folder2/THIS_ONE/file.php
$folders = preg_split('/', $path); // splits folders in array
$what_we_need = $folders[3];

Serve webpages with PHP, WordPress style

For a "classic" website, one would create a /foldername/index.php for every web page. With WordPress, however, this is not the case. For example, if a page was created with WordPress whose URI was http://myblog.org/some_page, you would not find the folder www/myblog.org/some_page in your web host's FTP.
My question then, is, How can I serve up pages located at http://[MY_WEBSITE].com/[page_name] for any arbitrary page_name, without creating a new folder for every page_name?
One method would be to use the page_name as parameter to a common file and use that to serve the contents of the required page.
That behaviour is handled (in an Apache server) by a .htaccess file, wherein rewrite rules are defined. Rewrite rules basically capture incoming traffic and directs those requests to a file on the server (typically a single page which will act as a router).
The router is then responsible for taking the input URI (usually via $_SERVER["REQUEST_URI"] in PHP) and working out what to do with it, and ultimately what the output will be for that request.
As for a decent router, you could look at klein.php. Also, a brief example:
# htaccess file
RewriteEngine On
RewriteRule ^[^\.]+$ index.php
And the index.php:
$route = $_SERVER["REQUEST_URI"];
if($route === '/home')
{
echo 'This is the homepage';
}
You tell your server to rewrite the URL. Most servers do it in their own way, so to find out how to do it look at your server's documentation.
Wordpress uses templates that make use of the require() function and a foreach loop commonly called "The Loop" to retreive content.
Different pages are called using different templates. If you want to know exactly how this logic is calculated, look into this.

How can I create a URL rewrite similar to Wordpress in my own PHP app

I am working with PHP5.3.6 on Windows 2008R2.
In Wordpress, I can set all kinds of friendly URLs which ultimately route to one PHP page. From the outside, it looks like many pages, but is only one.
In the web.config file (or .htaccess) file, there is only one instruction as opposed to having one entry per page/article.
This means that somewhere PHP is looking at the URL, comparing it to the database (where the article titles exist) and then routing transparently to the page.
All of this is transparent to the end user.
How is this accomplished in a non wordpress PHP site?
Here's a related answer that touches on how to do that. In brief, you'll want to check the $_SERVER['REQUEST_URI'] and just parse that.
Here's a simple example of parsing the request (MVC routers are usually configurable, and can route and match for many different URI structures):
If your format is something like news/article-slig you can do this (example code, there are less rigid ways to do this):
list($section, $slug) = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
At this point your PHP script knows how to interpret the request. If this were a full blown MVC application, the router would load the matching controller and pass the request data to it. If you're just doing a simple single page script, loading some data, then your DB calls would follow.
If the request is invalid, then a simple header() call can notify the browser:
header('HTTP/1.0 404 Not Found');
And any data output would be the content of your 404 page.
I can't vouch for wordpress, one method I have used is to redirect 404's in .htaccess to index.php and then have that file sort by parsing:
$sub = $_SERVER['SERVER_NAME'];
$file = $_SERVER['REQUEST_URI'];
$sub can be used to mask non existant subdomains to a specific file. $file can be used in a switch or if clause to include / redirect based on file name.
Obviously, you need to make sure that the alias' are not actual files in your doc root.
Its called Routing(you can also check info about Front Controller pattern). You can write your own implementation by redirecting all your requests to single file using server settings and parse request in this file. You can also check, for example, Zend_Controller_Router docs and sources to understand how it works.
http://framework.zend.com/manual/en/zend.controller.router.html
http://framework.zend.com/manual/en/zend.controller.html

Return current web path in PHP

Currently developing a PHP framework and have ran into my first problem. I need to be able to drop the framework into any folder on a server, no matter how many folders deep, and need to find that directory to use as a base URL.
For example, it currently works if I put the framework in the root of the server (http://cms.dev/), but if I were to put it in http://cms.dev/folder/ it does not work.
There are four existing answers, but they all seem to deal with file paths, and you're asking about a base URL for web requests.
Given any web request, you get a bunch of keys in $_SERVER that may be helpful. For example, in your mock example, you might have the following:
http://cms.dev/folder/ — $_SERVER['REQUEST_URI'] == /folder/
http://cms.dev/folder/index.php — $_SERVER['REQUEST_URI'] == /folder/index.php
http://cms.dev/folder/index.php/some/pathinfo — $_SERVER['REQUEST_URI'] == /folder/index.php/some/pathinfo
http://cms.dev/folder/some/modrewrite — $_SERVER['REQUEST_URI'] == /folder/some/modrewrite
Thinking critically, how would you pull out the base URL for any given subrequest? In certain cases you can look at $_SERVER['REQUEST_URI'] and strip off trailing elements if you know how deep in your hierarchy the request is. (For example, if your script is two folders deep, strip off the last two path elements.) When PATH_INFO or mod_rewrite are in use, things become less clear: as longer and longer URLs are provided, there is no clear indication where the paths end and the dynamic URL begins.
This is why WordPress, MediaWiki, phpBB, phpMyAdmin, and every application I've ever written has the user manually specify a base URL as part of the application configuration.
__FILE__ is a magic constant that returns the entire path of the current script. Combine with dirname and add ".." appropriately. It's more reliable than getcwd, since it cannot change during execution.
You can then strip off the web root, to get the relative path to your script (should map to URL). There are many $_SERVER variables that have this information. I suggest using the file system to determine:
If your script is publicly accessible?
At which depth / URL prefix?
Then combine with your base URL. If your script's path ==
/home/public/foo_1/script.php
... and your $_SERVER['DOCUMENT_ROOT'] ==
/home/public
Then you can rewrite your URL as /foo_1/script.php. You don't need the fully qualified URL, unless you want it. This technique works best if you execute it from a central location, like an autoloader.
In order to make urls work check the base tag:
<base href="http://cms.dev/folder/" />
If the PHP file paths are the issue go with Pestilance's advice:
dirname(__FILE__) // returns the directory of current file
Theres a bunch of useful stuff available for things like this in the $_SERVER array. Do a var_dump($_SERVER); to see which element(s) of the array you need.
dirname(__FILE__);
basename(__FILE__);
print_r($_SERVER);
pathinfo('www/htdocs/index.html');
realpath('../../dir1/');
parse_url('http://username:password#hostname/path?arg=value#anchor');
What you are looking for is the WEBROOT of your application based on your description. The checked answer is, by far, the closest answer.
The easiest way to identify the webroot is to have it be user defined, as was mentioned by Annika and noted in a comment.
However, there is a bit of information that was overlooked:
If you are trying to identify the location of the webroot, which coincidentally is also the top level of your framework, then you could use something like this:
$web_only_path = dirname($_SERVER['PHP_SELF']);
This will only work if your rewrite conditions are implemented correctly.
If they are in an htaccess file, no sweat.
However, if they are in an apache conf file. Then they must be contained within a container for the SERVER variable to store and return the proper information after working through the redirects when dealing with the SEO friendly URLs.
See:SCRIPT_NAME and PHP_SELF with mod_rewrite in .conf
To get the current path of the file you must use:
$path=getcwd();
This will return you if in windows for example C:\blah\blah\blah with no file name.
Sounds like you are looking for the relative path.
$_SERVER['SCRIPT_FILENAME']
should do the trick. The php.net site has good documentation on what is available to that http://php.net/manual/en/reserved.variables.server.php
Also, if you are ever curious about what else is there, and what the values are
<?php print_r($_SERVER); ?>
will tell you more that you thought you could know.
function GetCurrentWebDir() {
$CurrentPath = substr(
$_SERVER['SCRIPT_URL'], 0,
strlen($_SERVER['SCRIPT_URL']) - strlen(
strrchr($_SERVER['SCRIPT_URL'], "\\")
)
);
$CurrentFileName = basename(__FILE__);
return substr_replace(
$CurrentPath, '', -strlen($CurrentFileName),
strlen($CurrentFileName)
);
}
echo 'current dir:'.GetCurrentWebDir();`
cp:/apps/PHP/testtesttesttesttesttesttesttesttesttesttest.php
fn:testtesttesttesttesttesttesttesttesttesttest.php
len:48
current dir:/apps/PHP/
Use dirname(__PATH__) to fetch the parent directory path.

Can PHP 5 do request handling similar to Tomcat or GAE?

lets say i want to go to
http://example.com/something/a/few/directories/deep
is there a way I can process this in PHP without having to make those directories? I just want to get everything after the domain name as a variable and work from there.
The most common way of doing this is by using mod_rewrite. (There in an introduction to this at http://articles.sitepoint.com/article/guide-url-rewriting). This allows you to internally map these friendly URLs to query parameters passed to your PHP script.
Sure. You don't even need mod_rewrite if the beginning is constant or has only a few possible values. Make a php file named something (no extension) and tell Apache (via a SetHandler or similar directive) to treat it as PHP. Then, examine $_SERVER['PATH_INFO'] in the script, which will look like a/few/directories/deep IIRC. You can use that to route your request however you like.
Alternatively. as Martin says, use a simple mod_rewrite rule to rewrite it to /dispatch.php/something/a/few/directories/deep and then you have the whole path in PATH_INFO.
You do not need mod_rewrite to handle such a scenario. Most of the popular PHP frameworks currently support URI segment parsing. This is a simple example which still leaves a few security holes to be patched up.
You could handle this by taking one of the global $_SERVER variables and splitting it on forward slashes like so:
if (!empty($_SERVER['REQUEST_URI'])) {
$segments = explode('/', $_SERVER['REQUEST_URI']);
}
The $segments variable will now contain an array of segments to iterate over.
Assuming you are using apache...
Add a re-write rule (in your vhost conf or just drop .htaccess file in you doc root), to point everything to index.php. Then inside of your index.php, parse the request uri and extract path
RewriteEngine on
RewriteRule ^.*$ index.php [L,QSA]
index.php:
$filepath = $_SERVER['REQUEST_URI'];
$filepath = ltrim($myname, '/'); //strip leading slash if you want.
This actually is not a PHP5-related quesion - URL rewriting is part of your webserver.
You can, when you use mod_rewrite on Apache (don't know about IIS, but there likely is something similar).

Categories