카테고리 없음
Swift&Php에서 일부 body 변수를 읽지 못하는 문제
kangchaewon
2025. 12. 1. 16:46
swift에서 body로 php서버에 전달하는데, 뒤의 변수가 전달이 안 되는 문제가 생겼다.
let body =
"senderId=\(myUser.usersId)" +
"&receiverId=\(finalReceiverId)" +
"&title=\(encode(title))" +
"&content=\(encode(content))" +
"&expectedArrivalTime=\(encode(dateStr))" +
"&parentLettersId=\(parentId)" +
"&goalId=\(goalIdValue)"
<?php
// LetterCompose.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=utf-8");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
//$host = getenv('DB_HOST');
//$user = getenv('DB_USER');
//$pw = getenv('DB_PASSWORD');
//$dbName = getenv('DB_NAME');
include_once('./config.php');
$conn = new mysqli($host, $user, $pw, $dbName);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die(json_encode(["error" => "DB Connection failed: " . $conn->connect_error]));
}
$senderIntId = $_POST['senderId'] ?? '';
$receiverStringId = $_POST['receiverId'] ?? '';
$title = $_POST['title'] ?? '';
$content = $_POST['content'] ?? '';
$expectedArrivalTime = $_POST['expectedArrivalTime'] ?? '';
$parentLettersId = $_POST['parentLettersId'] ?? 0;
// goal for history
$goalId = $_POST['goalId'] ?? 0;
var_dump($_POST);
if (empty($senderIntId) || empty($receiverStringId)) {
echo json_encode(["error" => "보내는 사람 또는 받는 사람 정보가 없습니다."]);
exit;
}
로그도 찍어봤는데
편지 작성 시, 데이터 확인 senderId=22&receiverId=22&title=2222&content=22222&expectedArrivalTime=2025-12-01%2016:38:31&parentLettersId=0&goalId=7
원인:
인코딩을 하지 않아, 앞 부분 yy이런 데이터는 잘 읽었지만
2025-12-01 16:28:55 이런 데이터를 서버는
expectedArrivalTime=2025-12-01
16:28:55&parentLettersId=0&goalId=7
이렇게 읽어버리기 때문애, 뒤의 데이터가 날라간다.
즉,
- dateStr에서 공백 때문에 body가 두 줄로 나뉘고
- goalId는 두 번째 줄에 혼자 떨어짐
- PHP는 두 번째 줄의 파라미터를 무시함
그래서 goalId는 없음 → $_POST['goalId'] → 0
수정 코드:
// 인코딩
func encode(_ value: String) -> String {
return value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
}
let body =
"senderId=\(myUser.usersId)" +
"&receiverId=\(finalReceiverId)" +
"&title=\(encode(title))" +
"&content=\(encode(content))" +
"&expectedArrivalTime=\(encode(dateStr))" +
"&parentLettersId=\(parentId)" +
"&goalId=\(goalIdValue)"