how to get api token in rest api from url - php

I'm trying to develop REST Api with php and I have problem to get api token in my php file but it is consider as folder directory when I requested the Url !
Is there any way to solve this problem ?
e.p. Url that I call :
https://example.com/v1/6A4C426B70634E6D3831785155304F566C6359636167485079494C56624C4C524B686136374E6F6D4D51453D/
note : this is api token : 6A4C426B70694E6D3831785155304F566C6359636167485079494C56624C4C524B686136374E6F6D4D51453D
inside my index.php in "v1" folder:
<?php
//get verify vals
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
$url = "https://";
else
$url = "http://";
// Append the host(domain name, ip) to the URL.
$url.= $_SERVER['HTTP_HOST'];
// Append the requested resource location to the URL
$url.= $_SERVER['REQUEST_URI'];
echo $url;
var_dump(parse_url($url, PHP_URL_PATH));
?>
thanks
i tried to learn about headers !

The cleanest way to achieve this would be to create a .htaccess file at the root of your server, and add this rewriting rule in it:
RewriteEngine On
RewriteRule ^v([0-1])\/([0-9A-Z]+)\/?$ index.php?version=$1&token=$2 [QSA]
Then, in your index.php file, you will simply get the version number in a $_GET['version'] variable, and the token in a $_GET['token'] variable.
Because you apparently want to anticipate having different versions of your API, you could also do this:
RewriteEngine On
RewriteRule ^v1\/([0-9A-Z]+)\/?$ index-v1.php?token=$1 [QSA]
RewriteRule ^v2\/([0-9A-Z]+)\/?$ index-v2.php?token=$1 [QSA]
In that case, you will only have access to the token in a $_GET['token'] variable, the version number being useless to have in a get variable because you would separate the code of your v1, v2 (etc) or your API in two different files.
If you don't know what these special chains of characters are, they are called "Regex" and I encourage you to read/watch a tutorial about it, you can use them in Apache, PHP, JavaScript, ... many languages, and they are a good way to identify simple to complex patterns of strings.

Related

Why use $_SERVER['REQUEST_URI'] over $_GET['url'] in PHP after URL rewriting occurs for an MVC Router?

