Friday, 27 May 2016

Make a copy of a template file and Change a word by another word in the whole file using PHP

Dear Friends
While dealing with template file, it is too common to make copies of that file and replace one word by another word.

In the code attached below one file is created dynamically based on table name and then a local copy of template file is created in the name of table in a folder HUP. Then a word HHHUUUPPP will be replaced with the name of table. Once the entire file is replaced then a fresh copy the new file will be taken and old file will be deleted.

//Code starts here.

<?php

$table=$_POST['tablename'];
$viewfile1='HUP/view'.$table.'1.php';
$viewfile='HUP/view'.$table.'.php';
copy('HUPViewtable.php',$viewfile1);

$myfilemain=fopen($viewfile, "w") or die("Unable to open file!"); //Open table structure file for
$myfiletemp = fopen($viewfile1, "r") or die("Unable to open file!"); //Open table structure file for
while(!feof($myfiletemp)) // Reading the table structure file
{
  $line= fgets($myfiletemp) ;
  $rtext=str_replace("HHHUUUPPP",$table,$line);
  fwrite($myfilemain,$rtext);
}
fclose($myfilemain);
fclose($myfiletemp);
unlink($viewfile1);
?>

Delete all files from a folder using PHP

Dear friends,
In some cases we will be forced to clear the contents of some server folders. Use the code given below.

//Code starts here

<?php

$files = glob('HUP/*'); // get all file names
foreach($files as $file)
{ // iterate through the files in the folder
  if(is_file($file))
    unlink($file); // delete file
}
?>

Create Zip file out of your Folder using PHP

Dear Friends,
Use this code to generate and download zip files. NB: no echo statements should be there in your code. If so should comment it.

//Code starts below


<?php

$file_names=array();

$dir="HUP/";
if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            $file_names = array();
            while (false !== ($file = readdir($handle))) {
                if (is_file($dir.$file) && $file != basename($_SERVER['PHP_SELF'])) $file_names[] = $file;
            }
            closedir($handle);
            if (is_array($file_names)) sort($file_names);
          
        }
    }

$error = "";      //error holder
$file_path="HUP/";
//echo "entered 1";
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
//echo "entered 2";
    if(count($file_names) > 0)
    {  
    //echo "entered 3";
        // Checking files are selected
        $zip = new ZipArchive();            // Load zip library
        $zip_name = time().".zip";          // Zip name
        if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){       // Opening zip file to load files
            $error .=  "* Sorry ZIP creation failed at this time<br/>";
            //echo $error;
        }
        foreach($file_names as $file){ 

            $zip->addFile($file_path.$file);            // Adding files into zip
        }
        $zip->close(); 
        //echo $zip_name;
        if(file_exists($zip_name))
       {
        //echo "entered 4";
            // push to download the zip
            header('Content-type: application/zip');
            header('Content-Disposition: attachment; filename="'.$zip_name.'"');
            readfile($zip_name);

            // remove zip file is exists in temp path
            unlink($zip_name);
       }

    }
    else
    {
        $error .= "* Please select file to zip <br/>";
    }
}
else
{
    $error .= "* You dont have ZIP extension<br/>";
}
?> 

PHP code to prevent upload of invalid image with hack script

Hi All,

Always use this code for image upload to prevent images with vulnerable scripts.

<?php

$newIm = @imagecreatefromjpeg($_FILES["image"]["tmp_name"]);
if (!$newIm) {
    // gd could not create an image from the source
    // most likely, the file was not a valid jpeg image
    header('location:userhome.php?msg=error'); // Code to direct to your home page showing error

}
else     // code to upload file
       move_uploaded_file($_FILES["image"]["tmp_name"], $target_file) or die('Error'.mysql_error());


?>

Wednesday, 25 May 2016

Process Regular Expressions in Strings

A common problem which we encounter during string processing
In the program a sentence is given which contains actual text enclosed in parenthesis. In that case to extract only those text, we can go for the below given code. The same would be of great use in pdf text extraction.

<?php

       $text="1212(HI)fjsdlf(how)sldfjs(are)sldfjslf(you)";
        preg_match_all('#\((.*?)\)#', $text, $match);      
       print_r ($match);
       
            $key=key($match);
            $val=$match[$key];
               if ($val<> ' ')
            {
                   echo $key ." = ".  $val ." <br> ";
           
                    for ($i1 = 0; $i1 <  count($val); $i1++)
                    { echo "entered";
                        $key1=key($val);
                        $val1=$val[$key1];
                        if ($val1<> ' ')
                        {
                            echo "--". $key1 ." = ".  $val1 ." <br> ";
                           
                        }
                        next($val);
                    }
             
             }
            
?>