test 1: request and accept php are same
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
test 2: request in a.php and receive in b.php
// a.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="b.php">
Name: <input type="text" name="fname">
</form>
</body>
</html>
// b.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
test 3: ios client
func sendDeviceToken() {
// get device indentification
let data = DeviceDTO()
// arrange the data
do {
// send to server
let url = URL(string: "")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let jsonData = try JSONEncoder().encode(data)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString)
// method 1: DTO
request.httpBody = jsonData
// method 2:
// let postString = "a=test&b=bla"
// request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// check error
if let error = error {
print ("error: \(error)")
return
}
// check response
guard let response = response as? HTTPURLResponse,
(200...299).contains(response.statusCode) else {
print ("server error")
return
}
// print data from server
guard let data = data else {
print("no data")
return
}
// see server response
let dataString = String(data: data, encoding: .utf8)
print ("got data: \(dataString)")
}
task.resume()
}
catch {
print("[Shark] cannot encode the device data")
}
}
server.php
// method 1: DTO
// server receives this
[{"a": "a", "b": "b"}]
$keys = array_keys($_POST);
$obj = json_decode($keys[0]);
ech $obj->{"a"};
// method 2:
echo $_POST["a"];
echo $_POST["b"];
// you can add CustomStringConvertible protocol to the DTO to convert all attributes to the format of "a=a&b=b", so that you can access via this method.