简体   繁体   English

为什么我不能从php脚本中删除该文件?

[英]Why can't I delete the file from a php script?

Basically, I am proxying a file using a php script and then deleting it straight after... only, the file isn't deleting and I can't work out why. 基本上,我使用PHP脚本代理文件,然后直接删除它...只是,文件没有删除,我无法解决原因。

This is a little out of context, so, happy to explain more should you need it. 这有点脱离背景,因此,如果你需要它,很乐意解释更多。

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;
}

Try this code, which will not create a local file that needs to be deleted: 尝试此代码,该代码不会创建需要删除的本地文件:

// 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;

This uses the fopen() approach over cURL etc because it allows one to forward the entity straight to the output buffer, as well as giving access to the remote server's response headers before the body have been fully received. 这使用fopen()方法而不是cURL等,因为它允许将实体直接转发到输出缓冲区,并在完全接收到主体之前提供对远程服务器响应头的访问。 It is the most resource-efficient way to proxy using PHP. 它是使用PHP进行代理的最具资源效率的方法。

If your server has allow_url_fopen disabled, you may be able to use cURL, which will also allow you to pass the data straight to the output buffer, but does not allow you to parse and forward the headers from the remote server. 如果您的服务器禁用了allow_url_fopen ,您可以使用cURL,它还允许您将数据直接传递到输出缓冲区,但不允许您从远程服务器解析和转发标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM