Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: PHP

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: PHP
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Backup Database using Perl Script

Backup Database from Perl Script

 


Sometime we  need to Regularly Take Our Database Backup then Will Do this Our Process Simple By Using the perl script.

backup.pl


#!/usr/bin/perl -w
use DBI;
use Mail::Sender;

$space = ' ';

#### Read the backup directives
open(CONF, "<$ARGV[0]") || die "\nCan't open CONF file.\nPlease specify the full name and path of the .autoArchive.conf file.\n";
while ($line = <CONF>){
      if ($line =~ /^(\S+)\s+=\s+'(\S+)';/){
         my ($var, $value) = (substr($1,1,length($1)), $2); 
         $$var = $value;               
         }
      }
close(CONF); 

#### Build list of DBs
if ($all_dbs eq 'yes'){
   @selected_dbs = get_dbs();
   }

#### Loop through DBs in list
while ($selected_dbs[$db_loop]){
      #### Build list of tables for this DB
      if ($all_tables eq 'yes'){
         @selected_tables = get_tables();}
      archive_data();
      $db_loop++;
      }

#### Get all the DB names
sub get_dbs{
    $dbh = logon();
    $sth = $dbh->prepare("show databases") 
        or die "Can't create SQL statement\n$DBI::errstr";
    $rc  = $sth->execute 
        or die "Can't execute SHOW DATABASEs\n$DBI::errstr";

    while ($db_name = $sth->fetchrow_array) {
          $dbs [$db_count++] = $db_name;
          }
    logoff();
    return @dbs;
    }

#### Get all the table names
sub get_tables{
    $table_count = 0;
    $db_in       = $selected_dbs[$db_loop];
    $dbh         = logon();

    $sth = $dbh->prepare("Show Tables")    
        or die "Can't create SQL statement: $DBI::errstr";
    $rc  = $sth->execute 
        or die "Can't SHOW tables in $db_in's database: $DBI::errstr";   

    while ($table_name = $sth->fetchrow_array){
          $tables [$table_count++] = $table_name . ' ';
          }
    logoff();
    return @tables;
    }

 #### DBI Logon process
 sub logon{
     $dbh = DBI->connect("DBI:mysql:$db_in:$db_host:$db_port", $user, $password)
          or die "Can't logon to database:\n$DBI::errstr";
     }

 #### DBI Logoff process
 sub logoff{
     return $dbh->disconnect;
     }

 #### Backup the database
 sub archive_data{
     $time_in = time();
     if ($user ne ''){
        $logon = '--user=' . $user;}
     if ($password ne ''){
        $logon = $logon . ' --password=' . $password;}

     $month     = substr($time = localtime, 4, 3);
     if (($day  = substr($time, 8, 2)) < 10){
        $day    = '0' . substr($day, 1, 1);}
     $year      = substr($time, 20, 4);
     $date      = $month . $date_seperator . $day . $date_seperator . $year;
     $dump_file = $dump_directory . $selected_dbs[$db_loop] . '.' . $date . '.' . $dump_extension;   

     $dump_command = $dump_path .$dump_prog   . $space . 
                     $dump_parms              . $space .
                     $logon                   . $space .
                     $selected_dbs[$db_loop]  . $space .
                     '>'                      . $space .
                     $dump_file;

     $gzip_command = $gzip_path . $gzip_prog  . $space .
                     $gzip_parms              . $space .
                     $dump_file;

     $OS_return .= `$dump_command`;
     $OS_return .= `$gzip_command`;

     $time_out = time();
     mail_archive();
     }

 #### Email the backup files
 sub mail_archive{
     if ($smtp_auth eq 'yes'){
        pop_authentication();}

     $time_taken       = elapsed_time();
     $email_subject    = $selected_dbs[$db_loop] . ' DB Backup - ' . $date;
     $email_attachment = $dump_file . $gzip_extension;
     $message_body     = 'Note:  The database backup took: ' . $time_taken . ' to complete.';
     print "$smtp, $email_from, $email_to, $email_subject\n$message_body\n$email_attachment\n";
     $sender = new Mail::Sender 
                       {smtp    => $smtp,   
                        from    => $email_from};
     $sender->MailFile({to      => "$email_to",
                        subject => "$email_subject",
                        msg     => "$message_body",
                        file    => $email_attachment})
           or die "Backup file EMailing Failed.\n$Mail::Sender::Error\n";
     }

 ### Note execution time
 sub elapsed_time{
     $timediff = $time_out - $time_in;
     $hours    = int ($timediff / 3600);
     $minutes  = int ($timediff / 60);
     $seconds  = $timediff - ($hours * 3600) - ($hours * 60);     
     return $hours . ' hrs ' . $minutes . ' mins ' . $seconds . ' secs ';
     }

 ### POP3 Logon
 sub pop_authentication{
     use Mail::POP3Client;
     $pop = new Mail::POP3Client(USER     => $pop_user,
                                 PASSWORD => $pop_pwd,
                                 HOST     => $pop,
                                 DEBUG    => 99)
         or die "POP3 Authentication Failed.\n$Mail::POP3Client::Error\n";
     $pop->Close();
     }

