Wednesday, 17 April 2013

Download All Files from ftp server


       $local_file = "D:/testing/files/";
        $ftp_user_name = "ftp_username";
        $ftp_user_pass = "ftp_pswd";
        
        // set up basic connection
        $conn_id = ftp_connect("122.00.00.001");

        // login with username and password
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
        $mode = ftp_pasv($conn_id, TRUE);
        $contents  =  ftp_nlist($conn_id, ".");
        foreach($contents as $file)
        { 
        $local_file=$local_file.$file;
        // try to download $remote_file and save it to $handle
        if (ftp_get($conn_id, $local_file, $file, FTP_ASCII, 0)) {
            echo "successfully written to $local_file\n";
        } else {
        echo "There was a problem while downloading $remote_file to $local_file\n";
        }
        }
        // close the connection and the file handler
        ftp_close($conn_id);
        fclose($handle);
?>

Thursday, 6 December 2012

Difference Between Unlink and Unset

unlink()

unlink() is a function for file system handling.
It will simply delete the file in context.  


Example for unlink() :

<?php
$fh = fopen('file.html', 'a');
fwrite($fh, 'Hello world!');
fclose($fh);
unlink('file.html');
?>

Unset ()

Unset () is used to destroy a variable in PHP. In can be used to remove a single variable, multiple variables, or an element from an array. It is phrased as Unset ($remove).
Also Known As: Unset Variable, Destroy Variable.

Example for unset() :

<?php
// remove a single variable
unset($a);

// remove a single element in an array
unset($my_array['element']);

// remove multiple variables
unset($a, $b, $c);
?> 

Tuesday, 27 November 2012

MySQL LEFT JOIN

The LEFT JOIN keyword returns all rows from left table and returns match rows from right table.

family Table:

PositionAge
Dad41
Mom35
Daughter17
Dog12

food Table:

MealPosition
RiceDad
DosaMom
Idly
EggDog

When we decide to use a LEFT JOIN in the query instead, all the family members be listed, even if they do not have a favorite dish in our food table.
This is because a left join will preserve the records of the "left" table.
 
<?php 
/* Make a MySQL Connection */
$query = "SELECT family.Position, food.Meal FROM family LEFT JOIN food ON 
family.Position = food.Position";
  
$result = mysql_query($query) or die(mysql_error());


// Print out the contents of each row into a table 
while($row = mysql_fetch_array($result)){
 echo $row['Position']. " - ". $row['Meal'];
 echo "
";
}
?>
Output:-
Dad - Dosa Mom - Rice Daughter - NULL Dog - Egg

MySQL INNER JOIN

The INNER JOIN keyword returns rows when there is at least one match in both tables.

family Table:

PositionAge
Dad41
Mom35
Daughter17
Dog12

food Table:

MealPosition
RiceDad
DosaMom
Idly
EggDog

The INNER JOIN keyword returns rows when there is at least one match in both tables. If there are rows in "family" that do not have matches in "food", those rows will NOT be listed.
 
<?php 
/* Make a MySQL Connection */
$query = "SELECT family.Position, food.Meal FROM family INNER JOIN food ON 
family.Position = food.Position";
  
$result = mysql_query($query) or die(mysql_error());


// Print out the contents of each row into a table 
while($row = mysql_fetch_array($result)){
 echo $row['Position']. " - ". $row['Meal'];
 echo "
";
}
?>
Output:-
Mom - Rice Dad - Dosa Dog - Egg

Friday, 2 November 2012

PHP Date()

PHP Date() - Format the Date

The required format parameter in the date() function specifies how to format the date/time.
Here are some characters that can be used:
  • d - Represents the day of the month (01 to 31)
  • m - Represents a month (01 to 12)
  • Y - Represents a year (in four digits)
 Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting:
<?PHP
         echo date("Y/m/d") . "<br/>";
        echo date("Y.m.d") . "<br/>";
        echo date("Y-m-d");
?>
 The output of the code above could be like this:
2012/11/01
2012.11.01
2012-11-01

