Friday, September 5, 2014

Iframe image upload php

You can download the source code

Index.php

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>Uploader</title>
   <link href="style/style.css" rel="stylesheet" type="text/css" />

<script language="javascript" type="text/javascript">
<!--
function startUpload(){
      document.getElementById('f1_upload_process').style.visibility = 'visible';
      document.getElementById('f1_upload_form').style.visibility = 'hidden';
      return true;
}

function stopUpload(success){
      var result = '';
      if (success == 1){
         result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
      }
      else {
         result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
      }
      document.getElementById('f1_upload_process').style.visibility = 'hidden';
      document.getElementById('f1_upload_form').innerHTML = result;
      document.getElementById('f1_upload_form').style.visibility = 'visible';      
      return true;   
}
//-->
</script>   
</head>
<body>
       <div id="container">
            <div id="header"><div id="header_left"></div>
            <div id="header_right"></div></div>
            <div id="content">
                <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onSubmit="startUpload();" >
                     <p id="f1_upload_process" style="visibility:hidden;">Loading...<br/><img src="loading.gif" /><br/></p>
                     <p id="f1_upload_form" align="center"><br/>
                         <label>File:  
                              <input name="myfile" type="file" size="30" />
                         </label>
                         <label>
                             <input type="submit" name="submitBtn" class="sbtn" value="Upload" />
                         </label>
                     </p>
                     <iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
                 </form>
             </div>             
         </div>

</body>   

</html>
---------------------------

Upload.php

<?php
   // Edit upload location here
   $destination_path = getcwd().DIRECTORY_SEPARATOR;

   $result = 0;

   $target_path = $destination_path . basename( $_FILES['myfile']['name']);

   if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
      $result = 1;
   }

   sleep(1);
?>

<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>   

Thursday, September 4, 2014

Extracting ZIP file directories in PHP

Here is the code.

<?php  $toDir= getcwd();
$fromFile = "joomlacomponent.zip";
if (!file_exists($toDir))
mkdir($toDir, 0777);
if (class_exists('ZipArchive', false))
{
$zip = new ZipArchive();
if ($zip->open($fromFile) === true AND $zip->extractTo($toDir) AND $zip->close())
return true;
return false;
}
die();
?>

Deleting all files from a folder using php

Here is the code to this.
<?php
function deleteDirectory($dirPath) {
    if (is_dir($dirPath)) {
        $objects = scandir($dirPath);
        foreach ($objects as $object) {
            if ($object != "." && $object !="..") {
                if (filetype($dirPath . DIRECTORY_SEPARATOR . $object) == "dir") {
                    deleteDirectory($dirPath . DIRECTORY_SEPARATOR . $object);
                } else {
                    unlink($dirPath . DIRECTORY_SEPARATOR . $object);
                }
            }
        }
    reset($objects);
    rmdir($dirPath);
    }
}

echo deleteDirectory("old");

?>

Creating a zip file with PHP

I recently had a requirement to create a zip file from a number of files created within my application.

Code Is bellow.

<?php
//include "class.recursivezip.php";
class recursiveZip
{
    /**
     * Recursively reads a directory and compress files 
     * 
     * @param file $src source directory
     * @param file $zip recursively adds file
     * @param file $path the file path
     */
    private function recursive_zip($src,&$zip,$path) {
        // open file/directory
        $dir = opendir($src);
        // loop through the directory 
        while(false !== ( $file = readdir($dir)) ) {
            // skip parent (..) and root (.) directory
            if (( $file != '.' ) && ( $file != '..' )) {
                    // if directory found again, call recursive_zip() function again
                    if ( is_dir($src . '/' . $file) ) {
                            $this->recursive_zip($src . '/' . $file,$zip,$path);
                    }
                    else {
                            // add files to zip
                            $zip->addFile($src . '/' . $file,substr($src . '/' . $file,$path));
                    }
            }
        }
        closedir($dir);
    }

    /**
     * Perform compression
     * 
     * @param file $source source file/direcctory for compress
     * @param file $dst destination directory where zip file will be created
     * @return zip file / folder
     */        
    public function compress($src,$dst=''){
        
        // check zip extension loaded or not 
        // and
        // check soure file/directory exists or not
        if (!extension_loaded('zip') || !file_exists($src)) {
            return false;
        }        
        
        // remove last slash (/) from source directory / destination directory
        if(substr($src,-1)==='/'){
            $src=substr($src,0,-1);        
        }
        if(substr($dst,-1)==='/'){
            $dst=substr($dst,0,-1);           
        }
        $path=strlen(dirname($src).'/');
        //$filename=substr($src,strrpos($src,'/')+1).'.zip';
        $filename=substr($src,strrpos($src,'/')).'.zip';
        $dst=empty($dst)? $filename : $dst.'/'.$filename;
        @unlink($dst);

        // create zip     
        $zip = new ZipArchive;
        $res = $zip->open($dst, ZipArchive::CREATE);
        if($res !== TRUE){
            echo 'Error: Unable to create zip file';
            exit;
        }
        if(is_file($src)){
                $zip->addFile($src,substr($src,$path));
        }
        else{
            if(!is_dir($src)){
                $zip->close();
                @unlink($dst);
                echo 'Error: File not found';
                exit;
            }
            $this->recursive_zip($src,$zip,$path);
        }
        $zip->close();
        return $dst;
    }
} // end class file
 
 
 
//------- for mac ------------------
    // Always use absolute path
$src=$_SERVER['DOCUMENT_ROOT']."/";
    $dst=$_SERVER['DOCUMENT_ROOT'];
$z= new recursiveZip();
echo $z->compress($src,$dst);

?>