我需要一些帮助,已经两天了,但我找不到问题。我正在为我的最后一年项目开发 Android 应用程序,一切都很顺利,直到在 Filezilla 中上传我的 API 文件后出现 404 未找到错误。我尝试在 HTA 访问中重写基础,但它不起作用,或者我做得不正确,谁知道呢。
公共/index.php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require '../vendor/autoload.php';
require '../includes/DbOperations.php';
$app = AppFactory::create();
$app->setBasePath("/mylife/public");
$app->addErrorMiddleware(true, true, true);
/**
* endpoint : createUser
* parameters : email, password, name, school
* method : POST
**/
$app->post('/createuser', function (Request $request, Response $response) {
if (!haveEmptyParameters(array('nophone', 'password', 'name', 'username', 'email'), $response)) {
$request_data = $_REQUEST;
$nophone = $request_data['nophone'];
$password = $request_data['password'];
$name = $request_data['name'];
$username = $request_data['username'];
$email = $request_data['email'];
$hash_password = md5($password);
;
$db = new DbOperations;
$result = $db->createUser($nophone, $hash_password, $name, $username, $email);
if ($result == USER_CREATED) {
$message = array();
$message['error'] = false;
$message['message'] = 'User Created Successfully.';
$response->getBody()->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(201);
} elseif ($result == USER_FAILURE) {
$message = array();
$message['error'] = true;
$message['message'] = 'Some error occurred.';
$response->getBody()->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
} elseif ($result == USER_EXISTS) {
$message = array();
$message['error'] = true;
$message['message'] = 'User Already Exists.';
$response->getBody()->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
$app->post('/insertcart', function (Request $request, Response $response) {
if (!haveEmptyParameters(array('title', 'quantity', 'u_id'), $response)) {
$request_data = $_REQUEST;
$menuitem = $request_data['title'];
$quantity = $request_data['quantity'];
$user_id = $request_data['u_id'];
$db = new DbOperations;
$menuname = $db->getMenuItemByName($menuitem);
$menuitem = $menuname[0]['idmenu']; // Extract the correct value from the array
$existingItem = null; // Initialize $existingItem as null
// Check if the item with the same name already exists for the user
// Check if the item with the same name already exists for the user
$cartItems = $db->checkCartItems($menuname, $user_id);
error_log('Debug - Cart Items:');
error_log(print_r($cartItems, true)); // Log the cart items for debugging
$existingItem = null;
foreach ($cartItems as $item) {
if ($item['idorder'] && $item['quantity']) {
$existingItem = $item;
break; // Exit the loop once a matching item is found
}
}
$message = array();
// Check if the item with the same name already exists for the user
if ($existingItem) {
// If the item already exists, update the quantity
$newQuantity = $existingItem['quantity'] + $quantity;
$result = $db->updatecart($newQuantity, $existingItem['idorder']);
if ($result) {
$message['error'] = false;
$message['message'] = 'Item Quantity Updated Successfully.';
} else {
$message['error'] = true;
$message['message'] = 'Failed to Update Item Quantity.';
}
} else {
// If the item does not exist, insert a new item
$result = $db->insertcart($user_id);
if ($result){
$idorder = $db->getorder($user_id);
if($idorder != null) {
if ($menuname){
$rest = $db->insertcartdetails($menuname, $quantity, $result);
if ($rest == ITEMS_ADDED) {
$message['error'] = false;
$message['message'] = 'Item Inserted Successfully.';
$message['id'] = $idorder;
$message['cart_details'] = $rest;
$message['menuitem'] = $menuname;
$message['$cartItems'] = $cartItems;
} else {
$message['error'] = true;
$message['message'] = 'Failed to Insert Item.';
}
}
}
} else {
$message['error'] = true;
$message['message'] = 'Failed to Insert Item.';
}
}
$response->getBody()->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus($message['error'] ? 422 : 401);
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
$app->post('/insertpayment', function (Request $request, Response $response) {
if (!haveEmptyParameters(array('totalamount', 'user_id', 'totalquantity'), $response)) {
$request_data = $_REQUEST;
$totalamount = $request_data['totalamount'];
$user_id = $request_data['user_id'];
$totalquantity = $request_data['totalquantity'];
$db = new DbOperations;
$result = $db->insertpayment($totalamount, $user_id);
if ($result == ITEMS_ADDED) {
$updatecart = $db->updatecartsconfirmed($user_id);
$message = array();
$message['error'] = false;
$message['message'] = 'Payment Successfully.';
$message['updatecart'] = $updatecart;
$response->getBody()->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(401);
} elseif ($result == ITEMS_NOT_ADDED) {
$message = array();
$message['error'] = true;
$message['message'] = 'Some error occurred.';
$response->getBody()->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
} elseif ($result == ITEMS_ALREADY_ADDED) {
$message = array();
$message['error'] = true;
$message['message'] = 'Payment Already made.';
$response->getBody()->write(json_encode($message));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
$app->post('/userlogin', function (Request $request, Response $response) {
if (!haveEmptyParameters(array('username', 'password'), $response)) {
$request_data = $_REQUEST;
$username = $request_data['username'];
$password = $request_data['password'];
$db = new DbOperations();
$result = $db->userlogin($username, $password);
if ($result == USER_AUTHENTICATED) {
$user = $db->getUserByusername($username);
$response_data = array();
$response_data['error'] = false;
$response_data['message'] = 'Login Successful';
$response_data['user'] = $user;
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} elseif ($result == USER_NOT_FOUND) {
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'User NOt Exist';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(404);
} elseif ($result == USER_PASSWORD_DO_NOT_MATCH) {
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'Invalid Credentials';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(404);
}
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
$app->get('/allcategory', function (Request $request, Response $response) {
$db = new DbOperations();
$category = $db->getcategory();
$response_data['error'] = false;
$response_data['category'] = $category;
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
});
$app->get('/allusers', function (Request $request, Response $response) {
$db = new DbOperations();
$users = $db->getAllUsers();
$response_data['error'] = false;
$response_data['users'] = $users;
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
});
$app->get('/allcart', function (Request $request, Response $response) {
$request_data = $_REQUEST;
if (isset($request_data['u_id'])) {
$u_id = $request_data['u_id']; // Retrieve the username from the route parameters
$db = new DbOperations();
$cartItems = $db->getAllCartItems($u_id);
$response_data['cartItems'] = $cartItems;
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} else {
// Handle the case where "username" parameter is missing
$error_response['error'] = true;
$error_response['message'] = 'u_id parameter is missing in the request';
$response->getBody()->write(json_encode($error_response));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(400); // You can use a different HTTP status code if appropriate
}
});
$app->get('/allmenu', function (Request $request, Response $response, $args) {
// Retrieve the username from the route parameters
if (!haveEmptyParameters(array('category'), $response)) {
$request_data = $_REQUEST;
$categories = explode(',', $request_data['category']);
$db = new DbOperations();
$menuItems = $db->getAllmenuItems($categories);
$response_data['menuItems'] = $menuItems;
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} else {
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'Please try again';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
// Handle the case where "username" parameter is missing
});
$app->put('/updateuser', function (Request $request, Response $response) {
if (!haveEmptyParameters(array('nophone', 'name', 'username', 'id', 'email'), $response)) {
$request_data = $_REQUEST;
$nophone = $request_data['nophone'];
$name = $request_data['name'];
$username = $request_data['username'];
$id = $request_data['id'];
$email = $request_data['email'];
$db = new DbOperations();
if ($db->updateUser($nophone, $name, $username, $id, $email)) {
// Retrieve the updated user data
$updatedUser = $db->getUserByusername($username);
$response_data = array();
$response_data['error'] = false;
$response_data['message'] = 'User Updated Successfully';
$response_data['user'] = $updatedUser; // Include the user data in the response
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} else {
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'Please try again';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200); // You may want to change the status code if there's an error
});
$app->put('/updatecartitem', function (Request $request, Response $response, array $args) {
if (!haveEmptyParameters(array('quantity', 'o_id'), $response)) {
$request_data = $_REQUEST;
$quantity = $request_data['quantity'];
$id = $request_data['o_id'];
$db = new DbOperations();
if ($db->updatecart($quantity, $id)) {
// Retrieve the updated user data
$updatedUser = $db->getCartItems($id);
// Populate the 'user' field with the updated user data
if($updatedUser !=null){
$response_data = array();
$response_data['error'] = false;
$response_data['message'] = 'Cart Items Updated Successfully';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} else {
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'user data is ';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
} else {
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'Please try again';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
});
$app->put('/updatepassword', function (Request $request, Response $response) {
if (!haveEmptyParameters(array('currentpassword', 'newpassword', 'username'), $response)) {
$request_data = $_REQUEST;
$currentpassword = $request_data['currentpassword'];
$newpassword = $request_data['newpassword'];
$username = $request_data['username'];
$db = new DbOperations();
$result = $db->updatePassword($currentpassword, $newpassword, $username);
if ($result == PASSWORD_CHANGED) {
$response_data = array();
$response_data['error'] = false;
$response_data['message'] = 'Password Changed';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
} elseif ($result == PASSWORD_DO_NOT_MATCH) {
$response_data = array();
$response_data['error'] = true;
$response_data['message'] = 'You have given wrong password';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
} elseif ($result == PASSWORD_NOT_CHANGED) {
$response_data = array();
$response_data['error'] = false;
$response_data['message'] = 'some error ocurred';
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
}
}
return $response
->withHeader('Content-type', 'application/json')
->withStatus(422);
});
$app->delete('/deleteuser/{u_id}', function (Request $request, Response $response, array $args) {
$id = $args['u_id'];
$db = new DbOperations();
if ($db->deleteUser($id)) {
$response_data['error'] = false;
$response_data['message'] = 'User has been deleted';
} else {
$response_data['error'] = true;
$response_data['message'] = 'Please Try Again later';
}
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
});
$app->delete('/deleteitemcart', function (Request $request, Response $response, array $args) {
if (!haveEmptyParameters(array('o_id'), $response)) {
$request_data = $_REQUEST;
$id = $request_data['o_id'];
$db = new DbOperations();
if ($db->deleteitems($id)) {
$response_data['error'] = false;
$response_data['message'] = 'items has been deleted';
} else {
$response_data['error'] = true;
$response_data['message'] = 'Please Try Again later';
}
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
}
$response->getBody()->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
});
function haveEmptyParameters($required_params, $response)
{
$error = false;
$error_params = '';
$request_params = $_REQUEST;
foreach ($required_params as $param) {
if (!isset($request_params[$param]) || strlen($request_params[$param]) <= 0) {
$error = true;
$error_params .= $param . ', ';
}
}
if ($error) {
$error_detail = array();
$error_detail['error'] = true;
$error_detail['message'] = 'Required parameters ' . substr($error_params, 0, -2) . ' are either missing or empty';
$response->getBody()->write(json_encode($error_detail));
}
return $error;
}
$app->run();
我有两个 .htacess,一个位于公共文件夹内,一个位于外部文件夹内。
外部文件夹
公共文件夹之外
Options All -Indexes
<Files .htaccess>
order allow,deny
deny from all
</Files>
<IfModule mod_rewrite.c>
# Redirect to the public folder
RewriteEngine On
RewriteBase /mylife/
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
# Redirect to HTTPS
# RewriteEngine On
# RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
公共文件夹内
Options All -Indexes
<Files .htaccess>
order allow,deny
deny from all
</Files>
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect to HTTPS
# RewriteEngine On
# RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Some hosts may require you to use the `RewriteBase` directive.
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the index.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
# If the above doesn't work you might need to set the `RewriteBase` directive manually, it should be the
# absolute physical path to the directory that contains this htaccess file.
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
它说的错误是
[05-Nov-2023 02:05:24 Asia/Kuala_Lumpur] 404 Not Found
Type: Slim\Exception\HttpNotFoundException
Code: 404
Message: Not found.
File: /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php
Line: 76
Trace: #0 /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/vendor/slim/slim/Slim/Routing/RouteRunner.php(56): Slim\Middleware\RoutingMiddleware->performRouting()
#1 /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php(76): Slim\Routing\RouteRunner->handle()
#2 /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/vendor/slim/slim/Slim/MiddlewareDispatcher.php(121): Slim\Middleware\ErrorMiddleware->process()
#3 /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/vendor/slim/slim/Slim/MiddlewareDispatcher.php(65): Psr\Http\Server\RequestHandlerInterface@anonymous->handle()
#4 /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/vendor/slim/slim/Slim/App.php(199): Slim\MiddlewareDispatcher->handle()
#5 /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/vendor/slim/slim/Slim/App.php(183): Slim\App->handle()
#6 /home/sabrisae/public_html/ruangprojek/sadiahcafe/mylife/public/index.php(601): Slim\App->run()
#7 {main}
我知道如果它可以访问,会出现不同的错误,例如参数丢失等。
我尝试了很多方法来更改链接或基本网址或.htacess或数据库,它只是简单地不起作用,而且index.html文件也很好,不要大写或任何东西,因为在我的计算机上它可以工作。
我发现至少有两个问题可以解决:
主要问题是 Slim basePath 没有正确配置,因为
public
目录永远不可能成为 Slim 的 basePath 的一部分。 basePath 是 public
路径下的所有内容。 URL 路径中包含 public
目录不是“有效”的。 public
目录应配置为 Apache DocumentRoot。如果您将 Slim 应用程序放置在不直接位于 Apache DocumentRoot 路径下,那么您需要定义 Slim basePath,例如
我会尝试删除或注释掉
RewriteBase /mylife/
设置,因为这可能会导致与 Slim 基本路径发生“冲突”。
然后配置正确的basePath,不带公共路径,例如
$app->setBasePath("/sadiahcafe/mylife");
如果这不起作用,我建议安装 Slim BasePathMiddleware。该中间件能够检测和配置 Slim 的基本路径。