Monday, 6 August 2012

PHP CSV File Reading


CSV File Reading In PHP

<?php
$fp = fopen('example.csv','r') or die("can't open file");
print "<table>\n";
while($csv_line = fgetcsv($fp,1024)) {
    print '<tr>';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
        print '<td>'.$csv_line[$i].'</td>';
    }
    print "</tr>\n";
}
print '</table>\n';
fclose($fp) or die("can't close file");
?>

Wednesday, 1 August 2012

PHP Unique ID's


Generating Unique ID's

 Many of us use the md5() function for this, even though it's not exactly meant for this purpose:
// generate unique string
echo md5(time() . mt_rand(1,1000000));
There is actually a PHP function named uniqid() that is meant to be used for this.

// generate unique string
echo uniqid();

// Output like this:

4bd67c947233e

// generate another unique string
echo uniqid();

// Output like this:

4bd67c9472340.

To reduce the chances of getting a duplicate, you can pass a prefix, or the second parameter to increase entropy:
// with prefix
echo uniqid('myname_');

// Output like this:

myname_4bd67d6cd8b8f


// with more entropy
echo uniqid('',true);

// Output like this:

4bd67d6cd8b926.12135106


// both
echo uniqid('myname_',true);

// Output like this:

myname_4bd67da367b650.43684647

PHP Glob() to Find Files


Using Glob() to Find Files

Many PHP functions have long and descriptive names. However it may be hard to tell what a function named glob() does unless you are already familiar with that term from elsewhere.
Think of it like a more capable version of the scandir() function. It can let you search for files by using patterns.

// get all php files
$files = glob('*.php');
print_r($files);

Output:

Array
(
    [0] => php1.php
    [1] => phptesting.php
    [2] => post_output.php
    [3] => test.php
)

To fetch multiple file types like this:

// get all php files AND txt files
$files = glob('*.{php,txt}', GLOB_BRACE);
print_r($files);

Output:

Array
(
    [0] => phptest.php
    [1] => function.php
    [2] => post_output.php
    [3] => test.php
    [4] => log.txt
    [5] => test.txt
)

PHP Redirect To Another URL


How do I redirect with PHP script?

Using headers() method, you can easily transferred to the new page without having to click a link to continue. This is also useful for search engines. Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

PHP Redirect Script

You can easily redirect using following code:
 
