Anonymous
Как написать функцию, связанную с БД, на основе внешних данных из запросов, которые никогда не сломаются
Сообщение
Anonymous » 25 сен 2024, 13:06
Я получаю запросы данных от Интернета и мобильных устройств:
отправляет мобильные устройства:
Код: Выделить всё
$data = [
'request' => [
'uuid' => 'a38571ba-56e7-4e81-88d1-9f343097feac',
'task_id' => 16068,
'typ_pozadavku' => '1',
'tel_cislo' => '+420605896968',
'datum' => '2024-09-11 08:00:00'
]
];
Код: Выделить всё
var data = {
action: 'contact_request',
data: {
task_id: task_id,
reason: reason,
phone: phone
}
};
$.ajax({
type: 'POST',
url: '',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response) {
if (response.status === 'ok') {
localStorage.setItem('task_send_time_' + task_id, new Date().getTime());
localStorage.setItem('task_send_count_' + task_id, ++send_count);
Мой основной скрипт уже обрабатывает эти запросы:
Код: Выделить всё
function processRequestAndFetchUserId() {
// Initialize data array
$data = [];
$audit = new Audit(Audit::$udalost_typ[1]); // Initialize audit
try {
error_log("Request method: " . $_SERVER['REQUEST_METHOD']);
error_log("Request URI: " . $_SERVER['REQUEST_URI']);
// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $_SERVER['REQUEST_METHOD'] !== 'GET') {
throw new Exception(ERROR_MSG['invalid_method'] ?? 'Invalid request method.', ERROR_CODE['invalid_method'] ?? 1000);
}
$method = $_SERVER['REQUEST_METHOD'];
$source = ($method === 'POST') ? $_POST : $_GET;
// If POST method and no source data, read JSON input
if ($method === 'POST' && empty($source)) {
$requestBody = file_get_contents('php://input');
error_log("Raw JSON body: " . $requestBody);
$source = json_decode($requestBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception(ERROR_MSG['invalid_json'] ?? 'JSON decode error: ' . json_last_error_msg(), ERROR_CODE['invalid_json'] ?? 1005);
}
// Check for data or request key
if (!isset($source['data']) && !isset($source['request'])) {
throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Input validation error: No valid data found.', ERROR_CODE['input_validation_error'] ?? 1006);
}
// Set source to the appropriate request data for further processing
$source = isset($source['data']) ? $source['data'] : $source['request'];
}
error_log("POST/GET input detected: " . json_encode($source));
// Define expected fields
$expectedFields = [
'task_id' => ['key' => 'task_id', 'required' => true],
'typ_pozadavku' => ['key' => (isset($source['uuid']) ? 'typ_pozadavku' : 'reason'), 'required' => true],
'tel_cislo' => ['key' => (isset($source['uuid']) ? 'tel_cislo' : 'phone'), 'required' => true],
'uuid' => ['key' => 'uuid', 'required' => false],
'datum' => ['key' => 'datum', 'required' => false],
];
foreach ($expectedFields as $field => $info) {
$value = isset($source[$info['key']]) ? trim($source[$info['key']]) : null;
$data[$field] = $value;
// Set default value for 'datum' if not provided
if ($field === 'datum') {
$data[$field] = $value ?: date("Y-m-d H:i:s");
}
// Check for required fields
if ($info['required'] && is_null($data[$field])) {
throw new Exception(ERROR_MSG['missing_data'] ?? 'Missing required data: ' . $info['key'], ERROR_CODE['missing_data'] ?? 1001);
}
}
// Validate input fields
if (!validate_task_id($data['task_id'])) {
throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid task_id format.', ERROR_CODE['input_validation_error'] ?? 1008);
}
if (!validate_typ_pozadavku($data['typ_pozadavku'])) {
throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid typ_pozadavku format.', ERROR_CODE['input_validation_error'] ?? 1009);
}
if (!validate_phonenumber2($data['tel_cislo'])) {
throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid phone number format.', ERROR_CODE['input_validation_error'] ?? 1007);
}
if (!is_null($data['uuid']) && !validate_uuid($data['uuid'])) {
throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid UUID format.', ERROR_CODE['input_validation_error'] ?? 1010);
}
if (!is_null($data['datum']) && !validate_date($data['datum'])) {
throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid datum format.', ERROR_CODE['input_validation_error'] ?? 1011);
}
// Fetch user_id based on uuid or task_id
$user_id = null;
if (!empty($data['uuid'])) {
error_log("Fetching user_id for UUID: " . $data['uuid']);
$result = dibi::select('user_id')->from('device')->where('uuid = %s', $data['uuid'])->fetch();
if ($result instanceof \Dibi\Row) {
$user_id = $result->user_id;
} else {
throw new Exception("User ID not found for UUID: " . $data['uuid']);
}
} elseif (isset($data['task_id'])) {
error_log("Fetching user_id for Task ID: " . $data['task_id']);
$result = dibi::select('user_id')->from('task_user')->where('task_id = %i', $data['task_id'])->fetch();
if ($result instanceof \Dibi\Row) {
$user_id = $result->user_id;
} else {
throw new Exception("User ID not found for Task ID: " . $data['task_id']);
}
}
if (!$user_id) {
throw new Exception("Unable to retrieve user_id.");
}
// Final validation and logging
error_log("Final processed data: " . json_encode($data));
error_log("User ID: " . $user_id);
return [
'status' => STATUS['ok'],
'data' => $data,
'user_id' => $user_id
];
} catch (Exception $ex) {
$audit->set_dulezitost(Audit::$udalost_dulezitost[2]); // Set to error level
$message = $ex->getMessage() ?: ERROR_MSG['error'];
error_log("Error processing input data: " . $message . "\nTrace: " . $ex->getTraceAsString());
// Log the error in audit
$audit->execute($message);
// Return an error response
return [
'status' => STATUS['error'],
'message' => $message,
'code' => $ex->getCode()
];
}
}
И я отправляю эти данные на проверку следующего уровня в следующей последовательности:
Код: Выделить всё
Подробнее здесь: [url]https://stackoverflow.com/questions/79022291/how-to-write-a-db-related-function-based-on-front-end-data-from-requests-that-wi[/url]
1727258772
Anonymous
Я получаю запросы данных от Интернета и мобильных устройств: [list] [*]отправляет мобильные устройства: [/list] [code]$data = [ 'request' => [ 'uuid' => 'a38571ba-56e7-4e81-88d1-9f343097feac', 'task_id' => 16068, 'typ_pozadavku' => '1', 'tel_cislo' => '+420605896968', 'datum' => '2024-09-11 08:00:00' ] ]; [/code] [list] [*]веб-отправки: [/list] [code]var data = { action: 'contact_request', data: { task_id: task_id, reason: reason, phone: phone } }; $.ajax({ type: 'POST', url: '', data: JSON.stringify(data), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(response) { if (response.status === 'ok') { localStorage.setItem('task_send_time_' + task_id, new Date().getTime()); localStorage.setItem('task_send_count_' + task_id, ++send_count); [/code] Мой основной скрипт уже обрабатывает эти запросы: [code]function processRequestAndFetchUserId() { // Initialize data array $data = []; $audit = new Audit(Audit::$udalost_typ[1]); // Initialize audit try { error_log("Request method: " . $_SERVER['REQUEST_METHOD']); error_log("Request URI: " . $_SERVER['REQUEST_URI']); // Validate request method if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $_SERVER['REQUEST_METHOD'] !== 'GET') { throw new Exception(ERROR_MSG['invalid_method'] ?? 'Invalid request method.', ERROR_CODE['invalid_method'] ?? 1000); } $method = $_SERVER['REQUEST_METHOD']; $source = ($method === 'POST') ? $_POST : $_GET; // If POST method and no source data, read JSON input if ($method === 'POST' && empty($source)) { $requestBody = file_get_contents('php://input'); error_log("Raw JSON body: " . $requestBody); $source = json_decode($requestBody, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception(ERROR_MSG['invalid_json'] ?? 'JSON decode error: ' . json_last_error_msg(), ERROR_CODE['invalid_json'] ?? 1005); } // Check for data or request key if (!isset($source['data']) && !isset($source['request'])) { throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Input validation error: No valid data found.', ERROR_CODE['input_validation_error'] ?? 1006); } // Set source to the appropriate request data for further processing $source = isset($source['data']) ? $source['data'] : $source['request']; } error_log("POST/GET input detected: " . json_encode($source)); // Define expected fields $expectedFields = [ 'task_id' => ['key' => 'task_id', 'required' => true], 'typ_pozadavku' => ['key' => (isset($source['uuid']) ? 'typ_pozadavku' : 'reason'), 'required' => true], 'tel_cislo' => ['key' => (isset($source['uuid']) ? 'tel_cislo' : 'phone'), 'required' => true], 'uuid' => ['key' => 'uuid', 'required' => false], 'datum' => ['key' => 'datum', 'required' => false], ]; foreach ($expectedFields as $field => $info) { $value = isset($source[$info['key']]) ? trim($source[$info['key']]) : null; $data[$field] = $value; // Set default value for 'datum' if not provided if ($field === 'datum') { $data[$field] = $value ?: date("Y-m-d H:i:s"); } // Check for required fields if ($info['required'] && is_null($data[$field])) { throw new Exception(ERROR_MSG['missing_data'] ?? 'Missing required data: ' . $info['key'], ERROR_CODE['missing_data'] ?? 1001); } } // Validate input fields if (!validate_task_id($data['task_id'])) { throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid task_id format.', ERROR_CODE['input_validation_error'] ?? 1008); } if (!validate_typ_pozadavku($data['typ_pozadavku'])) { throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid typ_pozadavku format.', ERROR_CODE['input_validation_error'] ?? 1009); } if (!validate_phonenumber2($data['tel_cislo'])) { throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid phone number format.', ERROR_CODE['input_validation_error'] ?? 1007); } if (!is_null($data['uuid']) && !validate_uuid($data['uuid'])) { throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid UUID format.', ERROR_CODE['input_validation_error'] ?? 1010); } if (!is_null($data['datum']) && !validate_date($data['datum'])) { throw new Exception(ERROR_MSG['input_validation_error'] ?? 'Invalid datum format.', ERROR_CODE['input_validation_error'] ?? 1011); } // Fetch user_id based on uuid or task_id $user_id = null; if (!empty($data['uuid'])) { error_log("Fetching user_id for UUID: " . $data['uuid']); $result = dibi::select('user_id')->from('device')->where('uuid = %s', $data['uuid'])->fetch(); if ($result instanceof \Dibi\Row) { $user_id = $result->user_id; } else { throw new Exception("User ID not found for UUID: " . $data['uuid']); } } elseif (isset($data['task_id'])) { error_log("Fetching user_id for Task ID: " . $data['task_id']); $result = dibi::select('user_id')->from('task_user')->where('task_id = %i', $data['task_id'])->fetch(); if ($result instanceof \Dibi\Row) { $user_id = $result->user_id; } else { throw new Exception("User ID not found for Task ID: " . $data['task_id']); } } if (!$user_id) { throw new Exception("Unable to retrieve user_id."); } // Final validation and logging error_log("Final processed data: " . json_encode($data)); error_log("User ID: " . $user_id); return [ 'status' => STATUS['ok'], 'data' => $data, 'user_id' => $user_id ]; } catch (Exception $ex) { $audit->set_dulezitost(Audit::$udalost_dulezitost[2]); // Set to error level $message = $ex->getMessage() ?: ERROR_MSG['error']; error_log("Error processing input data: " . $message . "\nTrace: " . $ex->getTraceAsString()); // Log the error in audit $audit->execute($message); // Return an error response return [ 'status' => STATUS['error'], 'message' => $message, 'code' => $ex->getCode() ]; } } [/code] И я отправляю эти данные на проверку следующего уровня в следующей последовательности: [code] Подробнее здесь: [url]https://stackoverflow.com/questions/79022291/how-to-write-a-db-related-function-based-on-front-end-data-from-requests-that-wi[/url]