autoArchive.conf

$db_host         = 'localhost';                # What box is the DB on?
$db_port         = '3306';                     # What port should an external DB be contacted on
$user            = 'dbusername';               # What is the DB's userid
$password        = 'dbpassword';               # What is the DB's password


$email_to        = 'somebody@yoursite.com';    # Who should receive the backup file?
$email_from      = 'somebody2@yoursite.com';   # Whom should the job say it is from?
$smtp            = 'localhost';                # Name of SMTP server
$smtp_auth       = 'yes';                      # SMTP requires POP3 authentication?
$pop             = 'localhost';                # Name of POP3  server
$pop_user        = 'popusername';              # POP3 userid for SMTP authentication
$pop_pwd         = 'poppassword';              # POP3 password for SMTP authentication

$all_dbs         = 'no';                       # Should this job backup every database?
@selected_dbs    = qw['yourdbname'];           # If no, above, which databases should be backed up?

$all_tables      = 'no';                       # Should all of a database's tables be backed up?
@selected_tables = qw['table1','table2'];      # If no, above, which tables should be backed up?

$dump_prog       = 'mysqldump';                # What should be used to dump the tables?
$dump_path       = '/usr/bin/';                # Where can the dump program be found?
$dump_parms      = '--opt';                    # What options should the dump program receive?
$dump_directory  = '/backup/location/';        # Where should the backup files be written?
$dump_extension  = 'DB_Backup';                # What suffix should be applied to the backup files?

$gzip_prog       = 'gzip';                     # What zip program should be used?
$gzip_path       = '/bin/;                     # Where can the zip program be found?
$gzip_parms      = '-9f';                      # What options should the zip program receive?
$gzip_extension  = '.gz';                      # What suffix should be applied to the zipped files?

$date_seperator  = '-';                        # What should be used to seperate the date components in the file name?



Then We Just need to Run this Script in Cron Job in Our Website it will daily backup your database and emailed to you.


Cron Command

30 */12 * * * perl /path/to/backup.pl

This will run cron every 12 hours at half past of hour.

Thanks

PHP Live Edit Table Example

PHP Live Edit Table Example

Today We See How To Make Live Editable Using PHP+JS+Mysql+Ajax

Let's Start.

For Updating Data Live in Our Database.

1. Let's First Going TO Start My Server.

2.Opening PHPMyadmin and Creating a Database Named "live"

and also a table name "live_data".


live.php (code )  //Our View Page
 