<?php
/* Redirect browser */
header("Location: http://www.yoursitename.com/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>

Monday, 30 July 2012

PHP fread Function


PHP - File Read

If you wanted to read all the data from the file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes, which is just what we need! The filesize function requires the name of the file that is to be sized up.

PHP Code:

$myFile = "testfile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

Output:

Floppy Jalopy Pointy Pinto 
Note: It is all on one line because our "testfile.txt" file did not have a <br /> tag to create an HTML line break. Now the entire contents of the testfile.txt file is stored in the string variable $theData.

PHP fwrite Function


PHP - File Write

We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you're good to go!
Below we are writing a couple of names into our test file testfile.txt and separating them with a carriaged return.

PHP Code:

$myFile = "testfile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "News Paper\n";
fwrite($fh, $stringData);
$stringData = "Note Book\n";
fwrite($fh, $stringData);
fclose($fh);
The $fh variable contains the file handle for testfile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testfile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained News Paper and second contained Note Book. After we finished writing we closed the file using the fclose function. 

PHP Create a File


Create a File

The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

PHP Code:

$ourFileName = "testfile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
 
The file "testfile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.
  1. $ourFileName = "testfile.txt"; Here we create the name of our file, "testfile.txt" and store it into a PHP String variable $ourFileName.
  2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w".
    Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.
  3. fclose($ourFileHandle); We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.

Sunday, 29 July 2012

PHP Unzip Zip File


Unzip Zip File

/**********************
*@file - path to zip file
*@destination - destination directory for unzipped files
*/
function unzip_file($file, $destination){
    // create object
    $zip = new ZipArchive() ;
    // open archive
    if ($zip->open($file) !== TRUE) {
        die (’Could not open archive’);
    }
    // extract contents to destination directory
    $zip->extractTo($destination);
    // close archive
    $zip->close();
    echo 'Archive extracted to directory';
}

PHP Get Real IP Address of Client


Get Real IP Address of Client

This function will fetch the real IP address of the user even if he is behind a proxy server.

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    //to check ip is pass from proxy
    {
        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

PHP Destroy Directory


Destroy Directory

Delete a directory including its contents.

/*****
*@dir - Directory to destroy
*@virtual[optional]- whether a virtual directory
*/
function destroyDir($dir, $virtual = false)
{
    $ds = DIRECTORY_SEPARATOR;
    $dir = $virtual ? realpath($dir) : $dir;
    $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
    if (is_dir($dir) && $handle = opendir($dir))
    {
        while ($file = readdir($handle))
        {
            if ($file == '.' || $file == '..')
            {
                continue;
            }
            elseif (is_dir($dir.$ds.$file))
            {
                destroyDir($dir.$ds.$file);
            }
            else
            {
                unlink($dir.$ds.$file);
            }
        }
        closedir($handle);
        rmdir($dir);
        return true;
    }
    else
    {
        return false;
    }
}

PHP List Directory Contents


List Directory Contents 

function list_files($dir)
{
    if(is_dir($dir))
      {
          if($handle = opendir($dir))
          {
              while(($file = readdir($handle)) !== false)
              {
                  if($file != "." && $file != ".." && $file != "Thumbs.db")
                  {
                      echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
                  }
              }
              closedir($handle);
          }
    }
}

Friday, 27 July 2012

HTML line break


Inserts HTML line breaks before all newlines in a string

This code is very useful when we insert large content with number of new lines in the database table.
In case of html line, it inserts <br /> for all \n.

<?php
echo nl2br("Hello \n World");
?>
OUTPUT will be

Hello
World

PHP Login Page using Session


A Simple Login Page using Session

This page aims to show a simple ‘log in’ or ‘sign in’ script written in PHP

<?php
session_start();
if (isset($_POST["submit"])) {
  if ($_POST["user"] == "nilanjan" && $_POST["pass"] == "banerjee") {
    $_SESSION["usernm"] = $_POST["user"];
  }
}
?>

<html>
<head>
<title>User Authentication</title>
</head>
<body>
<?php
if (isset($_SESSION["usernm"])) {
  echo("You are logged in!");
} else {
?>
<form method="post">
<input type="text" name="user" /><br />
<input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
}
?>
</body>
</html>

PHP Email validation


Email validation with Regular Expressions

This is also case-insensitive, so it will treat all characters as lower case. It is a really easy way to check the syntax and format of an email address.

<html>
<body>
<?php
if (isset($_POST['posted'])) {
   $email = $_POST['email'];
   $theresults = ereg("^[^@ ]+@[^@ ]+\.[^@ \.]+$", $email, $trashed);   //"\w+@\w+.\w+$"
   if ($theresults) {
      $isamatch = "Valid";
   } else {
      $isamatch = "Invalid";
   }
   echo "Email address validation says $email is " . $isamatch;
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="posted" value="true">
Enter your email address for validation:
<input type="text" name="email" value="name@example.com">
<input type="submit" value="Validate">
</form>
</body>
</html>

PHP substr_replace()



<?php
    $id = "asdfasdf";
    $id = substr_replace( $id, "00", 3, 2);
    print "New id number: $id<br/>";
?>

Output:

New id number: asd00sdf


<?php
$mystring = substr_replace("Hello World", "asdf", 0, 0);
echo $mystring . "<br />"; 

$mystring = substr_replace("Hello World", "0 w0", 4, 4);
echo $mystring;
?>

Output :

asdfHello World
Hell0 w0rld
<?php
$favs = " is good boy.";
$name = "Ram";
$favs = substr_replace($favs, $name, 0, 0);
print $favs;
?>

Output :

Ram is good boy.