Build your first web service with PHP, JSON and MySql

原文连接: https://trinitytuts.com/build-first-web-service-php/

Web services ( application services ) is one of the most important part of today development where we ceneteralized or data and allow user to access that data from different sources like web, software, app etc.. Web service provide Interoperability between two different language.  Web service are easy to understand or to made we can easily create a web service of our website. There are no of method through which you can create you web service

  1. SOAP { Simple Object Access Protocol }.
  2. REST { Representational State Transfer }

Download

We are going to create a web service using REST method but i also give you small overview of SOAP method first.

What is SOAP?.

SOAP is Simple Object Access Protocol based on XML so it easy to read. It is simple XML based protocol to exchange data between two different language.

What is REST?.

REST { Representational State Transfer } is a simple stateless architecture that generally runs over HTTP. REST web service system produce status code response in JSON or XML format.

Create webservice using REST is very easy and take less time to make as compare to other.

REST support all most commonly used HTTP methods (GET, POST, PUT and DELETE). We use all these method according to need.

Application using REST

Now i am going to create a small application using REST. In this application we can create a SignUp, Get user Info and Update user status. Before creating this application it is recommended that you have basic understanding of PHP, MYSQL, JSON. I later explain you that how we can use this in android to access data from PHP based webservice.

Step 1. I hope that you already install WAMP or XAMPP in your computer.

Step 2.  Now we need to install chrome  extension for testing or web service so i use Advance REST Client.

REST Client is very useful to test or webservice. You simply follow the link i mention above and install extension in your Chrome browser.

Step 3. Now we are going to create our database http://localhost/phpmyadmin .

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

--

-- Database: `tuts_rest`

--

create database IF NOT EXISTS `tuts_rest`

-- --------------------------------------------------------

--

-- Table structure for table `users`

--

