在安装任何软件前,确保系统包列表是最新的,避免依赖冲突:
sudo apt update && sudo apt upgrade -y
Debian的apt仓库提供多版本PHP(如8.2、7.4),可根据需求选择:
sudo apt install php php-cli php-fpm php-json php-common php-mysql php-zip php-gd php-mbstring php-curl php-xml php-bcmath
上述命令会安装PHP核心、命令行工具(php-cli)、PHP-FPM(进程管理)、数据库驱动(php-mysql)、GD图形库(图片处理)、MB字符串(多字节字符)、CURL(网络请求)等常用扩展。ondrej/php仓库(支持多版本共存),再安装:sudo apt install software-properties-common ca-certificates lsb-release apt-transport-https
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install php7.4 php7.4-cli php7.4-fpm php7.4-mysql php7.4-gd
PHP的主配置文件分为命令行模式(cli)和FPM模式(fpm),路径为/etc/php/<version>/:
/etc/php/<version>/cli/php.ini):display_errors = On
error_reporting = E_ALL
/etc/php/<version>/fpm/php.ini):memory_limit = 256M
upload_max_filesize = 10M
post_max_size = 10M
/etc/php/<version>/fpm/pool.d/www.conf,设置Unix socket(更安全):listen = /run/php/php<version>-fpm.sock
listen.owner = www-data
listen.group = www-data
修改后重启PHP-FPM使配置生效:sudo systemctl restart php<version>-fpm
PHP需配合Web服务器才能处理HTTP请求,以下是两种常见服务器的配置:
编辑默认站点配置(/etc/nginx/sites-available/default),添加PHP处理逻辑:
server {
listen 80;
server_name your_domain_or_ip;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 处理PHP请求(关键配置)
location ~ \.php$ {
include snippets/fastcgi-php.conf; # 引入FastCGI配置
fastcgi_pass unix:/run/php/php<version>-fpm.sock; # 指向PHP-FPM socket
}
# 禁止访问.htaccess文件(Apache遗留文件)
location ~ /\.ht {
deny all;
}
}
测试Nginx配置语法,无误后重启:
sudo nginx -t && sudo systemctl restart nginx
启用PHP模块并重启服务:
sudo a2enmod proxy_fcgi setenvif # 启用FastCGI模块
sudo systemctl restart apache2
编辑默认站点配置(/etc/apache2/sites-available/000-default.conf),添加PHP处理规则:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# 将.php文件交给PHP-FPM处理
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php<version>-fpm.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>
重启Apache使配置生效:
sudo systemctl restart apache2
在Web根目录(/var/www/html)创建info.php文件,内容如下:
<?php phpinfo(); ?>
通过浏览器访问http://your_server_ip/info.php,若看到PHP详细信息页面(如版本、加载的扩展),则说明配置成功。
安全提示:测试完成后,建议删除info.php文件,避免泄露服务器信息。
若需管理PHP项目依赖(如Laravel、Symfony),可安装Composer:
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
验证安装:
composer --version
通过以上步骤,你已在Debian系统中成功搭建PHP环境,可根据项目需求进一步扩展(如安装Redis、PDO等扩展)。