note 99669 deleted from function.http-put-file by sobak

From: Date: Sun, 04 Dec 2016 07:23:19 +0000
Subject: note 99669 deleted from function.http-put-file by sobak
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208074@lists.php.net to get a copy of this message
Note Submitter: D&#39;n Russler d_n att CatchMedia dott com ---- After much frustration and very little documentation that I could find, I thought I'd offer this example of implementation of http_put_file with custom HTTP headers, and the corresponding ReceiveFile.php. I do an http put with a customized header containing parameters for file processing. <?php $header = array( 'file_size' => $file_size , 'file_name' => $file_name , 'md5sum' => $md5sum ); $URI = 'http://MyDomain.com/ReceiveFile.php'; if (($f = @fopen($URI,'r'))) { fclose($f); if ($result = @http_put_file($URI, $file_path, array( headers => array( 'X_CUSTOM_PUT_JSON' => json_encode($header) ,'X_FRUIT' => 'bananna' ) , useragent => 'Magic UnitTests' ) , $info))) { echo str_replace("\n",'<BR>',$result); } else echo 'http failure'; } else echo "Can't find URI: [$URI]"; ?> ReceiveFile.php has: <?php $CUSTOM_HEADER = 'HTTP_X_CUSTOM_PUT_JSON'; $CHUNK = 8192; try { if (!($putData = fopen("php://input", "r"))) throw new Exception ("Can't get PUT data."); if (!(array_key_exists($CUSTOM_HEADER, $_SERVER))) throw new Exception ("Custom header missing.") $json = json_decode($_SERVER[$CUSTOM_HEADER], true); $this->logParams(__FUNCTION__, $json); foreach ($json as $fld => $val) $$fld = $val; // now the params can be used like any other variable // see below after input has finished $tot_write = 0; // Create a temp file if (!($tmpFileName = tempnam("/tmp", "PUT_FILE_"))) throw new Exception ("Can't create tmp file."); // Open the file for writing if (!($fp = fopen($tmpFileName, "w"))) throw new Exception ("Can't write to tmp file"); // Read the data a chunk at a time and write to the file while ($data = fread($putData, $CHUNK)) { $chunk_read = strlen($data); if (($block_write = fwrite($fp, $data)) != $chunk_read) throw new Exception ("Can't write more to tmp file"); $tot_write += $block_write; } if ( ! fclose($fp) ) throw new Exception ("Can't close tmp file"); unset($putData); // Check file length and MD5 if ($tot_write != $file_size) throw new Exception ("Wrong file size"); $md5_arr = explode(' ',exec("md5sum $tmpFileName")); $md5 = $md5sum_arr[0]; if ($md5 != $md5sum) throw new Exception ("Wrong md5"); ?>

« previous php.notes (#208074) next »