Apache (2.4.x)
If I establish a rewrite rule in my httpd-vhosts.conf (which is included into my main httpd.conf), within a <VirturalHost> block, like the following (as I see some example and tutorials do, not my idea):
RewriteRule ^(.*)$ /public/www/foo.com/public/index.php?url=$1 [QSA,L]
1) Do I need to specify the absolute path (seems so, as RewriteBase is not appropriate in this context)? It works this way, but I just wanted to know if there was something I overlooked. However, it only works this way because of a dubious suggestion (which seems unacceptable).
<Directory />
AllowOverride none
Require all granted ---> original setting: Require all denied
</Directory>
That seems outrageously flawed and permissive (seems). I really need to study up on the module that implements the Require runtime directive (mod_access, I think).
Is this enough (never works for me within a <VirtualHost> block)? Is it better to put the rewrite rules in .htaccess so that they travel with the application (instead of being coupled to the server)?
RewriteRule ^(.*)$ index.php [L] -->Wihout QSA, Query String Append
2) I see some people using $_SERVER['REQUEST_URI'] instead of $_GET['url']. Is there any benefit, or advantage, to doing this?
I read some where in Stackoverflow Code Review that $_SERVER['REQUEST_URI'] will receive URL encoded values. So, I tested it and found that to be true.
For http://www.foo.com/hi/there/" ...
$_SERVER
... you would get this in your $_SERVER['REQUEST_URI']
[REQUEST_URI] => /hi/there%22 <---definitely URL encoded.
... this in $_SERVER['QUERY_STRING']
[QUERY_STRING] => url=/hi/there" <---probably URL decoded?
this in $_SERVER['SCRIPT_NAME']
[SCRIPT_NAME] => /hi/there" <---probably URL decoded?
... and, this in $_SERVER['SCRIPT_URL']
[SCRIPT_URL] => /hi/there" <---probably URL decoded?
$_GET
[url] => /hi/there/" <---probably URL decoded.
3) Am I wrong for wanting to use the values without %22? What I mean is, "Am I wrong for wanting to send that input through my filters, as opposed to the value with %22" For instance I use FILTER_SANITIZE_URL and FILTER_VALIDATE_URL (among other techniques) to validate URLs.
Note: After establishing a centralized index.php, my filters on INPUT_SERVER (just 6 or 7 elements) started failing (all 6 or 7). I use filter_input_array() Anyone experience something similar? I can figure it out. It just started happening after implementing the rewrite rule above.
Why would anyone use $_SERVER['REQUEST_URI'] over $_GET['url'] in PHP after URL rewriting occurs for an MVC Router?
Because using your approach means my app can't have a query string parameter of url anywhere in it, and I'll get weird, hard to diagnose behavior if I forget that. Diagnosing why submit?url=google.com gives me a 404 won't be much fun.
Laravel's .htaccess rule is just:
RewriteRule ^ index.php [L]
It'll get the route from $_SERVER['REQUEST_URI'], and parse it accordingly.
Do I need to specify the absolute path (seems so, as RewriteBase is not appropriate in this context)?
No, and you shouldn't, so your code is portable to other servers where files may be differently located.
3) Am I wrong for wanting to use the values without %22?
Yes, you are. Don't use invalid unescaped characters like " in routes.
The short answer is that $_GET['url'] doesn't magically exist in PHP. You need to have an entire framework setup and configured in the way you want for a value like this to exist.
In your case, you have some MVC router setup. So you should use the $_GET['url'] as it seems to be parsed by whatever framework you're using.
If you were to create a fresh PHP script with no dependencies or frameworks, $_GET['url'] will be undefined.
I prefer to parse Routes as so:
// Parse Request
$route = "";
$routes = [];
$url_components = explode('/', $_SERVER['REQUEST_URI']);
foreach($url_components as $key => $val)
{
if(empty($val))
{
if(!$key)continue;
$route .= 'index/';
continue;
}
$routes[] = $val;
$route .= "$val/";
}
// Examine Result
$_GET['url'] = $route;
echo "Route: $_GET[url]\n";
echo "Routes Array: <pre>".var_export($routes, true)."</pre>";
Hope this helps.

Get Current Url in PHP instead of files root folder url

Hello Friends I want to get the Current Page Url instead of capturing root url of file
I want to capture Like this
http://localhost/tester/
but coming like this
http://localhost/tester/views/inc/readcountry.php
I have tried like this but it's returning
$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]
localhost/tester/views/inc/readcountry.php
This one is working perfectly thanx alot
$_SERVER['QUERY_STRING']
A little handy function I found somewhere else might help you out.
function url() {
return sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['SERVER_NAME'],
$_SERVER['REQUEST_URI']
);
}
To use it:
echo url();
if you want the full url, try this:
<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
$_SERVER['HTTP_HOST'] - header from the current request, if there is one.
$_SERVER['REQUEST_URI'] - the URI which was given in order to access this page; for instance, '/index.html'.
$_SERVER['QUERY_STRING'] - it is your parameters and values in URL
My htaccess for MVC app:
RewriteEngine on
RewriteRule !.(js|gif|jpg|png|css)$ index.php
Plus in each directory (model, views, controllers) i putted htaccess too:
Deny from all
Not knowing which is the point of the tree you need to stop the capture, I may suggest you to have a look at all the content of the [$_SERVER] array, dumping it, and at the php magic constants.

How to write .htaccess for twitter API like urls