<?php
include 'connect.php';
//==========Checked Connection Establish or Not.==============
if(!$con1){

	echo "Failed TO Establish Database Connection";
	die();
	//===========Stop Execution if connection failed============

}
else{
	//===========Fetching Result from table live_data==================
	$qr=mysql_query("select * from live_data");

	//=========adding border so it look good===============
	echo "<table style='border-collapse:collapse;' border='1'>";

	//============adding heading for each column=========================
	echo "<tr><th>ID</th><th>NAME</th><th>DOB</th><th>Qualification</th></tr>";
	while ($row=mysql_fetch_assoc($qr)) {

		//============Printing All Data in Table Row========

		//============data is html5 attribute for adding exta information on html page===
		echo "<tr>";
		echo "<td class='id' data-id='".$row['id']."' >".$row['id']."</td>";
		echo "<td class='item' data-name='name'>".$row['name']."</td>";
		echo "<td class='item' data-name='dob'>".$row['dob']."</td>";
		echo "<td class='item' data-name='qualification'>".$row['qualification']."</td>";
		echo "</tr>";
	}
	echo "</tr>";
}
?>
<script  src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
	//===========Events Call When Our Page is Ready======
	$(document).ready(function() {
		

		//=============adding double click event on each table cell==========
		$(document).on("dblclick",".item",function(){

			//=======get The Value Of Current Selected TD using this keyword======
			var values=$(this).text();
			$(this).html("<input value='"+values+"' class='input'>");

		});

		$(document).on("blur",".input",function(){

			var vales=$(this).val();

sendToServer($(this).val(),$(this).parent("td").parent("tr").children(".id").data("id"),$(this).parent("td").data("name"));
									$(this).parent("td").text(vales);
			                      $(this).remove();
		})




function sendToServer(value,id,key){



			$.ajax({
				url: 'api.php',
				type: 'POST',
				data: {key:key,id:id,value:value},
			})
			.done(function(data) {
				alert(data);
			})
			.fail(function() {
				alert("Network error");
			});

			}

	})
</script> 

connect.php (Database Connection file)
 
<?php
//================+Connecting Database================
$con=mysql_connect("localhost","root","");

//=============Selecting Database======================
$con1=mysql_select_db("live",$con);

api.php (Our Api Which Update Our Date When We Post Through Ajax)
 
<?php
include 'connect.php';
if($_REQUEST['key']=="name"){
$qr=mysql_query("UPDATE live_data set name='".$_REQUEST['value']."' where id='".$_REQUEST['id']."'");
echo "Updated";
}
else if($_REQUEST['key']=="dob"){
$qr=mysql_query("UPDATE live_data set dob='".$_REQUEST['value']."' where id='".$_REQUEST['id']."'");
echo "Updated";	
}
else if($_REQUEST['key']=="qualification"){
	$qr=mysql_query("UPDATE live_data set qualification='".$_REQUEST['value']."' where id='".$_REQUEST['id']."'");
echo "Updated";
}
else{
	echo "Key Not Found";
}

Video Tutorial
0

PHP Date Time Difference

PHP Date Time Difference


Code

<?php

//======End date in YYYY-MM-DD HH:MM:SS format===
$date1=$_REQUEST['end'];

//======Start date in YYYY-MM-DD HH:MM:SS format===
$date2=$_REQUEST['start'];


//=======For Difference in Seconds=========
$data['seconds']=strtotime($date1)-strtotime($date2);

//=======For Difference in Minutes=========
$data['minutes']=(strtotime($date1)-strtotime($date2))/60;

//=======For Difference in Hours=========
$data['hrs']=((strtotime($date1)-strtotime($date2))/60)/60;

//=======For Difference in Days=========
$data['day']=round((((strtotime($date1)-strtotime($date2))/60)/60)/24);


//=======For Difference in Week=========
$data['week']=round(round((((strtotime($date1)-strtotime($date2))/60)/60)/24)/7);


//==============For Differnce in Month=================
$year1 = date('Y', strtotime($date2));
$year2 = date('Y', strtotime($date1));

$month1 = date('m', strtotime($date2));
$month2 = date('m', strtotime($date1));

$diff = (($year2 - $year1) * 12) + ($month2 - $month1);

$data['month']=$diff;


//=======For Difference in Year=========
$data['year']=date('Y', strtotime($date1))-date('Y', strtotime($date2));

//===========Printing All Results in JSON Data=========
echo json_encode($data);

PHP File Handling

PHP File Handling

php file handling

For New Beginners I know They Think What is File Handling?
In Simple Word Reading and Writing in Files is Called file handling. 

Let's Start:-

1.How we Open Files Using PHP and Read its Contents.
2.How To write in Files.
3.How to Append Text on Existing Files After Old Contents.
4.How to Append Text on Existing Filed Before Old Contents.


List Of Some Important Function Of File Handling.
readfile("path/to/file");  : -   Simply Read the Contents of text files.

file_get_contents("path/to/file"); : - Get Contents from anytypes of file.

fopen("path/to/file","r");  : - fopen is a standard php function used for Opening and writing in files. In its Second Parameter we Passed the mode How we Opening the file.  

fread("file_open_fopen_file",filesize("path/to/file")) : - fread read the file contents.