CREATE TABLE IF NOT EXISTS `users` (

`ID` int(11) NOT NULL AUTO_INCREMENT,

`name` text NOT NULL,

`email` varchar(100) NOT NULL,

`password` varchar(100) NOT NULL,

`status` text NOT NULL,

PRIMARY KEY (`ID`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Copy paste this sql query to your phpmyadmin-> sql.

Step 4. Now we need to create a data handler file in php and  url where we can handle request information.

Code : confi.php

1

2

3

<?php

$conn = mysql_connect("localhost", "root", "");

mysql_select_db(‘tuts_rest‘, $conn);

first we need to connection to our database. Now we can create a file to save requested data to data base

signup.php

Requested URL : http://localhost/aneh/rest/signup.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<?php

// Include confi.php

include_once(‘confi.php‘);

if($_SERVER[‘REQUEST_METHOD‘] == "POST"){

// Get data

$name = isset($_POST[‘name‘]) ? mysql_real_escape_string($_POST[‘name‘]) : "";

$email = isset($_POST[‘email‘]) ? mysql_real_escape_string($_POST[‘email‘]) : "";

$password = isset($_POST[‘pwd‘]) ? mysql_real_escape_string($_POST[‘pwd‘]) : "";

$status = isset($_POST[‘status‘]) ? mysql_real_escape_string($_POST[‘status‘]) : "";

// Insert data into data base

$sql = "INSERT INTO `tuts_rest`.`users` (`ID`, `name`, `email`, `password`, `status`) VALUES (NULL, ‘$name‘, ‘$email‘, ‘$password‘, ‘$status‘);";

$qur = mysql_query($sql);

if($qur){

$json = array("status" => 1, "msg" => "Done User added!");

}else{

$json = array("status" => 0, "msg" => "Error adding user!");

}

}else{

$json = array("status" => 0, "msg" => "Request method not accepted");

}

@mysql_close($conn);

/* Output header */

header(‘Content-type: application/json‘);

echo json_encode($json);

In signup page i did not add any validation you can add your validation here if you like the main and important thing in this page is

header(‘Content-type: application/json’);

we tell php that this page is return as json, and we also usejson_encode() to return our data in json format.

Now after this we need Advance Rest Client to send data to our page. Go to your chrome app store where you add your extensions

click on Advance Rest client. Now add your request

url: http://localhost/aneh/rest/signup.php, Select the Request method, Click on  Add new vaule define your value and data in it and click on send.

after doing all this you need send data to server and this output like this


That all if you get done message!.

Now we get user info using GET method. I create a new php file to get user info once you have command on this you easily work on single page.

Info.php

Requester URL: url: http://localhost/aneh/rest/info.php?uid=Request_ID

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?php

// Include confi.php

include_once(‘confi.php‘);

$uid = isset($_GET[‘uid‘]) ? mysql_real_escape_string($_GET[‘uid‘]) :  "";

if(!empty($uid)){

$qur = mysql_query("select name, email, status from `users` where ID=‘$uid‘");

$result =array();

while($r = mysql_fetch_array($qur)){

extract($r);

$result[] = array("name" => $name, "email" => $email, ‘status‘ => $status);

}

$json = array("status" => 1, "info" => $result);

}else{

$json = array("status" => 0, "msg" => "User ID not define");

}

@mysql_close($conn);

/* Output header */

header(‘Content-type: application/json‘);

echo json_encode($json);

In this we pass user id in url. Add this url in Advance REST Client and click on send and get output like this:

1

2

3

4

5

6

7

8

9

10

{

status: 1

info: [1]

0:  {

name: "aneh tahkur"

email: "[email protected]"

status: "Cool!!"

}-

-

}

Now we can update user info using PUT method. To read about Put method follow this link.

status.php

Request URL: http://localhost/aneh/rest/status.php

Update user status

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<?php

// Include confi.php

include_once(‘confi.php‘);

if($_SERVER[‘REQUEST_METHOD‘] == "PUT"){

$uid = isset($_SERVER[‘HTTP_UID‘]) ? mysql_real_escape_string($_SERVER[‘HTTP_UID‘]) : "";

$status = isset($_SERVER[‘HTTP_STATUS‘]) ? mysql_real_escape_string($_SERVER[‘HTTP_STATUS‘]) : "";

// Add your validations

if(!empty($uid)){

$qur = mysql_query("UPDATE  `tuts_rest`.`users` SET  `status` =  ‘$status‘ WHERE  `users`.`ID` =‘$uid‘;");

if($qur){

$json = array("status" => 1, "msg" => "Status updated!!.");

}else{

$json = array("status" => 0, "msg" => "Error updating status");

}

}else{

$json = array("status" => 0, "msg" => "User ID not define");

}

}else{

$json = array("status" => 0, "msg" => "User ID not define");

}

@mysql_close($conn);

/* Output header */

header(‘Content-type: application/json‘);

echo json_encode($json);

In above i am using PUT method in PUT we access data like this: $_SERVER[‘HTTP_DATAVARIABLE’].

Sending PUT Request from Advance Rest Client.

In this we add url where we want to make request and then select Request method PUT and then add header as shown in above image.

Out Put of above is

1

2

3

4

{

status: 1

msg: "Status updated!!."

}

This is very simple and easy example webservice example.

Thanku!

Happy Coading.

时间: 2024-10-03 23:28:51

Build your first web service with PHP, JSON and MySql的相关文章

基于Web Service的客户端框架搭建二:数据转换层(FCL)

引言 要使用WebService来分离客户端与服务端,必定要使用约定好两者之间的数据契约.Json数据以其完全独立于语言的优势,成为开发者的首选.C# JavaScriptSerializer为Json与Object对象之间的序列化与反序列化提供了良好的方法. 接口设计 数据转换包含Json反序列化成Object对象和Object序列化成Json数据.在项目中,会有很多实例对象,都需要使用Serialize和Deserialize方法来实现数据转换,我们可以抽象出一个接口IDFC(数据格式转换接

基于Web Service的客户端框架搭建一:C#使用Http Post方式传递Json数据字符串调用Web Service

引言 前段时间一直在做一个ERP系统,随着系统功能的完善,客户端(CS模式)变得越来越臃肿.现在想将业务逻辑层以下部分和界面层分离,使用Web Service来做.由于C#中通过直接添加引用的方来调用Web Service的方式不够灵活,故采取手动发送Http请求的方式来调用Web Service.最后选择使用Post方式来调用Web Service,至于安全性和效率暂不考虑.在学习使用的过程,遇到了很多问题,也花了很长时间来解决,网上相关的帖子很少,如果各位在使用的过程中有一些问题难以解决,可

c#从Web Service 获取信息并解析json

如果需要登录,使用下边方法,如果为匿名登录的,可以省略,在全局变量中定义public static string Cookiemsg,方便重复使用cookie. 1 public static CookieMsg GetCookieMessage(string name, string password) 2 { 3 CookieMsg cookieMsg = null; 4 string retString = ""; 5 try 6 { 7 HttpWebRequest reque

ASP.NET AJAX Call Web Service , Return JSON Format String

最近同事问用ASP.NET AJAX Call Web Service可以返回DataTable吗?现在公司项目的后台很多都直用AJAX作掉,达到异步的效果,目前公司的作法是用Web Service回传一个 List 到前端给JavaScript作Parse,Parse过程花调许多程序与性能,所以问题来了,如果能直接返回DataTable该有多好啊!? 最近同事问用ASP.NET AJAX Call Web Service可以返回DataTable吗? 现在公司项目的后台很多都直用AJAX作掉,

Liferay Portal Json Web Service 反序列化漏洞(CVE-2020-79

作者:[email protected]知道创宇404实验室 时间:2020年3月27日 原文地址:https://paper.seebug.org/1162/英文版本:https://paper.seebug.org/1163/ 之前在CODE WHITE上发布了一篇关于Liferay Portal JSON Web Service RCE的漏洞,之前是小伙伴在处理这个漏洞,后面自己也去看了.Liferay Portal对于JSON Web Service的处理,在6.1.6.2版本中使用的是

Difference between WCF and Web API and WCF REST and Web Service

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of ch

搭建一个RESTFUL风格的Web Service (Maven版本)

[该教程翻译自Spring官方,并进行适当删减.] 你将搭建的 你将搭建一个可以接受Http Get 请求的web service, http://localhost:8080/greeting 并将以JSON字符串的形式返回问候, {"id":1,"content":"Hello, World!"} 工具 一个文本编辑器,JDK1.6及以上,Maven 3.0+或者Gradle 1.11+.(本文将使用Maven) 下面是pom.xml文件的清

使用Restful风格的Web Service(Maven版本)

[该教程翻译自Spring官方,并进行适当删减.] 你将搭建的 你将创建的应用将使用Spring的RestTemplate来获取Facebook的Graph API的数据.(符合Restful风格) http://graph.facebook.com/pivotalsoftware 它将返回的JSON字符串为: { "id": "161112704050757", "about": "Pivotal is enabling the cr

如何封装RESTful Web Service

所谓Web Service是一个平台独立的,低耦合的,自包含的.可编程的Web应用程序,有了Web Service异构系统之间就可以通过XML或JSON来交换数据,这样就可以用于开发分布式的互操作的应用程序.Web Service使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件就可相互交换数据或集成,无论它们各自所使用的语言.平台或内部协议是什么,都可以相互交换数据.Web Service为整个企业甚至多个组织之间的业务流程的集成提供了一个通用机制. ??REST(REpre