Monday, September 30, 2013

Php FTP Functions ( phpfox )


This is a simple function to connect to an ftp and download the xml files from that ftp to a specified folder in our server

$ftp_server = 'abcdefg.com';      // FTP Server Address (exlucde ftp://)
        $ftp_user_name = 'abcuser';     // FTP Server Username
        $ftp_user_pass = 'abcpass';      // Password
        // Connect to FTP Server
        $conn_id = ftp_connect($ftp_server);
        // Login to FTP Server
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
        // Verify Log In Status
        if ((!$conn_id) || (!$login_result))
        {
           Phpfox_Error::set('FTP connection has failed!Attempted to connect to'. $ftp_server.' for user'. $ftp_user_name);
        } else {
           Phpfox::addMessage('Connected to '. $ftp_server .', for user '. $ftp_user_name);
        }
        $contents = ftp_nlist($conn_id, ".");
        foreach($contents as $currentFile)
        {
            // to check directory ('0') or file('1')
            $fType =  Phpfox::getService('moduleName')->is_ftp_dir($currentFile, $conn_id);
            $ext = pathinfo($currentFile, PATHINFO_EXTENSION);
            if($ext == 'xml')
            {        
                // define some variables
// check whether the xml is already downloaded and saved in Database
                $getxmlDetailsFromDb = Phpfox::getService('moduleName')->getxmlDetailsFromDb($currentFile);
                if($getxmlDetailsFromDb['xml_name'] =='')
                {
                    $local_file = Phpfox::getParam('core.dir_file').'xml/'.$currentFile;
                    $server_file = $currentFile;
                    // try to download $server_file and save to $local_file
                    if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY))
                    {
// inserting the downloaded xml name to DB by giving ftpconnect as download type which is used for future reference.
                        $uptype = 'ftpconnect';
                        $XMLtoDB = Phpfox::getService('moduleName')->insertXMLnameToDb($server_file,$uptype);
                    }
                }
               
            }
        }
         // close the FTP connection
        ftp_close($conn_id);

// reading xml datas from DB
        $getxmlDatas = Phpfox::getService('moduleName')->getxmlDatas();
        foreach ($getxmlDatas as $keyxml => $valueXML)
        {
            // reading each xml and fetching the datas.
            $xml=simplexml_load_file(Phpfox::getParam('core.dir_file').'xml/'.$valueXML['xml_name']);
// converting the xml object to array.
            $array = Phpfox::getService('moduleName')->object_to_array($xml);
}

// by printing this '$array' we will get the xml values as
echo '<pre>';
print_r($array);
echo '</pre>';


public function object_to_array($obj)
    {
        if(is_object($obj)) $obj = (array) $obj;
        if(is_array($obj))
        {
            $new = array();
            foreach($obj as $key => $val)
            {
                $new[$key] = $this->object_to_array($val);
            }
        }
        else $new = $obj;
        return $new;      
    }


Reference : php.net

Random Password Generation in php

This is a simple function to Generate random passwords in php applications



     /**
     * random password generator
     * @return type
     * @author Arun George <arun@arun-g.in>
     * @since 30-09-2013
     */
    public function randomPassword()
    {
        $Inputs = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $password = array(); //declare $password as an array
        $aLength = strlen($Inputs) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++)
        {
            $num = rand(0, $aLength);
            $password[] = $Inputs[$num];
        }
        return implode($password); //turn the array into a string
    }

Friday, September 13, 2013

VIN Validation with PHP

Vehicle Identification Number Validation


$vin = '1G1YW2DW0A5108451';


