本文目录导读:

在 PHP 中使用 Ngrok 主要有两种场景,我来分别说明:
本地开发调试(最常用)
命令行方式(推荐)
# 启动 ngrok 转发到本地 PHP 开发服务器 ngrok http 80 # 如果使用 PHP 内建服务器 php -S localhost:8000 # 另开终端 ngrok http 8000
使用 PHP 内建服务器示例
# 终端1:启动 PHP 服务器 cd /path/to/your/project php -S localhost:8080 # 终端2:启动 ngrok ngrok http 8080
Ngrok 会生成一个公网 URL(如 https://abc123.ngrok.io),指向你的本地 PHP 服务器。
在 PHP 代码中集成 Ngrok
使用 PHP 执行系统命令
<?php
// 动态启动 ngrok
function startNgrok($port = 8080, $subdomain = null) {
$command = "ngrok http $port";
// 如果指定了子域名
if ($subdomain) {
$command .= " --subdomain $subdomain";
}
// 后台运行 ngrok
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
pclose(popen("start /B $command", "r"));
} else {
exec("nohup $command > /dev/null 2>&1 &");
}
// 等待 ngrok 启动
sleep(2);
// 获取 ngrok 的公开 URL
return getNgrokUrl();
}
// 获取 ngrok 的公开 URL
function getNgrokUrl() {
$api = file_get_contents('http://127.0.0.1:4040/api/tunnels');
$data = json_decode($api, true);
if (isset($data['tunnels'][0]['public_url'])) {
return $data['tunnels'][0]['public_url'];
}
return null;
}
// 使用示例
$publicUrl = startNgrok(8080);
echo "你的公网地址: " . $publicUrl;
?>
安装 PHP Ngrok 扩展包
composer require mtxshift/php-ngrok
<?php require 'vendor/autoload.php'; use PHPNgrok\Ngrok\Ngrok; // 基本用法 $ngrok = new Ngrok(); $ngrok->tunnel(8080); // 创建隧道 $url = $ngrok->getPublicUrl(); // 获取公网地址 echo "公网地址: $url"; ?>
Laravel 中使用 Ngrok
配置 Laravel 的 URL
<?php
// config/app.php
return [
'url' => 'http://your-ngrok-url.ngrok.io',
// 其他配置...
];
动态设置(在启动时)
<?php
// 在 AppServiceProvider.php 中
public function boot()
{
if (env('APP_ENV') === 'local' && isset($_SERVER['HTTP_HOST'])) {
URL::forceRootUrl('http://' . $_SERVER['HTTP_HOST']);
}
}
常用 Ngrok 配置
配置文件 ngrok.yml
authtoken: your_auth_token
tunnels:
php-server:
proto: http
addr: 8080
subdomain: my-php-app
auth: "username:password" # 添加认证
使用配置文件启动
ngrok start php-server
需要注意的事项
- 端口冲突:确保 PHP 服务器端口没有被其他程序占用
- 防火墙:确保本地防火墙允许 ngrok 连接
- Token 配置:免费版用户需要配置 ngrok 的 auth token
- 会话管理:ngrok 可能影响 PHP session 或 Cookie 处理
处理 Session 问题
<?php
// 在 PHP 中设置允许的域
session_set_cookie_params([
'domain' => '.ngrok.io', // 允许所有 ngrok 子域名
'secure' => false,
'httponly' => true
]);
session_start();
调试技巧
<?php
// 获取 ngrok 调试信息
function getNgrokDebugInfo() {
$info = file_get_contents('http://127.0.0.1:4040/status');
echo $info;
// 查看请求日志
$requests = file_get_contents('http://127.0.0.1:4040/api/requests/http');
$data = json_decode($requests, true);
return $data;
}
这样就能在 PHP 中很好地使用 ngrok 进行本地开发调试了!