You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用纯PHP访问Windows XAMPP服务器外接USB摄像头实现拍照

实现方案

PHP本身没有内置直接操作服务器硬件的能力,无法仅靠PHP原生函数完成摄像头拍照,Windows+XAMPP环境下可以借助第三方命令行拍照工具,通过PHP调用系统执行函数触发拍照,再将生成的照片返回前端即可。

前置准备

  • 下载适配Windows的命令行拍照工具CommandCam,这是微软官方推出的轻量免安装工具,将下载好的CommandCam.exe放到站点目录下,比如C:\xampp\htdocs\cam\tools\路径下。
  • 打开XAMPP对应的php.ini配置文件,找到disable_functions配置项,移除exec、shell_exec两个函数的禁用配置,保存后重启Apache服务生效。
  • 在站点目录下新建照片保存目录,比如C:\xampp\htdocs\cam\photos\,确保该目录有写入权限。

后端PHP接口实现

新建take_photo.php文件作为拍照请求接口,代码示例如下:

<?php
// 自定义配置项,替换为你自己的实际路径
$cam_tool_path = 'C:\\xampp\\htdocs\\cam\\tools\\CommandCam.exe';
$save_dir = 'C:\\xampp\\htdocs\\cam\\photos\\';

// 自动创建不存在的保存目录
if (!file_exists($save_dir)) {
    mkdir($save_dir, 0777, true);
}
$photo_name = time() . '.jpg';
$save_full_path = $save_dir . $photo_name;

// 拼接命令行拍照指令
$command = $cam_tool_path . ' /filename ' . escapeshellarg($save_full_path);
shell_exec($command);

// 返回结果给前端
if (file_exists($save_full_path)) {
    echo json_encode([
        'code' => 200,
        'photo_url' => '/cam/photos/' . $photo_name
    ]);
} else {
    echo json_encode([
        'code' => 500,
        'msg' => '摄像头调用失败'
    ]);
}
?>

前端页面实现

页面包含触发拍照的按钮和展示照片的容器,代码示例如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>服务器摄像头拍照</title>
</head>
<body>
    <button id="takeBtn">点击拍照</button>
    <div id="photoContainer" style="margin-top: 20px; width: 640px; height: 480px; border: 1px solid #ccc;"></div>

    <script>
        const takeBtn = document.getElementById('takeBtn');
        const photoContainer = document.getElementById('photoContainer');

        takeBtn.addEventListener('click', function() {
            takeBtn.textContent = '拍照中...';
            takeBtn.disabled = true;

            fetch('/cam/take_photo.php')
                .then(res => res.json())
                .then(data => {
                    if (data.code === 200) {
                        photoContainer.innerHTML = `<img src="${data.photo_url}" style="width: 100%; height: 100%; object-fit: cover;">`;
                    } else {
                        alert(data.msg || '拍照失败');
                    }
                    takeBtn.textContent = '点击拍照';
                    takeBtn.disabled = false;
                })
                .catch(err => {
                    alert('请求失败:' + err);
                    takeBtn.textContent = '点击拍照';
                    takeBtn.disabled = false;
                });
        });
    </script>
</body>
</html>

注意事项

  • 如果服务器接入了多个摄像头,可以在调用CommandCam的命令中添加/devnum参数指定调用的设备编号,也可以添加/width、/height参数自定义输出照片的分辨率,直接在Windows cmd中运行CommandCam.exe即可查看所有可用参数。
  • 上线使用时建议给拍照接口增加权限校验、请求频率限制,避免被恶意调用占用服务器资源。
  • 可以新增定时清理逻辑,定期删除历史照片,避免占用过多磁盘空间。

内容的提问来源于stack exchange,提问作者VictorTheBeast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:36:02