fclose("file_open_fopen_file") : - Used to Closed the  Open file.

feof("file_open_fopen_file") : - Used to check reached the end of file when reading file line by line in loop.

fgets("file_open_fopen_file") : -Used To Read file Line by line.

fgetc("file_open_fopen_file") : - Used to Read file character by Character.

fwrite("file_open_fopen_file","contents") : - Used to write the contents in opened file.


Here is a List Of Modes For Opening Files.

r    For Reading Only : - For Reading From the Beginning of files.

w   Open a file for write only : - Erase The Contents of Old file if exist and create the new contents.

a   Open a file for write only : -  Used For Appending the contents on Already Exist File if File not Exist Create a new File.

x   Creates a new file : - Create a new file for writing . It Returns false if filename already exist.

r+  Open a file for read/write : -  Used For Reading and Writing Cursor at the beginning.

w+ Open a file for read/write : - Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file.

a+  Open a file for read/write : - Existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist.

x+  Creates a new file for read/write : - Returns FALSE and an error if file already exists


Code 1 . Reading Files Using All Methods and Prints the Contents: 


<?php

//=======file_get_contents("filename")=======================
echo "This is The Contents of file.txt Reading Using file_get_contents function()  : = ".file_get_contents("file.txt")."<br>";
echo "<hr>";


//======readfile("filename")==============
echo "This is The Contents of file.txt Reading Using readfile()  : = <br>".readfile("java.txt")."<br>";
echo "<hr>";


//========fread(fopen("filename"),filesize("filename"))=============
echo "This is The Contents of file.txt Reading Using fopen function()  using mode <b>r</b> : = ".fread(fopen("javascript.txt","r"),filesize("javascript.txt"))."<br>";

php read file


Code 2. Simple Writing Contents in Files

 
<?php

//===Creating File Using file_put_contents (If file Not Exist Then Create a New File)====
file_put_contents("newfile.txt","Hello i am writing data in newfiles.txt");

//==Writing Contents in file using fwrite (If file Not Exist Then Create a New File)============

$file=fopen("newfile2.txt","w");
fwrite($file,"I am New String and Writing Data in newfile2.txt");
fclose($file);


php write


Code 3 . Appending Text in Already Exist Files After The Old Contents

<?php

//===Appending Text in Already Exist Files After The Old Contents=====


$file=fopen("file.txt","a");
fwrite($file,"I am New String and Writing Data in newfile2.txt");
fclose($file);

php write


Code 4 . Appending Text in Already Exist Files Before The Old Contents

<?php

//===Appending Text in Already Exist Files Before The Old Contents======

$file=fopen("file.txt","r+");
fwrite($file,"I am New String and Writing Data in newfile2.txt");
fclose($file);
 

Code 5 . Reading Long Text File Line By Line
<?php

//========Reading File Line By Line==========

$file=fopen("filelong.txt","r");
// Output one line until end-of-file
while(!feof($file)) {
    echo fgets($file) . "<br>";
}
fclose($file);


php read line


Code 6 . Reading Long Text File Character By Character
<?php

//========Reading File Character By Character==========

$file=fopen("filelong.txt","r");
// Output one line until end-of-file
while(!feof($file)) {
    echo fgetc($file) . "<br>";
}
fclose($file);
Download Complete Source Code : Download

How To Install Laravel

How To Install Laravel



Before Start Installing Laravel Let's first Know What is Laravel. i Know Some PHP Developers know about What is Laravel . But For rest Laravel is a PHP frameworks which Maker our Easy By Using OOP Concept of MVC (Model+view+controller). 


Model = Our Data Provider (E.g Database .)
View = Our HTML Page 
Controller = Our Login and Functions.

Routes:
 
All the Request in laravel whether its GET or POST  must be passed through a file (web.php or routes.php) this files handles routing means where we send the user in POST or GET Request.

Let's Start Installing (Currently i am Using Ubuntu).

Step 1: Install PHP  (if Already installed Skip it)

Code : sudo apt-get install php

Step 2 : Install PDO Extension (If already Installed Skip it)

Code : sudo apt-get install php-mysql  
Step 3 : Install PHP Mbstring (if already install Skip it)

Code : sudo apt-get install php-mbstring

Step 4 : Install PHP xml (if already install Skip it)

Code : sudo apt-get install php-xml