function vinValidate($vin){
 
    $transliteration = array(
        'A'=>1, 'B'=>2, 'C'=>3, 'D'=>4, 'E'=>5, 'F'=>6, 'G'=>7, 'H'=>8,
        'J'=>1, 'K'=>2, 'L'=>3, 'M'=>4, 'N'=>5, 'P'=>7, 'R'=>9,
        'S'=>2, 'T'=>3, 'U'=>4, 'V'=>5, 'W'=>6, 'X'=>7, 'Y'=>8, 'Z'=>9,
    );

    $weights = array(8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2);
       
        $vin = strtoupper($vin);
        $length = strlen($vin);
        $sum = 0;

        if($length != 17)
        {
            return array('status'=>false, 'message'=>'VIN is not the right length');
        }

        for($x=0; $x<$length; $x++)
        {
            $char = substr($vin, $x, 1);

            if(is_numeric($char))
            {
                $sum += $char * $weights[$x];
            }
            else
            {
                if(!isset($transliteration[$char]))
                {
                    return array('status'=>false, 'message'=>'VIN contains an invalid character.');
                }

                $sum += $transliteration[$char] * $weights[$x];
            }
        }

        $remainder = $sum % 11;
        $checkdigit = $remainder == 10 ? 'X' : $remainder;

        if(substr($vin, 8, 1) != $checkdigit)
        {
            return array('status'=>false, 'message'=>'The VIN is not valid.');
        }

        return array('status'=>true, 'message'=>'The VIN is valid.');
    }
   



Thanks coderelic

Wednesday, September 4, 2013

Very Simple PHP Captcha

Very Simple PHP Captcha :
Very easy and it requires only a couple lines of code. Please follow the below steps.

Step 1
The first step is to create a HTML form which is later submitted.
I assume you already have a HTML form, so I'll only focus on the captcha code and not all the other fields.
 
<?php
session_start();
echo '<form action="something.php" method="post">';
$rand_int1 = substr(mt_rand(),0,2);
$rand_int2 = substr(mt_rand(),0,1);
$rand_int3 = substr(mt_rand(),0,1);
$captcha_answer = $rand_int1 + $rand_int2 - $rand_int3;
$_SESSION['captcha_answer'] = $captcha_answer;
echo 'What is '.$rand_int1.' + '.$rand_int2.' - '.$rand_int3.'?<br>
<input type="text" name="captcha">
<input type="submit" value="Do captcha">
</form>';
?>


Step 2
The second step is collecting the form data and check if captcha is correct.
 
<?php
session_start();
$captcha = $_POST['captcha'];
$captcha_answer = $_SESSION['captcha_answer'];
 
if($captcha != $captcha_answer) {
    echo 'Captcha is incorrect!';
}
else {
    echo 'Captcha is correct, congratulations! :)';
}
?>


Thanks : ITDB

Tuesday, September 3, 2013

Function for Date Selection


Function for Date Selection. Its simply superb & cool...



<?PHP

    FUNCTION DateSelector($inName, $useDate=0)
    {
        /* create array so we can name months */
        $monthName = ARRAY(1=> "January", "February", "March",
            "April", "May", "June", "July", "August",
            "September", "October", "November", "December");

        /* if date invalid or not supplied, use current time */
        IF($useDate == 0)
        {
            $useDate = TIME();
        }

        /* make month selector */
        ECHO "<SELECT NAME=" . $inName . "Month>\n";
        FOR($currentMonth = 1; $currentMonth <= 12; $currentMonth++)
        {
            ECHO "<OPTION VALUE=\"";
            ECHO INTVAL($currentMonth);
            ECHO "\"";
            IF(INTVAL(DATE( "m", $useDate))==$currentMonth)
            {
                ECHO " SELECTED";
            }
            ECHO ">" . $monthName[$currentMonth] . "\n";
        }
        ECHO "</SELECT>";

        /* make day selector */
        ECHO "<SELECT NAME=" . $inName . "Day>\n";
        FOR($currentDay=1; $currentDay <= 31; $currentDay++)
        {
            ECHO "<OPTION VALUE=\"$currentDay\"";
            IF(INTVAL(DATE( "d", $useDate))==$currentDay)
            {
                ECHO " SELECTED";
            }
            ECHO ">$currentDay\n";
        }
        ECHO "</SELECT>";

        /* make year selector */
        ECHO "<SELECT NAME=" . $inName . "Year>\n";
        $startYear = DATE( "Y", $useDate);
        FOR($currentYear = $startYear - 5; $currentYear <= $startYear+5;$currentYear++)
        {
            ECHO "<OPTION VALUE=\"$currentYear\"";
            IF(DATE( "Y", $useDate)==$currentYear)
            {
                ECHO " SELECTED";
            }
            ECHO ">$currentYear\n";
        }
        ECHO "</SELECT>";

    }
?>

<HTML>
<BODY>
<FORM>
Choose a Date: <?PHP DateSelector( "Sample"); ?>
</FORM>
</BODY>
</HTML>

Thanks : Psoug