Remote File Saving


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // File to download
  2. $remoteFile = 'http://www.yahoo.com/';
  3.  
  4. // Local file for saving
  5. $localFile = "YahooHome.htm";
  6.  
  7. // Time to cache in hours
  8. $cacheTime = 24;
  9.  
  10. // Connection time out
  11. $connTimeout = 10;
  12.  
  13. if(file_exists($localFile) && (time() - ($cacheTime * 3600) < filemtime($localFile))){
  14. readfile($localFile);
  15. }else{
  16. $url = parse_url($remoteFile);
  17. $host = $url['host'];
  18. $path = isset($url['path']) ? $url['path'] : '/';
  19.  
  20. if (isset($url['query'])) {
  21. $path .= '?' . $url['query'];
  22. }
  23.  
  24. $port = isset($url['port']) ? $url['port'] : '80';
  25.  
  26. $fp = @fsockopen($host, '80', $errno, $errstr, $connTimeout );
  27.  
  28. if(!$fp){
  29. // If connection failed, return the cached file
  30. if(file_exists($localFile)){
  31. readfile($localFile);
  32. }
  33. }else{
  34. // Header Info
  35. $header = "GET $path HTTP/1.0
  36. ";
  37. $header .= "Host: $host
  38. ";
  39. $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6
  40. ";
  41. $header .= "Accept: */*
  42. ";
  43. $header .= "Accept-Language: en-us,en;q=0.5
  44. ";
  45. $header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
  46. ";
  47. $header .= "Keep-Alive: 300
  48. ";
  49. $header .= "Connection: keep-alive
  50. ";
  51. $header .= "Referer: http://$host
  52.  
  53. ";
  54.  
  55. $response = '';
  56. fputs($fp, $header);
  57. // Get the file content
  58. while($line = fread($fp, 4096)){
  59. $response .= $line;
  60. }
  61. fclose( $fp );
  62.  
  63. // Remove Header Info
  64. $pos = strpos($response, "
  65.  
  66. ");
  67. $response = substr($response, $pos + 4);
  68. echo $response;
  69.  
  70. // Save the file content
  71. if(!file_exists($localFile)){
  72. // Create the file, if it doesn't exist already
  73. fopen($localFile, 'w');
  74. }
  75. if(is_writable($localFile)) {
  76. if($fp = fopen($localFile, 'w')){
  77. fwrite($fp, $response);
  78. fclose($fp);
  79. }
  80. }
  81. }
  82. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.