Skip to content

Commit 81d80bb

Browse files
authoredMay 2, 2024
Add files via upload
1 parent f1e9a47 commit 81d80bb

File tree

1 file changed

+164
-0
lines changed

1 file changed

+164
-0
lines changed
 

‎rest.php

+164
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
<?php
2+
// Подключение к базе данных
3+
$host = "localhost";
4+
$dbname = "rest";
5+
$username = "root";
6+
$password = "";
7+
8+
try {
9+
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
10+
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
11+
} catch (PDOException $e) {
12+
// Обработка ошибки подключения к базе данных
13+
sendResponse("error", "Database connection failed");
14+
}
15+
16+
// Функция для отправки ответа в формате JSON
17+
function sendResponse($status, $message, $data = null) {
18+
header("Content-Type: application/json");
19+
echo json_encode(array("status" => $status, "message" => $message, "data" => $data));
20+
exit;
21+
}
22+
23+
// Метод создания пользователя
24+
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/api/users/create') {
25+
26+
$data = json_decode(file_get_contents("php://input"), true);
27+
28+
// Проверка наличия обязательных полей в данных
29+
if (!isset($data['username']) || !isset($data['email']) || !isset($data['password'])) {
30+
sendResponse("error", "Missing required fields");
31+
}
32+
33+
// Проверка корректности email адреса
34+
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
35+
sendResponse("error", "Invalid email format");
36+
}
37+
38+
$username = htmlspecialchars($data['username']);
39+
$email = htmlspecialchars($data['email']);
40+
$password = password_hash($data['password'], PASSWORD_DEFAULT);
41+
42+
try {
43+
$stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
44+
$stmt->execute([$username, $email, $password]);
45+
sendResponse("success", "User created successfully");
46+
} catch (PDOException $e) {
47+
// Обработка ошибки добавления пользователя в базу данных
48+
sendResponse("error", "Failed to create user");
49+
}
50+
}
51+
52+
// Метод обновления информации о пользователе
53+
if ($_SERVER['REQUEST_METHOD'] === 'PUT' && $_SERVER['REQUEST_URI'] === '/api/users/update') {
54+
55+
$data = json_decode(file_get_contents("php://input"), true);
56+
57+
// Проверка наличия обязательных полей в данных
58+
if (!isset($data['userId']) || !isset($data['newUsername']) || !isset($data['newEmail'])) {
59+
sendResponse("error", "Missing required fields");
60+
}
61+
62+
// Проверка корректности email адреса
63+
if (!filter_var($data['newEmail'], FILTER_VALIDATE_EMAIL)) {
64+
sendResponse("error", "Invalid email format");
65+
}
66+
67+
$userId = $data['userId'];
68+
$newUsername = htmlspecialchars($data['newUsername']);
69+
$newEmail = htmlspecialchars($data['newEmail']);
70+
71+
try {
72+
$stmt = $pdo->prepare("UPDATE users SET username = ?, email = ? WHERE id = ?");
73+
$stmt->execute([$newUsername, $newEmail, $userId]);
74+
sendResponse("success", "User information updated successfully");
75+
} catch (PDOException $e) {
76+
// Обработка ошибки обновления информации о пользователе
77+
sendResponse("error", "Failed to update user information");
78+
}
79+
}
80+
81+
// Метод удаления пользователя
82+
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && $_SERVER['REQUEST_URI'] === '/api/users/delete') {
83+
84+
$data = json_decode(file_get_contents("php://input"), true);
85+
86+
// Проверка наличия обязательных полей в данных
87+
if (!isset($data['userId'])) {
88+
sendResponse("error", "Missing required fields");
89+
}
90+
91+
$userId = $data['userId'];
92+
93+
try {
94+
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
95+
$stmt->execute([$userId]);
96+
sendResponse("success", "User deleted successfully");
97+
} catch (PDOException $e) {
98+
// Обработка ошибки удаления пользователя
99+
sendResponse("error", "Failed to delete user");
100+
}
101+
}
102+
103+
// Метод аутентификации пользователя
104+
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/api/users/login') {
105+
106+
$data = json_decode(file_get_contents("php://input"), true);
107+
108+
// Проверка наличия обязательных полей в данных
109+
if (!isset($data['email']) || !isset($data['password'])) {
110+
sendResponse("error", "Missing required fields");
111+
}
112+
113+
$email = htmlspecialchars($data['email']);
114+
$password = $data['password'];
115+
116+
try {
117+
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
118+
$stmt->execute([$email]);
119+
$user = $stmt->fetch(PDO::FETCH_ASSOC);
120+
121+
if ($user && password_verify($password, $user['password'])) {
122+
// Пользователь аутентифицирован успешно
123+
sendResponse("success", "User authenticated successfully", array("userId" => $user['id']));
124+
} else {
125+
// Неверный email или пароль
126+
sendResponse("error", "Invalid email or password");
127+
}
128+
} catch (PDOException $e) {
129+
// Обработка ошибки аутентификации пользователя
130+
sendResponse("error", "Failed to authenticate user");
131+
}
132+
}
133+
134+
// Метод получения информации о пользователе
135+
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_SERVER['REQUEST_URI'] === '/api/users/info') {
136+
137+
$data = json_decode(file_get_contents("php://input"), true);
138+
139+
// Проверка наличия обязательных полей в данных
140+
if (!isset($data['userId'])) {
141+
sendResponse("error", "Missing required fields");
142+
}
143+
144+
$userId = $data['userId'];
145+
146+
try {
147+
$stmt = $pdo->prepare("SELECT id, username, email FROM users WHERE id = ?");
148+
$stmt->execute([$userId]);
149+
$user = $stmt->fetch(PDO::FETCH_ASSOC);
150+
151+
if ($user) {
152+
sendResponse("success", "User information retrieved successfully", $user);
153+
} else {
154+
sendResponse("error", "User not found");
155+
}
156+
} catch (PDOException $e) {
157+
// Обработка ошибки получения информации о пользователе
158+
sendResponse("error", "Failed to retrieve user information");
159+
}
160+
}
161+
162+
// Если запрос не соответствует ни одному из методов, отправляем ошибку
163+
sendResponse("error", "Invalid request method or URL");
164+
?>

0 commit comments

Comments
 (0)
Please sign in to comment.