Wednesday, May 7, 2014

get all images as array from a folder or directory in php

<?php
$myfull_path="/uploads";
$images=array();

if ($dir = opendir( $myfull_path)) {
    $images = array();
    while (false !== ($file = readdir($dir))) {
        if ($file != "." && $file != ".." )
        {
        $ext=strtolower(getExtension($file));
       
        if ($ext=="jpg" || $ext=="jepg" || $ext=="png" || $ext=="gif" || $ext=="bmp" )   
        {

            $images[] = $file;
        }
       
        }
    }
    closedir($dir);
}



print_r($images);

function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

?>

Get Dollar current rate with INR



<?php
function current_rate($price=1)
{
  
        $url  = "http://www.google.com/finance/converter?a=$price&from=USD&to=INR";
       $data = file_get_contents($url);
         preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
            
     $new_price = preg_replace("/[^0-9.]/", "", $converted[1]);
    

return    $new_price;
}




echo "1$==".$current_dolar_rate=current_rate(1) ." INR";
?>

check a valid file extension and size in php

<?php
    $allowed_ext = array(
             'jpg'    =>    true,
            'gif'    =>    true,
            'png'    =>    true
     );




$allowed_imagesize=1024000;

    function easy_checkvalid_ext($ext,$allowed_ext)
    {
     
     
       if($allowed_ext[$ext])
        {
            return true;
        }
       else
        {
           return false;
       }  
    
       }
   
    function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}   
 
     


      
    function easy_checkfile_size($size,$allowed_imagesize) {
    
       if($size < $allowed_imagesize)
        {    return true;}
       
       else
        {
             return false;
    
       }
    }

       $ext=getExtension($_FILES["files"]["name"]);    
      $validfile = easy_checkvalid_ext($ext,$allowed_image_format);
      $validfilesize = easy_checkfile_size($_FILES["files"]["size"],$allowed_imagesize);

if (!$validfilesize or  !$validfile)
{
echo "not a valid file format or too big size";   
}

?>

check valid Extension in php

<?php
$allowed_ext = array(
             'jpg'    =>    true,
            'gif'    =>    true,
            'png'    =>    true
     );

    function easy_checkvalid_ext($ext,$allowed_ext)
    {
     
     if($allowed_ext[$ext])
        {
            return true;
        }
       else
        {
           return false;
       }  
    
       }

 $validfile = easy_checkvalid_ext('jpg',$allowed_image_format);

if ( !$validfile)
echo "not a valid file type";
?>

Get country code by ip address in php

<?php

function get_easy_visitor_country($ip_address)
{
    if (!$ip_address)
     $ip_address=$_SERVER['REMOTE_ADDR'];
   
     $geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ip_address;
     $addrDetailsArr =@unserialize(file_get_contents($geopluginURL));
      easy_debug($addrDetailsArr);
     $result=$addrDetailsArr['geoplugin_countryCode'];
    return $result;
}


function easy_debug($obj)
{

echo "<pre>";
     print_r(  $obj);
     echo "</pre>";
 
}

?>

Monday, December 9, 2013

Get the current Page Url

<?PHP


///Get the current Page Url



function currentPageUrl() {
 $pageURL = 'http';
 if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}

 $pageURL .= "://";

 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}


echo  currentPageUrl();

?>

Check the given striong have any HTML Tags

<?PHP

  
    /*
     * Check if a string is html
     *
     * @param  string $string string to check
     * @return bool
     */
     function is_html($string)
    {
      
        if ( strlen(strip_tags($string)) < strlen($string))
        return 1;
        else
        return 0;
    }





$string="hello this is string";

echo is_html($string);



$string="hello <strong>this is string</strong>";

echo is_html($string);

?>

Check email validation with Preg_Metch

<?php


//// check email validation with  preg_metch




function checkEmail($email){
  return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}



?>

Check given number is positive and number of digits

<?php

// check number is greater than 0 and $length digits long
  // returns 1 on success
  function isNumberlength($num, $length){
  if($num > 0 && strlen($num) == $length)
  
    return 1;
    else
    return 0;
}



/// call the function with your  values








echo isNumberlength(100,5);



?>

Convert an object to an array with php

<?php



    /**
    *
    * Convert an object to an array
    *
    * @param    object  $object The object to convert
    * @reeturn      array
    *
    */



    function objectToArray( $object )
    {
        if( !is_object( $object ) && !is_array( $object ) )
        {
            return $object;
        }
        if( is_object( $object ) )
        {
            $object = get_object_vars( $object );
        }
        return array_map( 'objectToArray', $object );
    }


    /*** convert the array to object ***/

 //    $array = objectToArray( $obj );

    /*** show the array ***/



  //  print_r( $array );




?>

Check curl is install or on at your server with php

<?php





///  check curl is install or on at your server with php
function iscurlinstalled()
{
    if  (in_array  ('curl', get_loaded_extensions())) {
        return true;
    }
    else{
        return false;
    }
}









?>

Thursday, December 5, 2013

Downalod any file with php

<?php
///Downalod any file with php


