溫馨提示×

PHP file_get_contents能重命名嗎

PHP
小樊
81
2024-10-23 06:11:10
欄目: 編程語言

file_get_contents 本身沒有提供直接重命名的功能。但是,你可以通過將文件內(nèi)容讀取到一個臨時文件中,然后使用 PHP 的文件操作函數(shù)(如 rename)將臨時文件重命名為目標文件名。以下是一個示例:

<?php
$url = 'http://example.com/file.txt'; // 替換為你要讀取的文件 URL
$target_filename = 'new_file.txt'; // 替換為你想要重命名的目標文件名

// 使用 file_get_contents 讀取文件內(nèi)容
$content = file_get_contents($url);

if ($content === false) {
    die('Error: Failed to fetch file content');
}

// 將文件內(nèi)容寫入臨時文件
$temp_filename = tempnam(sys_get_temp_dir(), 'file');
file_put_contents($temp_filename, $content);

// 將臨時文件重命名為目標文件名
if (!rename($temp_filename, $target_filename)) {
    die('Error: Failed to rename temporary file to target file');
}

echo 'File successfully fetched and renamed';
?>

請注意,這個示例適用于從遠程 URL 讀取文件。如果你要讀取本地文件,只需將 $url 變量替換為本地文件的路徑即可。

0