

新闻资讯
技术学院部署PHP程序到SlimAPI框架需先配置PHP 7.4+、Web服务器及Composer,再通过Composer安装Slim并创建入口文件,配置Nginx或Apache重写规则,最后启动服务测试接口,建议优化安全设置。
将PHP程序部署到SlimAPI轻量接口框架中,关键在于正确配置运行环境并合理组织项目结构。SlimAPI基于Slim Framework,适合构建RESTful API服务,部署过程简单高效。
确保服务器或本地开发环境满足以下基础条件:
可通过命令检查PHP环境:
php -v php -m | grep -E "(json|mbstring|openssl)"
进入目标目录,使用Composer创建Slim应用:
composer require slim/slim "^4.0" composer require slim/psr7
创建入口文件 public/index.php:
get('/hello/{name}', function ($request, $response, $args) {
$name = $args['name'];
$response->getBody()->write("Hello, " . htmlspecialchars($name));
return $response;
});
$app->run();
为支持路由转发,需设置URL重写规则。
Nginx 配置示例:server {
listen 80;
root /path/to/your-project/public;
index index.php;
location / {
try_files $uri $uri/ /
index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Apache .htaccess(位于public目录):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
方式一:使用PHP内置服务器(适用于测试)
cd public php -S localhost:8080
访问 https://www./link/3e89ac165a1a75a582fa8305bae74fcd 查看返回结果。
方式二:通过Nginx + PHP-FPM正式部署
sudo systemctl start php-fpm
sudo systemctl reload nginx
基本上就这些。只要环境配置正确,SlimAPI的部署非常轻便,适合快速交付小型API服务。