I'd like to write a proper .htaccess rule and PHP code to parse url like this one : https://myapi.com/1.1/users/search.json?q=abc&page=1&count=3
Here's what I found so far:
RewriteRule ^([a-zA-Z_-])\.(xml|json)$ index.php?url=$1&format=$2
And my PHP code looks like
$requestParts = explode('/', $_GET['url']);
$contentType = $_GET['type'];
//$params = ... //Here's where I'm lost
How can I get the optional part with the RewriteRule and PHP code ?
My suggestion would be to use a very simple rewrite to a front controller (like index.php) and then use code in that file to evaluate the requested route.
RewriteRule ^index\.php$ index.php [L,QSA]
In your api example you would then have paremeters q,page,count available in $_GET due to the QSA (query string append) flag on the rewrite rule.
This leaves it up to you to interpret the rest of the URI.
You can do that rather simply using simple string manipulation techniques.
// discard query string after trimming leftmost '/' from URI
$uri_parts = explode('?', ltrim($_SERVER['REQUEST_URI'], '/'));
$uri_base = $uri_parts[0];
// get routing information from URI
$route_parts = explode('/', $uri_base);
$api_version = $route_parts[0];
$controller = $route_parts[1];
$action_parts = explode('.',$route_parts[2]);
$action = $action_parts[0];
$format = $action_parts[1];
// your parameters would be in $_GET['q'], $_GET['page'], etc.
You might consider Googling PHP URL routing to get more examples of how to set up a proper router, as this was just a very basic example and does not include any sort of validation or handling of more complex routes.
The benefit of this approach is that it keeps your routing logic all in PHP rather than split between Apache server config and PHP. If you need to make routing changes, you do it in PHP only. This also prevents mixing of routing information with actual parameter information within $_GET as would happen with your proposed rewrite.

How to check what is Written in the url bar and navigate to a certain page in php?

What i want to be able to do is if someone writes in the url bar
www.somesite.com/test
test is like the Username name so it will be www.somesite.com/Username
then page navigate to another and display data from the data where the username is the same
The page will navigate to another page and display data from he database
is this possible first of?
And this is what i have write now it not much, and i am also new to PHP
$url = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url2 = "http://www.somesite.com/"$databaseVar1=mysql_result($result,$i,"username");
if ($url) == ($url2)
{
header("location: http://somesite.com/viewcontent.php");
}
else
{
//not found
}
Am i Able to do something like this? Any help will be great-full thanks
In PHP this is not exactly possible, however, you can do the following:
www.somesite.com/index.php/test
Apache will open index.php and you can use something like $_SERVER['REQUEST_URI'] to navigate from there
You will either need to use a rewrite rule in .htaccess to redirect all requests to index.php. Index.php can then use
Or you can put a ? before the username. Then index.php will automatically get all requests. The $_SERVER['querystring'] will then receive the username.
Taken some assumptions (due to lack of complete source code in your question):
mysql connection is estabilished
proper query has been sent to mysql server
variable $i is set to meaningful value
www server is configured to rewrite requests to index.php
You only have to compare REQUEST_URI with "username" column value taken from database.
Header "Location: ..." must have capital letter "L".
And avoid usage of "==" operator when comparing strings in PHP, strcmp() function is more reliable - "==" operator tests identity not equality - it's useful to compare numeric values.
You can define the index.php as the application dispatcher and create an .htaccess file that will redirect the requests to it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
index.php:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
if ($page == '/some/page/') include('file_that_handles_this_request.php');
Or you could use this to create instances of classes and call methods:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
list($class, $method) = explode($page);
$object = new $class();
$object->{$method}();
you should use mvc architecture to get perfect as you want.
the url in mvc is like same as you want. You can call the method with the parameter from url directly. Here is a url pattern in mvc architecture -
www.yoursitename.com/controller/methodname/parameter

URL rewriting advice please

