基本上,我使用 php 脚本代理一个文件,然后直接将其删除...只是,文件没有删除,我不知道为什么。
这有点断章取义,因此,如果您需要,我们很乐意解释更多。
exec("wget http://xxxx/123_" .$matches[1] . " --no-check-certificate -P /usr/share/nginx/www/" );
$file = "/usr/share/nginx/www/123_" . $matches[1];
if (file_exists($file)) {
header('Content-Type: text/plain');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exec("rm /usr/share/nginx/www/123_" . $matches[1] );
exit;
}
最佳答案
试试这段代码,它不会创建需要删除的本地文件:
// Define URL
$url = "http://xxxx/123_{$matches[1]}";
// Open pointer to remote resource
if (!$remoteFP = @fopen($url, 'r')) {
header("{$_SERVER['SERVER_PROTOCOL']} 500 Internal Server Error");
exit;
}
// Get content length and type from remote server's headers
$length = $type = NULL;
foreach ($http_response_header as $header) { // Loop headers (see http://php.net/manual/en/reserved.variables.httpresponseheader.php)
list($name, $val) = explode(':', $header, 2); // Split to key/value
switch (strtolower(trim($name))) { // See if it's a value we want
case 'content-length':
$length = (int) trim($val);
break;
case 'content-type':
$type = trim($val);
break;
}
if ($length !== NULL && $type !== NULL) break; // if we have found both we can stop looping
}
// Send headers
if ($type === NULL) $type = 'text/plain';
header("Content-Type: $type");
if ($length) header("Content-Length: $length"); // Only send content-length if the server sent one. You may want to do the same for content-type.
// Open a file pointer for the output buffer
$localFP = fopen('php://output', 'w');
// Send the data to the remote party
stream_copy_to_stream($remoteFP, $localFP);
// Close streams and exit
fclose($remoteFP);
fclose($localFP);
exit;
这在 cURL 等上使用了 fopen()
方法,因为它允许将实体直接转发到输出缓冲区,并在正文被发送之前允许访问远程服务器的响应 header 完全收到。这是使用 PHP 进行代理的最节省资源的方式。
如果您的服务器禁用了 allow_url_fopen
,您可以使用 cURL,它也允许您将数据直接传递到输出缓冲区,但不允许您解析和转发来自远程服务器的 header 。
关于php - 为什么我不能从 php 脚本中删除文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10106504/