add

Showing posts with label remote Server file. Show all posts
Showing posts with label remote Server file. Show all posts

Thursday, October 4, 2012

Fetch files from remote server automatically in PHP using Curl

PHP provides multiple ways to download and upload files to remote servers, such as fopen, fsockopen, cURL library, and other methods. fopen is the simplest but not the best. A while ago I wrote a function to fetch remote file by using fsockopen. However, I found a lot of problems when I use it. Then I read the PHP Cookbook and decided to try cURL library. After I implemented it in the independent class, it works like a charm. The following is the class source code.


// I adopt cURL library to download files
// It is reliable and fast, less hassle than fopen/fsockopen etc.

// this following three lines include testing code
// $file = new Remotefile("http://downloads.pcworld.com/pub/new/patches___drivers/utilities/framxpro.zip");
// $file->save2file("");
class Remotefile
{
 // the url components
 private $url = "";
 // data get back from server
 private $header  = array();
 private $content = "";
 private $extension = "";

 function __construct($url)
 {
  $this->initialize($url);
 }

 private function curl_url()
 {
  $c = curl_init($this->url);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($c, CURLOPT_HEADER, 1);
  $buffer = curl_exec($c);
  curl_close($c);

  // process data
  $rnrn = "\r\n\r\n";
  $pos = strpos($buffer,$rnrn);

  if($pos === false)
  {
   // string $rnrn NOT found in $buffer
    echo "Something is not correct!
";
  }
  else
  {
   // string $rnrn found in $buffer
   $this->content = substr($buffer, $pos+4);
   $header = substr($buffer, 0, $pos);
   $this->processHeader($header);
  }
 }

 private function initialize($url)
 {
  // initialize all variables
  $this->url = $url;
  // fetch the remote file
  $this->curl_url();
 }

 private function processHeader($header)
 {
  $lines = explode("\r\n", $header);
  $this->header["status"] = $lines[0];
  foreach($lines as $line)
  {
   $data = explode(": ",$line);
   if ($data[1] != "")
   {
    $this->header[$data[0]] = $data[1];
   }
//echo "$data[0] |===| $data[1]
";
  }
 }

 private function redirectedURL()
 {
  return $this->header["Location"];
 }

 private function getMIMEtype()
 {
  // check redirection url
  $rdurl = $this->redirectedURL();
  if ($rdurl)
  {
   $ext = ereg_replace("^.+\\.([^.]+)$", "\\1", $rdurl);
   $this->extension = $ext;
  }
  else
  {
   $mtype = $this->header["Content-Type"];
   $temps1 = split("/",$mtype);
   $temps2 = split(";",$temps1[1]);
   $ext1 = $temps2[0];
   $this->extension = $ext1;
   if (($temps1[0] == "application"))
   {
    $ext2 = ereg_replace("^.+\\.([^.]+)$", "\\1", $this->url);
    if ($ext2)
    {
     $this->extension = $ext2;
    }
   }
       }
       $this->extension = trim($this->extension);
//echo "file extension = ".$this->extension."
";
 }

 function getHeader()
 {
  return $this->header;
 }

 function getContent()
 {
  return $this->content;
 }

 function save2file($folder)
 {
  // write to file
  $this->getMIMEtype();
  $filename = date('YmdHis').".".$this->extension;
  $target_path = getcwd();
  if ($folder)
  {
   $target_path .= "/$folder";
  }
  $target_path .=  "/".$filename;
  $Handle = fopen($target_path, 'w');
  fwrite($Handle, $this->content);
  fclose($Handle);
  return $filename;
 }

}

?>
I adopt cURL library to download files. It is reliable and fast, less hassle than fopen/fsockopen etc. To use the above class, at Ubuntu yot have to install libcurl and php5-curl by the following command:
apt-get install curl libcurl3 libcurl3-dev php5-curl
After this is done, just restart apache2 server by
/etc/init.d/apache2 restart

Wednesday, July 4, 2012

post a file using PHP to remote server without ftp


Recently I was working for a product where i have to post a file to a remote server where remote server dont allow outbout FTP.
And in this process i found a couple of methods to post file to server;

my required file was in Xml and have to post that xml to remote server where I can fetch that data
Its quite simple and easy method.

here are my findings

local file name : postfile.php
remote file name : receivexml.php

code for postfile.php


$thistext="<?xml version="1.0"?>
        <SERVICES>
          <serv1234>
                <short>1234</short>
                <isuser>0</isuser>
                <keyword>keyword</keyword>
                <table>wltable</table>
                <expiry>
                        <expiry_status>1</expiry_status>
                        <expiry_startdate>04-JUL-12</expiry_startdate>
                        <expiry_enddate>27-JUL-12</expiry_enddate>
                        <expiry_message>Expiry Message</expiry_message>
                </expiry>
             
          </serv1234>
        </SERVICES>";



$ch = curl_init('http://rem.ote.server.ip/receivexml.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $thistext);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/xml',
'Content-Length: ' . strlen($thistext)) );                                                                                                                  
$result = curl_exec($ch);
print_r($result);
curl_close($ch);

code for  receivexml.php


echo "test xml";
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
    $postText = file_get_contents('php://input');
}
//print_r($postText);
$shortcode='';
$xml = new SimpleXMLElement($postText);
$result = $xml->xpath('/SERVICES/ serv1234/short');
while(list( , $node) = each($result)) {
    echo $short=$node;
}
$myFile = "/directory/path/to/xml/".$short.".xml";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData=$postText;
fwrite($fh, $stringData);
fclose($fh);
?>

in receivexml.php
  1. received the file and stored in  $postText
  2. parsed the xml data with xpath
  3. set the file name to a tag value in this case "short"
  4. write data to file.