ZetCode

PHP copy 函数

最后修改于 2025 年 4 月 3 日

PHP 的 copy 函数将一个文件从源复制到目标。它对于 PHP 应用程序中的文件管理操作至关重要。

基本定义

copy 函数将文件从一个位置复制到另一个位置。成功时返回 true,失败时返回 false。

语法:copy(string $source, string $dest, resource $context = null): bool。如果权限允许,该函数会覆盖现有文件。

基本文件复制示例

这演示了 copy 复制文件的最简单用法。

basic_copy.php
<?php

declare(strict_types=1);

$source = "source.txt";
$destination = "destination.txt";

if (copy($source, $destination)) {
    echo "File copied successfully";
} else {
    echo "Failed to copy file";
}

这将 "source.txt" 复制到 "destination.txt"。如果成功,该函数返回 true。始终检查返回值进行错误处理。

使用绝对路径复制

本示例为了清晰起见,展示了使用绝对文件路径进行复制。

absolute_paths.php
<?php

declare(strict_types=1);

$source = "/var/www/html/images/photo.jpg";
$destination = "/var/www/html/backups/photo_backup.jpg";

if (copy($source, $destination)) {
    echo "Backup created successfully";
} else {
    echo "Backup failed: " . error_get_last()['message'];
}

在这里,我们将一张照片复制到一个备份位置。绝对路径确保我们处理的是特定的文件。错误处理会在失败时显示最后一条错误消息。

使用上下文复制

这演示了使用流上下文进行额外的复制选项。

copy_with_context.php
<?php

declare(strict_types=1);

$source = "data.csv";
$destination = "archive/data_backup.csv";
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => "User-Agent: PHP Copy Script\r\n"
    ]
]);

if (copy($source, $destination, $context)) {
    echo "Data archived successfully";
} else {
    echo "Archive operation failed";
}

流上下文允许设置 HTTP 标头或其他选项。当从远程源复制或需要特定的传输参数时,这非常有用。

带有错误处理的复制

本示例展示了文件复制操作的健壮错误处理。

error_handling.php
<?php

declare(strict_types=1);

function safeCopy(string $source, string $dest): bool {
    if (!file_exists($source)) {
        throw new RuntimeException("Source file not found");
    }
    
    if (!is_readable($source)) {
        throw new RuntimeException("Source file not readable");
    }
    
    if (file_exists($dest) && !is_writable(dirname($dest))) {
        throw new RuntimeException("Destination directory not writable");
    }
    
    return copy($source, $dest);
}

try {
    safeCopy("report.pdf", "backups/report.pdf");
    echo "File copied successfully";
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}

这实现了一个安全复制函数,并进行了预先验证。它在尝试复制操作之前检查文件是否存在、是否可读以及是否可写。

复制远程文件

本示例演示了将远程 URL 的文件复制到本地服务器。

remote_copy.php
<?php

declare(strict_types=1);

$remoteUrl = "https://example.com/images/banner.jpg";
$localPath = "downloads/banner.jpg";

if (copy($remoteUrl, $localPath)) {
    echo "Remote file downloaded successfully";
} else {
    echo "Failed to download remote file";
}

copy 函数可以从 HTTP/HTTPS URL 获取文件。请注意,PHP 配置必须允许 URL fopen 包装器才能正常工作。

最佳实践

来源

PHP copy 文档

本教程介绍了 PHP 的 copy 函数,并通过实际示例展示了其在不同场景下的用法。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 PHP 文件系统函数