fetch.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. function usage($argv) {
  3. echo "Usage:\n";
  4. printf("\tphp %s <http://example.com/file> <localfile>\n", $argv[0]);
  5. exit(1);
  6. }
  7. function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
  8. static $filesize = null;
  9. switch($notification_code) {
  10. case STREAM_NOTIFY_RESOLVE:
  11. case STREAM_NOTIFY_AUTH_REQUIRED:
  12. case STREAM_NOTIFY_COMPLETED:
  13. case STREAM_NOTIFY_FAILURE:
  14. case STREAM_NOTIFY_AUTH_RESULT:
  15. /* Ignore */
  16. break;
  17. case STREAM_NOTIFY_REDIRECTED:
  18. echo "Being redirected to: ", $message, "\n";
  19. break;
  20. case STREAM_NOTIFY_CONNECT:
  21. echo "Connected...\n";
  22. break;
  23. case STREAM_NOTIFY_FILE_SIZE_IS:
  24. $filesize = $bytes_max;
  25. echo "Filesize: ", $filesize, "\n";
  26. break;
  27. case STREAM_NOTIFY_MIME_TYPE_IS:
  28. echo "Mime-type: ", $message, "\n";
  29. break;
  30. case STREAM_NOTIFY_PROGRESS:
  31. if ($bytes_transferred > 0) {
  32. if (!isset($filesize)) {
  33. printf("\rUnknown filesize.. %2d kb done..", $bytes_transferred/1024);
  34. } else {
  35. $length = (int)(($bytes_transferred/$filesize)*100);
  36. printf("\r[%-100s] %d%% (%2d/%2d kb)", str_repeat("=", $length). ">", $length, ($bytes_transferred/1024), $filesize/1024);
  37. }
  38. }
  39. break;
  40. }
  41. }
  42. isset($argv[1], $argv[2]) or usage($argv);
  43. if (!isset($_ENV['http_proxy'])) {
  44. $copt = null;
  45. } else {
  46. $copt = array(
  47. 'http' => array(
  48. 'proxy' => preg_replace('/^http/i', 'tcp', $_ENV['http_proxy']),
  49. 'request_fulluri' => true,
  50. ),
  51. );
  52. }
  53. $ctx = stream_context_create($copt, array("notification" => "stream_notification_callback"));
  54. $fp = fopen($argv[1], "r", false, $ctx);
  55. if (is_resource($fp) && file_put_contents($argv[2], $fp)) {
  56. echo "\nDone!\n";
  57. exit(0);
  58. }
  59. $err = error_get_last();
  60. echo "\nError..\n", $err["message"], "\n";
  61. exit(1);