function downloadFile($filename)
    {
        header("Content-disposition: filename=".$filename."");

        header("Content-type: application/octetstream");
       
        header("Pragma: no-cache");
       
        header("Expires: 0");
       
    }
   
    $filename='test.doc';
    downloadFile($filename);
   
    ?>

filter_var function in php

<?php

      // The filter_var() function Returns the filtered data TRUE on success or FALSE on failure.
     $emailid='test@test.com';
        if(!filter_var($emailid, FILTER_VALIDATE_EMAIL))
        {
           echo("E-mail ID is Invalid");
        }
       else
        {
             echo("E-mail ID is valid ");
       }
?>

Check e-mail address is valid with php

<?php

  // Check e-mail address is valid with php
         $email=$_POST['email'];
          if (!preg_match("/^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-] +)+/",$email))
            {
                  echo "Email Address Is Invalid !";
            }
          else
           {
                 echo "Email Address Is Valid !";
           }
          

?>

Check IP address by Host Name or Site url

<?php


/// get IP address by Host Name or   site url

 $ip_address = gethostbyname("www.google.com");

 echo "Your  Site IP address :". $ip_address;
?>

Check Password is Strong or weak with php

<?php


$password = "Fyfjk34sdfjfsjq7";

if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password)) {
    echo "Your passwords is strong.";
} else {
    echo "Your password is weak.";
}

?>

Redirect to page with php & javascript

/////// Redirect to  any page

function redirectToPage($page)
{

 if($page!="")
 {
    echo "<script>window.location='".$page."';</script>";
 }

}


//////////////////////// example//////////////////


redirectToPage('home.php');

Saturday, October 6, 2012

foreach loop in php example

foreach loop in php 

 

Syntax

foreach (array as value)
{
    code to be executed;

}
 
 
<?php
 
 
 $arr = array( 10, 20, 3, 40, 150);
foreach( $arr as $value )
{
  echo " $value <br />";
} 


//


$lang = array('php','java','c','c#','.net','perl');
echo "Your output here <br>"; 
 foreach( $lang as $val )
{
  echo " $val <br />";
} 

Do while loop in php

// Do While loop in php

Syntax

do
{
   code to be executed;
}while (condition); 
 
 
<?php
//print 1 to 10 number
$a = 1; 
do
{ 
echo "<br>".$a; 
 $a++; 
}while( $a < 10 );

?>
 

While loop in php examples



//  How to use while loop in php.


Syntax

while (condition)
{
    code to be executed;
}
 
 
<?php
// print  1 to 5  
$a=1;
while ($a<=5)
{
echo "\t ".$a;
$a=$a+1;
 
} 
 
?> 

Type of loop in php

There is mainly four type of loops.
Loops  are used to execute the same block of code a specified number of times in php.
 
1. for loop.
2. while loop.
3. Do-while loop.
3. foreach loop.


Syntax


for (initialization; condition; increment)
{
  code to be executed;
}


<?php 
// print  1 to 10 number 
for( $i=0; $i<10; $i++ )
{
echo "<br>".$i;
 
}
///////////////////
 
 
//Sum of ten number 
 
 
$sum = 0;
for( $i=0; $i<10; $i++ )
{
echo "<br>".$i;
$sum=$sum+$i;
}

echo " Total of 10 number =".$sum; 
 
?> 



Saturday, August 11, 2012

Remove whitespace from both sides of a string with php

//Remove whitespace from both sides of a string in php

function removeSideSpace($str)
{

return trim($str);

}

$yourString="  This  is test for the string    ";

echo " <br> Before remove the space == ".strlen($yourString);

$yourString= removeSideSpace($yourstring);

echo " <br> After remove the space == ".strlen($yourString);


?>

How to Redirect any page with php

<?php

//how  to Redirect any page with php




function  reDirect2Url($pageUrl) //  Write the function code Here
{
    if ($pageUrl!="")
    {
        header("location: $pageUrl");
    }
}



reDirect2Url("yourpageurlhere");   // called the function

?>

Tuesday, July 3, 2012

Find if url(current address) contains "?" or not with php

//  how to find the current url contains  the "?" or not
// to verify the current url has the one/single query string variable or many  string variable
function  get_urlsigntype($current_url) {
    if(strpos($current_url, '?') === false) {
        return "?";
    } else {
        return "&";
    }
}

Monday, July 2, 2012

How to get client's IP address with PHP

<?php
//  get the  client ip address and store into the variable.

$client_ipaddress = $_SERVER["REMOTE_ADDR"];
echo "Client IP is :".$client_ipaddress;
?>

Get Current file Name in php

<?php

//  get the current file name
$currentFile_Name = $_SERVER["SCRIPT_NAME"];
echo basename($currentFile_Name); 
 
?>

Comments in PHP

1. Single Line Comment

<?php
 //here is any code
//echo "this  is test";

?>



2. Multiple Line Comment

<?php
/* Here is your  code 
 
echo " this is test..."; 
echo "this is not display at screen";
*/
?>

Php tags

1.  php short tag  


<? = ?>

2. php full tag


<?php
// write your code here

?>