Step 5 : Install PHP zip (if already install Skip it)

Code : sudo apt-get install php-zip

Step 6 : Install PHP Composer (if already install Skip it)

Code :

curl -sS https://getcomposer.org/installer | sudo php -- --install- dir=/usr/local/bin --filename=composer

Step 7  : Install Laravel (if permssion problem try with sudo)

Code : composer global require "laravel/installer" 

Step 8 : Create Laravel Project

Code : composer create-project --prefer-dist laravel/laravel blog "5.3.*"

Now Open blog folder

cd blog
Run: -
command php artisan serve

Now Local Development Server is Ready open the given url in console.

Laravel Run at Default port is 3000 but if your 3000 port is already using some application .

Change the port when running

Command :  php artisan serve --port=3001
 

laravel install

0

How To Read CSV File Using PHP

How To Read CSV File Using PHP

php csv parser


When Creating Business Tool for any Company or ERP System Sometime we Need to Parse the csv data of Clients  which contains informations of companies like products, survey anything that comes in csv.

Now How We Parse Such types of Data and Create a new file from that or Show the Current file Data.?

Let's Start today we See.

1.How to Open CSV file.
2.How to read CSV files rows data.
3.How to  Create CSV file using php.

Let's Do it...


First php had Two prebuild function for reading csv file and writing data in CSV files.

For Reading Data
1.fgetcsv(file,length,separator,enclosure);

file (Required)  current open file.
length (optional) length of file.
separator (Optional) character that specifies the field. ( , ) comma is default.
enclosure  (Optional) character that specifies the field enclosure character

For Writing Data
2. fputcsv(file,fields,separator,enclosure);
file (Required)  current open file.
fields (Required) simple array of data.
separator (Optional) character that specifies the field. ( , ) comma is default.
enclosure  (Optional) character that specifies the field enclosure character
 Now Let's Create a Demo Example in which i create a PHP file which open a csv and read the data the use its two column (id,name) and create a another csv file. Also i display the current csv file which i am opening.

Code : 

<?php

/*=========================================================================================
 || Function for Opening CSV File and Read its Data with title and Data contents         ||
==========================================================================================*/

function csv_to_php_array($file)
{
     //=========opening file======
    $files = fopen($file, "r");

    //=========decalring two array for title and data=============
    $array = array();
    $title = array();
    $i     = 0;


    //===============running loop until not reached the end of file============
    while (!feof($files)) {

      //=======if loop running first time then it will be its title so storing in title===========
        if ($i == 0) {

          //==================increase value 1 so it dont run again===================
            $i    = 1;
            $data = fgetcsv($files);
            array_push($title, $data);
            continue;
        }

        //========after title when loops runs it stores data in data array=======================
        $data = fgetcsv($files);
        array_push($array, $data);
        
    }

    //==================closing the file after work==================================
    fclose($files);

    //================returning the contents of file===============================
    return array(
        "title" => $title,
        "data" => $array
    );
}
/*=========================================================================================
 || End Of Function                                                                      ||
==========================================================================================*/

//=================calling the function of csv=========================
$filedata = (csv_to_php_array("sample.csv"));

//==============getting titles====================
$titles   = $filedata['title'][0];

//================getting datas=====================
$datas    = $filedata['data'];

//=================opening new file for writing our new data which is only id and name.============
$newfile  = fopen("newfile.csv", "w");

//=================putting the heading title of new csv file===================
fputcsv($newfile, array(
    "id",
    "name"
));

//========================creating table which disaplay our csv file in browser================
echo "<table style='border:1px solid green;border-collapse:collapse;' border='1'>";
echo "<tr>";

//===============running loop until all title not print==============
foreach ($titles as $title) {
    echo "<th>" . $title . "</th>";
}
echo "</tr>";

//=================running loop for each row of data====================
foreach ($datas as $data) {

  //=================store data in new csv which is id and name in array index 0 and 2 respectively.
    fputcsv($newfile, array(
        $data[0],
        $data[2]
    ));

    //=================printing each cell data of rows======================
    echo "<tr>";
    foreach ($data as $cell) {
        echo "<td>" . $cell . "</td>";
    }
    echo "</tr>";
    
}
//=================closing our new created file=============================
fclose($newfile);

Output Result : 

php csv
 

Download Dummy CSV File Link

 
0