How to take data from URL - php

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];

Related

Is it possible to get URL slash/ parameters with simple php?

is it possible to get parameters like:
index.php/bar/foo with php?
I know that I can use s.th. like index.php?a=bar&b=foo and the user $_GET['a']. But I need to do it with the other way.
The answers here just look like guesses. mod_rewrite presumes apache webserver (we don't know which one you use) and is way too much for this simple task.
Apache's default behaviour is to map index.php/xx/xx to index.php?xx/xx.
Look how easy this is:
$args = explode('/', $_SERVER['QUERY_STRING']);
print_r($args);
EDIT: As DanFromGermany pointed out it is actually possible to have urls like index.php/bar/foo without using mod_rewrite or such. I guess the key here is to have a filename (index.php) in the url.
This has to be done in the web server.
In apache there is a module called mod_rewrite which can rewrite urls like index.php/bar/foo to another format such as index.php?a=bar&b=foo.
Examples, and a description of the topic: http://www.seochat.com/c/a/search-engine-optimization-help/creating-search-engine-friendly-urls-with-php/
What web server are you using?
I used following code to access slash parameters:
$args = $_SERVER["REQUEST_URI"];
$arg_arr = explode("/",$args);
print_r($arg_arr);
Hope this helps someone
To achieve the same either you work on httpd.conf for rewriting the URL or use PHP framework like codeigniter etc. which provide inbuilt functionality.

Use URL segments as jQuery $.post variables

I would like to be able to use jQuery $.post with url segments as follows:
www.mysite.com/stats/user1
www.mysite.com/stats is the landing page, with this code on it:
var user = //get user1 from the url;
$.post('stats.php', {username : user}, function(results){...});
The username should be posted to a PHP backend which then does some database querying.
Is this possible? I might be able to use .htaccess to redirect users from stats/user1 to stats/, but I don't have much experience in this area.
Many thanks in advance for your help.
EDIT
In response to Loopo's answer:
I can use .htaccess to rewrite incoming URLs as follows:
RewriteRule ^/stats/(.*)$ stats.php?username=$1 [L].
This would allow me to enter a URL such as mysite.com/stats/user123, which the server would interpret as mysite.com/stats?username=user123
In stats.php can I then use $user = $_GET['username']?
It seems you are mixing some concepts up.
If you want to pass data to a webserver, you can do it in two ways; POST or GET. (There is also PUT and DELETE but we'll ignore that here.)
If you are using a GET request, the data is in the URL, normally in a format like
mysite.com/mypage.php?param1=value1&param2=value2....
the slashes normally act as a path separator to tell the webserver where to look for the resource that answers the request.
mysite.com/myapp/myfolder/resources/logo.png
would tell the server where to find and then send the file logo.png to the client.
If you want to have parameters in the path, you can also use redirection (.htaccess) to have virtual resources.
as in your example.
www.mysite.com/stats/user1
there is no stats folder with a script for every user.
You'll have to tell your webserver when someone asks for some path that looks like
/stats/<something>
the request should be served by some script (probably 'stats.php') and the parameters that are passed to the script will be <something>
in your .htaccess this might look like:
RewriteRule ^/stats/(.*)$ stats.php/$1 [L]
In a POST request the parameters are not visible in the url.
So your stats.php would have to be called without the username in the URL, but instead in the POST variables, i.e. in your case POSTing to stats.php/user1 and then including the username again in the POST variables is redundant.
So your stats.php could deal with a POST request by reading in the parameters and creating/updating a new user with the values provided in the POST parameters, while dealing with GET requests by returning the user's stats as they are now.
What I am describing is REST, see also

how to use $_GET with this url format site.com/extension/rar

I am seeing this url format at most websites.
site.com/extension/rar
I wonder how they get the value='rar' using $_GET.
What I know is that $_GET can be use in here
site.com/extension/index.php?ext=rar
Now I wanted to change my way of calling a variable.
I wanted to apply what most websites do.
How can I call variable in the former?
Perhaps this works to get the "rar":
$name = basename($_SERVER['REQUEST_URI']);
I most likely being done using .htaccess
It is an Apache module that allows you "rewrite" urls at the engine level based on your own set of rules. So basically it rewrites URLs on the fly.
So, in your example you could have a file named .htaccess with the following contents: (there may be other options)
RewriteEngine On
RewriteRule ^extension/([a-z0-9]+)$ somefile.php?extension=$1 [L]
Basically, you are saying: If someone is looking for a URL that looks like "extension/somenumbers-and-letters" then show the contents of "somefile.php?extension=whatever-those-number-and-leters-are".
Do a search on Apache mod_rewrite to find more information.

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

PHP alter URL without redirecting to it?

How can I alter url or part of it using php? I lost the code that I have used and now I cannot find answer online.
I know using header('Location: www.site.com') gets redirect but how can I just show fake URL?
I don't want to use mod_rewrite now.
It is impossible in PHP, which is executed server side. Any change to the url you make will trigger a page loading.
I think it may be possible in javascript, but I really doubt this is a good idea, if you want to rewrite an url only in the user adressbar, you're doing something wrong, or bad ;)
What you've actually asked for isn't possible in using PHP (Although, in JavaScript you can use the dreadful hashbang or the poorly supported bleeding edge pushState).
However, in a comment on another answer you stated that your goal is actually friendly URIs without mod_rewrite. This isn't about showing a different URI to the real one, but about making a URI that isn't based on a simple set of files and directories.
This is usually achieved (in PHP-land) with mod_rewrite, so you should probably stick with that approach.
However, you can do it using ScriptAlias (assuming you use Apache, other webservers may have different approaches).
e.g. ScriptAlias /example /var/www/example.php in the Apache configuration.
Then in the PHP script you can read $_SERVER['REQUEST_URI'] to find out what is requested and pull in the appropriate content.
You can make somewhat SEO-friendly URLs by adding directories after the php script name so that your URLs become:
http://yoursite.com/script.php/arg1/arg2
In script.php:
<?php
$args = preg_split('#/#', $_SERVER['PATH_INFO']);
echo "arg1 = ".$args[1].", arg2 = ".$args[2]."\n";
?>
if you use some more htaccess trickery, then you can make the script.php look like something else (see #David's answer for an idea)
You can try using,
file_get_contents("https://website.com");
This is not going to redirect but fire the api and you can catch the output by assigning a variable to above function.

Categories