I would like to make my urls more seo friendly and for example change this:
http://www.chillisource.co.uk/product?&cat=Grocery&q=Daves%20Gourmet&page=1&prod=B0000DID5R&prodName=Daves_Insanity_Sauce
to something nice like this:
http://www.chillisource.co.uk/product/Daves_Gourmet/Daves_Insanity_Sauce
What is the best way of going about doing this? I've had a look at doing this with the htaccess file but this seems very complicated.
Thanks in advance
Ben Paton, there is in fact a very easy way out. CMSes like Wordpress tend to use it instead of messing around with regular expressions.
The .htaccess side
First of, you use an .htacess with the content below:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Let me explain what it does (line by line):
if the apache module named mod_rewrite exists..
turn the module on
let it be known that we will rewrite anything starting after the
domain name (to only rewrite some directories, use RewriteBase
/subdir/)
if the requested path does not exist as a file...
and it doesn't even exist as a directory...
"redirect" request to the index.php file
close our module condition
The above is just a quick explanation. You don't really need it to use this.
What we did, is that we told Apache that all requests that would end up as 404s to pass them to the index.php file, where we can process the request manually.
The PHP side
On the PHP side, inside index.php, you simply have to parse the original URL. This URL is passed in the $_SERVER variable as $_SERVER['REDIRECT_URL'].
The best part, if there was no redirection, this variable is not set!
So, our code would end up like:
if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
$url = explode('/', $_SERVER['REDIRECT_URL'] );
switch($url[0]){
case 'home': // eg: /home/
break;
case 'about': // eg: /about/
break;
case 'images': // eg: /images/
switch( $url[1] ){
case '2010': // eg: /images/2010/
break;
case '2011': // eg: /images/2011/
break;
}
break;
}
}
Easy Integration
I nearly forgot to mention this, but, thanks to the way it works, you can even end up not changing your existing code at all!
Less talk, more examples. Let's say your code looked like:
<?php
$page = get_page($_GET['id']);
echo '<h1>'. $page->title .'</h1>';
echo '<div>'. $page->content .'</div>';
?>
Which worked with urls like:
index.php?id=5
You can make it work with SEO URLs as well as keep it with your old system at the same time. Firstly, make sure the .htaccess contains the code I wrote in the one above.
Next, add the following code at the very start of your file:
if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
$url = explode('/', $_SERVER['REDIRECT_URL'] );
$_GET['id'] = $url[0];
}
What are we doing here? Before going on two your own code, we are basically finding IDs and information from the old URL and feeding it to PHP's $_GET variable.
We are essentially fooling your code to think the request had those variables!
The only remaining hurdle to find all those pesky <a/> tags and replace their href accordingly, but that's a different story. :)
It's called a mod_rewrite, here is a tutorial:
http://www.workingwith.me.uk/articles/scripting/mod_rewrite
What about using the PATH_INFO environment variable?
$path=explode("/",getenv("PATH_INFO"));
echo($path[0]."; ".$path[1] /* ... */);
Will output
product; Daves_Gourmet; Daves_insanity_Sauce
The transition from using $_GET to using PATH_INFO environment is a good programming exercise. I think you cannot just do the task with configuration.
try some thing like this
RewriteRule ^/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+) /$1.php?id1=$2&id2=$3 [QSA]
then use $_GET to get the parameter values...
I'll have to add: in your original url, there's a 'prod' key, which seems to consist of an ID.
Make sure that, when switching to rewritten urls, you no longer solely depend upon a unique id, because that won't be visible in the url.
Now, you can use the ID to make a distinction between 2 products with the same name, but in case of rewriting urls and no longer requiring ID in the url, you need to make sure 1 product name can not be used multiple times for different products.
Likewise, I see the 'cat'-key not being present in the desired output url, same applies as described above.
Disregarding the above-described "problems", the rewrite should roughtly look like:
RewriteRule ^/product/(.*?)/(.*?)$ /product?&cat=Grocery&q=$1&page=1&prod=B0000DID5R&prodName=$2
The q & prodName will receive the underscored value, rather than %20, so also that will require some patching.
As you can see, I didn't touch the id & category, it'll be up to you to figure out how to handle that.

Categories