- Как получить текущий URL в PHP?
- Полный URL
- Результат:
- URL без GET-параметров
- Результат:
- Основной путь и GET-параметры
- Результат:
- Только основной путь
- Результат:
- Только GET-параметры
- Результат:
- Результат:
- Комментарии 2
- Другие публикации
- Create and Consume Simple REST API in PHP
- What is REST?
- How Does REST API Work
- How to Create and Consume Simple REST API in PHP
- 1. Create REST API in PHP
- 1. Create a Database and Table with Dummy Data
- 2. Create a Database Connection
- 3. Create a REST API File
- 2. Consume REST API in PHP
- 1. Create an Index File with HTML Form
- 2. Fetch Records through CURL
Как получить текущий URL в PHP?
Сформировать текущий адрес страницы можно с помощью элементов массива $_SERVER. Рассмотрим на примере URL:
Полный URL
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $url;
Результат:
https://example.com/category/page?sort=asc
URL без GET-параметров
$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $url = explode('?', $url); $url = $url[0]; echo $url;
Результат:
https://example.com/category/page
Основной путь и GET-параметры
$url = $_SERVER['REQUEST_URI']; echo $url;
Результат:
Только основной путь
$url = $_SERVER['REQUEST_URI']; $url = explode('?', $url); $url = $url[0]; echo $url;
Результат:
Только GET-параметры
Результат:
Для преобразования строки с GET-параметрами в ассоциативный массив можно применить функцию parse_str() .
parse_str('sort=asc&page=2&brand=rich', $get); print_r($get);
Результат:
Array ( [sort] => asc [page] => 2 [brand] => rich )
Комментарии 2
Авторизуйтесь, чтобы добавить комментарий.
Другие публикации
Как получить данные из Google spreadsheets в виде массива PHP? Очень просто, Google docs позволяет экспортировать лист в формате CSV, главное чтобы файл был в общем доступе.
В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.
Create and Consume Simple REST API in PHP
In this tutorial, we will create and consume simple REST API in PHP. REST enables you to access and work with web based services. But before moving ahead let me explain what is REST and how does it work.
What is REST?
REST stands for Representational State Transfer, REST is an architectural style which defines a set of constraints for developing and consuming web services through standard protocol (HTTP). REST API is a simple, easy to implement and stateless web service. There is another web service available which is SOAP which stands for Simple Object Access Protocol which is created by Microsoft.
REST API is widely used in web and mobile applications as compared to SOAP. REST can provide output data in multiple formats such as JavaScript Object Notation (JSON), Extensible Markup Language (XML), Command Separated Value (CSV) and many others while SOAP described output in Web Services Description Language (WSDL).
How Does REST API Work
REST requests are related to CRUD operations (Create, Read, Update, Delete) in database, REST uses GET, POST, PUT and DELETE requests. Let me compare them with CRUD.
- GET is used to retrieve information which is similar to Read
- POST is used to create new record which is similar to Create
- PUT is used to update record which is similar to Update
- DELETE is used to delete record which is similar to Delete
How to Create and Consume Simple REST API in PHP
JSON format is the most common output format of REST API, we will use the JSON format to consume our simple REST API. We will developed an online transaction payment REST API for our example. I will try to keep it as simple as possible so i will use GET request to retrieve information.
1. Create REST API in PHP
To create a REST API, follow these steps:
- Create a Database and Table with Dummy Data
- Create a Database Connection
- Create a REST API File
1. Create a Database and Table with Dummy Data
To create database run the following query.
CREATE DATABASE allphptricks;
To create a table run the following query. Note: I have already attached the SQL file of this table with dummy data, just download the complete zip file of this tutorial.
CREATE TABLE IF NOT EXISTS `transactions` ( `id` int(20) NOT NULL AUTO_INCREMENT, `order_id` int(50) NOT NULL, `amount` decimal(9,2) NOT NULL, `response_code` int(10) NOT NULL, `response_desc` varchar(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `order_id` (`order_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;
2. Create a Database Connection
Just create a db.php file and paste the following database connection in it. Make sure that you update these credentials with your database credentials.
// Enter your Host, username, password, database below. $con = mysqli_connect("localhost","root","","allphptricks"); if (mysqli_connect_errno())
3. Create a REST API File
Create a api.php file and paste the following script in it.
0)< $row = mysqli_fetch_array($result); $amount = $row['amount']; $response_code = $row['response_code']; $response_desc = $row['response_desc']; response($order_id, $amount, $response_code,$response_desc); mysqli_close($con); >else < response(NULL, NULL, 200,"No Record Found"); >>else < response(NULL, NULL, 400,"Invalid Request"); >function response($order_id,$amount,$response_code,$response_desc) < $response['order_id'] = $order_id; $response['amount'] = $amount; $response['response_code'] = $response_code; $response['response_desc'] = $response_desc; $json_response = json_encode($response); echo $json_response; >?>
The above script will accept the GET request and return output in the JSON format.
I have created all these files in folder name rest, now you can get the transaction information by browsing the following URL.
http://localhost/rest/api.php?order_id=15478959
You will get the following output.
Above URL is not user friendly, therefore we will rewrite URL through the .htaccess file, copy paste the following rule in .htaccess file.
RewriteEngine On # Turn on the rewriting engine RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?order_id=$1 [NC,L]
Now you can get the transaction information by browsing the following URL.
http://localhost/rest/api/15478959
You will get the following output.
2. Consume REST API in PHP
To consume a REST API, follow these steps:
1. Create an Index File with HTML Form
2. Fetch Records through CURL
"; echo "Order ID: $result->order_id "; echo "Amount: $result->amount "; echo "Response Code: $result->response_code "; echo "Response Desc: $result->response_desc "; echo ""; > ?>
You can do anything with these output data, you can insert or update it into your own database if you are using REST API of any other service provider. Usually in case of online transaction, the service provider provides status of payment via API. You can check either payment is made successfully or not. They also provide a complete guide of it.
Make sure CURL is enabled on your web server or on your localhost when you are testing demo.
I try my best to explain this tutorial as simple as possible.
If you found this tutorial helpful, share it with your friends and developers group.
I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.