Thursday, May 24, 2012

Installing and Working With Joomla

Installing and Working With Joomla

What is Joomla

Joomla is a content management system (CMS), which enables you to build Web sites and powerful online applications. Many aspects, including its ease-of-use and extensibility, have made Joomla the most popular Web site software available. Best of all, Joomla is an open source solution that is freely available to everyone.

Joomla is written in PHP, uses object-oriented programming (OOP) techniques  and software design patterns,stores data in a MySQL and includes features such as page caching, RSS feeds, printable versions of pages, news flashes, blogs, polls, search, and support for language internationalization.

http://www.joomla.org/about-joomla.html
http://en.wikipedia.org/wiki/Joomla 

What's a content management system (CMS)?

A content management system is software that keeps track of every piece of content on your Web site, much like your local public library keeps track of books and stores them. Content can be simple text, photos, music, video, documents, or just about anything you can think of. A major advantage of using a CMS is that it requires almost no technical skill or knowledge to manage. Since the CMS manages all your content, you don't have to.

What are some real world examples of what Joomla! can do?


Joomla is used all over the world to power Web sites of all shapes and sizes. For example:
  • Corporate Web sites or portals
  • Corporate intranets and extranets
  • Online magazines, newspapers, and publications
  • E-commerce and online reservations
  • Government applications
  • Small business Web sites
  • Non-profit and organizational Web sites
  • Community-based portals
  • School and church Web sites
  • Personal or family homepages

Download Joomla


Installing Joomla 

here we are installing Joomla in App Server ( link to how to Install Joomla )


all you need is a Web server with PHP and MySQL. Most commercial hosts provide these as part of their basic package of services. Then download a copy of Joomla.  The Joomla Installation Manual (Download PDF) takes you through the installation process step by step, The Joomla Quick Start Guide (Download PDF) should get you running quickly, and the accompanying video is a nice resource.


Minimum System Requirements

To successfully install and use Joomla! you must have a fully operational Web server (Apache is the
optimum), a database (MySQL is the optimum) and the server side scripting language PHP together with specific modules that are activated within PHP for MySQL, XML

To Be Continued...



Wednesday, May 2, 2012

Sending E-mail with PHP (basic mail() & Gmail with phpmailer )


Basic PHP mail()

Send a simple email:

<?php
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("someone@example.com","My subject",$msg);
?>
Definition and Usage
The mail() function allows you to send emails directly from a script.
Syntax
mail(to,subject,message,headers,parameters);

Basic PHP mail() Function code to send emails from a form

Below is the code for the basic email function. We can take the script and actually use a form on our website to set the variables in the script above to send an email.

<?php
//if "email" variable is filled out, send email
  if (isset($_REQUEST['email']))  {
  
  //Email information
  $admin_email = "someone@example.com";
  $email = $_REQUEST['email'];
  $subject = $_REQUEST['subject'];
  $comment = $_REQUEST['comment'];
  
  //send email
  mail($email, "$subject", $comment, "From:" . $email);
  
  //Email response
  echo "Thank you for contacting us!";
  }
  
  //if "email" variable is not filled out, display the form
  else  {
?>

 <form method="post">
  Email: <input name="email" type="text" /><br />
  Subject: <input name="subject" type="text" /><br />
  Message:<br />
  <textarea name="comment" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />
  </form>
  
<?php
  }
?>

So let’s now review what the form is actually doing. 
 1. The first part checks to make sure the email input field is filled out. If it is not, then it will display the HTML form on the page. If the email is in fact, set (after the visitor fills out the form), it is ready to send.  
2. When the submit button is pressed, after the form is filled out, the page reloads and reads that the email input is set, so it sends the email.
3. if you get following error,  Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25,
then make sure your php.ini configured correctly you have to configure these values on php.ini file
SMTP = smtp.yourdomain.com  
smtp_port = 25 
username = info@yourdomain.com
password = yourmailpassord
sendmail_from = info@yourdomain.com

Sending E-mail with PHP (Gmail SMTP and phpmailer)

 tutorial for sending PHP Mail using Gmail as your SMTP engine (with help of phpmailer functions.

before you start you must have valid gmail account and web server capable of PHP
  • PHP (you know, PHP: Hypertext Preprocessor). Its a lovely language for developing web pages. If you already knew that, then good. If not, you might want to read a good PHP Tutorial.
  • A local apache+PHP webserver running to test with. I am using  AppServ -http://www.appservnetwork.com/  while on Windows 7.
  • Can edit your PHP.ini configuration file. (If you don’t know what I’m talking about, get really familiar with the above two.
-----------------------------------------------------------------------------------------------------------

  1. If you haven’t done so already, get a PHP server running.
  2. Download PHP-Mailer .
  3. Go to your Apache  web server directory C:\AppServ\www\PHP_MAIL folder (in AppSever), and extract the PHP Mailer into it. I’ll call this folder Root from now on.(it contain - 3 PHP files- class.phpmailer.php , class.pop3.php , class.smtp.php , include   class.phpmailer.php in your test_gmail.php file ,source code is given below)
  4. Now go to Root\PHP-Mailer\examples\, and open up test_smtp_gmail_basic.php.(i have created my own test_gmail.php in side example, with the following content )
  5. Now do some minor editing. (Just change the Emails to your send and receiver, and type your password. )
---------------------------------------------------------------------------------------------
<?php

include("../class.phpmailer.php");

$mail             = new PHPMailer();
$body             = $mail->getFile('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP();
$mail->SMTPAuth   = true;  // enable SMTP authentication
$mail->SMTPKeepAlive = true;
$mail->SMTPSecure = "ssl";  // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port       = 465;// set the SMTP port for the GMAIL server
$mail->Username   = "umeshnarayanan1983@gmail.com";  // GMAIL username
$mail->Password   = "********";// your GMAIL password
$mail->AddReplyTo("umeshnarayanan1983@gmail.com","Umesh Narayanan");
$mail->From       = "umeshnarayanan1983@gmail.com";
$mail->FromName   = "Umesh Narayanan";


$mail->Subject    = "PHPMailer Test Subject via gmail";


$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap   = 50; // set word wrap

$mail->MsgHTML($body);

$mail->AddAddress("umeshnarayanan1@gmail.com", "Umeshnarayanan");

$mail->AddAttachment("images/activate.jpg");     // attachment

$mail->IsHTML(true); // send as HTML

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Email has been sent Sucessfuly!";
}

?>


6.Now, pressing save, you have almost done . Ok, the actual step is you need to edit your PHP.ini file settings. You can find that C:\Windows or  C:\AppServ\php5

or you can Go Start > All Programs > AppServ> Configuration server >PHP Edit the php.ini Configuration  as show below




open the PHP.ini file, then search for “openssl”. Go ahead and remove ‘;’ comment symbol from the start of the line.

extension=php_openssl.dll



  1. Restart your servers (optional -  restart your system )
  2. navigate to http://localhost/PHP_MAIL/examples/test_gmail.php in your browser. ( navigate to your file through browser )
  3. And then check your Receivers Inbox. 

Full source code can be downloaded from the following

Google doc link - https://docs.google.com/open?id=0B30amJFTQ4KbRlExVHNlQWM1QkU
(download and extract the whole folder in your root folder , and change email and password and you have done It!)


if you have any query pls contact me - umeshnarayanan1@gmail.com


Tuesday, May 1, 2012

PHP MySQL Basics

PHP MySQL Basics

(if you haven't installed PHP and Apache server see this Link - Installing and configuring PHP )

What is PHP?

    PHP stands for PHP: Hypertext Preprocessor
    PHP is a server-side scripting language, like ASP

What is a PHP File?

    PHP files can contain text, HTML tags and scripts
    PHP files are returned to the browser as plain HTML 

Variables in PHP

Variables are used for storing values, like text strings, numbers or arrays.
$txt="Hello World!";   (String Variables in PHP)
$x=16;

The Concatenation Operator .
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;

------------------------------------------------------------------------------------------------------------

PHP Array

 there are three kind of arrays:

    Numeric array - An array with a numeric index
    Associative array - An array where each ID key is associated with a value
    Multidimensional array - An array containing one or more arrays

Numeric array - $cars=array("Saab","Volvo","BMW","Toyota");  
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota"; 

associative array - $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);


$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34"; 

Multidimentional array

$families = array
 (
 "Griffin"=>array  (  "Peter", "Lois", "Megan"  ),
 "Quagmire"=>array (  "Glenn"  ),
 "Brown"=>array ( "Cleveland", "Loretta", "Junior" )
 ); 

Array
( [Griffin] => Array  (  [0] => Peter  [1] => Lois  [2] => Megan  )
  [Quagmire] => Array  (  [0] => Glenn  )
  [Brown] => Array ([0] => Cleveland[1] => Loretta [2] => Junior )

------------------------------------------------------------------------------------------------------------
Conditional Statements

if 

$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
if else

$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
else
  echo "Have a nice day!";
if...elseif....else

$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
elseif ($d=="Sun")
  echo "Have a nice Sunday!";
else
  echo "Have a nice day!";


------------------------------------------------------------------------------------------------------------

PHP Loops

while loop 

$i=1;
while($i<=5)
 {
 echo "The number is " . $i . "<br />";
  $i++;
   }
do while

$i=1;
do
 {
  $i++;
  echo "The number is " . $i . "<br />";
 }
while ($i<=5);
for loop

for ($i=1; $i<=5; $i++)
 {
 echo "The number is " . $i . "<br />";
  }
for each

$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "<br />";
 }
------------------------------------------------------------------------------------------------------------

PHP Function

function writeName()
{
echo "Kai Jim Refsnes";
}

echo "My name is ";
writeName();

PHP function with parameter

function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Kai Jim");

PHP function Returens 

function add($x,$y)
{
$total=$x+$y;
return $total;
}

echo "1 + 16 = " . add(1,16);
------------------------------------------------------------------------------------------------------------

PHP Form Handling

<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

in welcome.php
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.


The $_GET Variable


The predefined $_GET variable is used to collect values in a form with method="get"

Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old! 
When using method="get" in HTML forms, all variable names and values are displayed in the URL.

The $_POST Variable


The predefined $_POST variable is used to collect values from a form sent with method="post".
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old. 

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

PHP include() Function


The include() function takes all the content in a specified file and includes it in the current file.
<?php include("header.php"); ?>

------------------------------------------------------------------------------------------------------------

PHP File Handling



opening a file - $file=fopen("welcome.txt","r");
closing a file - $file = fopen("test.txt","r");

reading line by line - 
while(!feof($file))
  {
     echo fgets($file). "<br />";
  }
Reading a File Character by Character -  fgetc($file);

------------------------------------------------------------------------------------------------------------

What is a Cookie?


A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

setcookie(name, value, expire, path, domain); 

setcookie("user", "Alex Porter", time()+3600);

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.  echo $_COOKIE["user"];

PHP Sessions

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.


session_start();
$_SESSION['views']=1;
echo "Pageviews=". $_SESSION['views'];

Destroying a Session

unset($_SESSION['views']);

session_destroy();

What is an Exception


Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception

function checkNum($number)
  {
  if($number>1)
    {
    throw new Exception("Value must be 1 or below");
    }
  return true;
  }

//trigger exception
checkNum(2);

Try, throw and catch



Proper exception code should include:

    Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"
    Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"
    Catch - A "catch" block retrieves an exception and creates an object containing the exception information




------------------------------------------------------------------------------------------------------------


PHP MySQL Introduction

PHP MySQL Connect to a Database

Syntax - mysql_connect(servername,username,password); 


$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

closing connection 

mysql_close($con);


Create a Database

syntax - CREATE DATABASE database_name 

if (mysql_query("CREATE DATABASE my_db",$con))
 {
 echo "Database created";
 }
else
  {
  echo "Error creating database: " . mysql_error();
  }
Create a Table


// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";

// Execute query
mysql_query($sql,$con);



$sql = "CREATE TABLE Persons 
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";

insering data to table


mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");


Select Data From a Database Table


mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }

mysql_close($con);

Update Data In a Database

mysql_select_db("my_db", $con);

mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");

mysql_close($con);

Delete Data In a Database

mysql_select_db("my_db", $con);

mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");


SQL basics


SQL SELECT Statement

SELECT column_name(s) FROM table_name - eg:-  SELECT LastName,FirstName FROM Persons
SELECT * FROM table_name - eg:-  SELECT * FROM Persons

The SQL SELECT DISTINCT Statement


SELECT DISTINCT column_name(s) FROM table_name - eg:-  SELECT DISTINCT City FROM Persons



The WHERE Clause 

SELECT column_name(s) FROM table_name WHERE column_name operator value

eg:- SELECT * FROM Persons WHERE City='Sandnes'



SQL Joins


SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.

Different SQL JOINs

Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.

    JOIN: Return rows when there is at least one match in both tables
    LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
    RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
    FULL JOIN: Return rows when there is a match in one of the tables



OOPS in PHP
===============
 a class is just a template for these data members and methods. So, The idea is that you can create any number of "objects" based on a single "class." 

So if your class is called "User" you may create an object based on that class called $myUser or $myOtherUser 


Installing and working with FFMPEG with PHP

Installing and working with FFMPEG with PHP


ffmpeg is widely used for media format conversions or encoding. You may have seen on Youtube. Whatever media format you upload, it is converted into streaming flash files.(.flv). You can get more information about ffmpeg from http://ffmpeg.mplayerhq.hu/

ffmeg installation on Linux may be easy because primarily it is made for Linux not Windows. However some good experts have made it for windows also.(here we are trying to explain ,how we can use ffmpeg in windows also how we can make use of FFMPEG with PHP to make good web applications with video)

one thing is confirmed that you must have dedicated Windows server to install ffmpeg. There are a lot of changes in the OS and PHP settings.(in this tutorial we explaining installation of ffmpeg in windows 7, and basic operations ,and working with php and Apache sever)

install ffmpeg on Windows 7( or Windows XP/Vista)

Right now I will guide you to install ffmpeg on Windows 7, please follow these steps to install ffmpeg on your Windows 7 machine.
1- You must have PHP version 5.2.6 or above installed
2- Graphics library GD2 must also be installed. ( ignore if you are using AppServe )
3- Now download ffmpeg.exe file from this URL http://ffmpeg.arrozcru.org/builds/


4- extract and Put this files (ffmpeg.exe and ffplay.exe, it will be available in side the bin folder) on a base or short location like c:/ffmpeg/ffmpeg.exe this path will be used in DOS commands. So keep it easy and simple.

5- In fact this is the only file required for encoding files. However I will guide you to creating frame images and video conversions etc.
7-put one sample .flv in the same directory(test.flv video file and ,now we can convert it using ffmpeg) 
flv to mpg conversion using FFMPEG

 now we are trying to convert the test.flv file to new_test.mg
6-If you switch to DOS simply give a source and destination file like
(syntax - ffmpeg -i inputfile.flv outputfile.mpg

        c:/ffmpeg/ffmpeg.exe –i test.flv new_test.mpg


It will start converting file.


You must have know-how about the parameters that you have to set for file encoding. This will increase or decrease size and quality of your output file. Read the documentation on this URL. http://ffmpeg.mplayerhq.hu/ffmpeg-doc.html

Extracting frame from a video file

Hit following command against your video file and you'll get a splash image from the first frame of the video.(reference- http://flowplayer.org/tutorials/generating-thumbs.html)
Syntax-
ffmpeg -i [video_file] -f image2 -vframes 1 [output_image].jpg

example as given below

  • C:\ffmpeg>ffmpeg -ss 12 -i test.flv -f image2 -vframes 1 testimage.jpg




FFMPEG Working with PHP

7- Now come to another thing. It is called ffmpeg-php extension. This extension is made to manipulate encoded files. You can create frames and logo for your output file with PHP script.( Install PHP and   Apache Web Server  before you proceed 
8- You can download ffmpeg-php extension and API documentation from this URL
I used this link http://sergey89.ru/files/ffmpeg-php/ffmpeg-php-win32-all.zip and downloded ffmpeg-php-win32-all.zip which contain these files
9- Copy all fmpeg-php dll files into PHP "ext" (extensions) folder or System32, 

Where the extensions are located.














10-Also copy all these  in C:\WINDOWS\system32







10- Make this entry in php.ini (normally it will be in C:\Windows)
[PHP_ffmpeg]
extension=php_ffmpeg.dll 

(under - Dynamic Extensions )

also do the same modification in C:\AppServ\php5\php.ini (search for .ini file and modify it )




11- Now restart your PC. It’s good, because sometimes appserve restart doesn’t show effect.
(here I have used AppServe as the web server)
Check the ffmpeg installation http://localhost/phpinfo



If ffmpeg installed properly the the above detail will display.
Another php Script for checking ffmpeg
<?
extension_loaded('ffmpeg') or die("ffmpeg extension not loaded");


?>
If If you get “ffmpeg extension not loaded” then your web hosting provider does not have ffmpeg installed, if you get nothing, then you’re one the good track!
12- Take phpinfo() to check that extension is installed successfully. I hope it will be there. J
13- As ffmpeg.exe will be executed from DOS within PHP. There is a function in PHP called exec() for that. However it will not work straight away. Restart your pc in safe mode with Administrator account. Because mostly Windows 7 won’t let set security permissions in normal mode. Here is a very good example of setting permissions. http://www.somacon.com/p255.php
14- Ok, everything is done, How should we test that it is working?
here is the code http://www.sajithmr.com/ffmpeg-sample-code/ (this example explained in the bottom)
If sample code is printing all the information then your ffmpeg installation is successful and you can carry on with development of your application development.
When working on Home or PC, you might face some issues like slow encoding, It is because ffmpeg encoding requires more resources. You must experiment with small video/audio clips. However on Web servers you can try large files also.
If you are looking for ffmpeg hosting with everything ready then you can try Cirtex Hosting


Working with ffmpeg and PHP (tutorial will be uploaded soon)

Now here i am explaining how can we work with FFMPEG with PHP (in web Server)

Displaying Duration ,window size of a video file using ffmpeg with PHP  

1. First install one web sever (i have Installed AppServe) which support PHP and configure it for ffmpeg (as explained above)
2.the place the ffmpeg.exe file in web server (we have used - C:\AppServ\www)




 3.copy one video file to the same location
4.create one php file with the following code (file name test_ffmpeg.php)





<?php

$file= "test.flv";


ob_start();
passthru("ffmpeg -i ".$file." 2>&1");
$duration = ob_get_contents();
$Size = ob_get_contents();
$Other = ob_get_contents();
ob_end_clean();


$search='/Duration: (.*?)[.]/';
$duration=preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE);
$duration = $matches[1][0];

list($hours, $mins, $secs) = split('[:]', $duration);
echo "Video Name - ".$file;
echo "</br>Duration - Hours: ".$hours." Minutes: ".$mins." Seconds: ".$secs;

$search='/Video: (.*?), (.*?), (.*?),/';
$Size=preg_match($search, $Size, $matches, PREG_OFFSET_CAPTURE, 0);
$Size = $matches[3][0];
echo "</br>Window size - ".$Size."</br>";

?>


out put




Convert video files with ffmpeg and PHP (eg: flv to avi) and Convert Every n seconds to JPEG
video is converted to .avi format and every 10 second'th frame is captured to image(.jpg)





<?
  /*** convert video to flash ***/
  $input_file = "test.flv";
  $output_file = "out.avi";
  $out_image_folder = "image";
  $out_put_dimension = "320x240";
 
 
 exec("ffmpeg -i ".$input_file." -ar 22050 -ab 32 -f flv -s  ".$out_put_dimension." ".$output_file."");
 exec("ffmpeg -i ".$input_file." -an -r .1 -y -s ".$out_put_dimension." ".$out_image_folder."/video%d.jpg");
?>




 Following tutorial will be uploaded soon

1.Thumbnail creation for  first frame of video
2.Video uploading and convering video
before trying uploading file make some modification php.in file (for upload limit, execution time tc)

in (C:\Windows, and C:\AppServ\php5)

make the following changes
----------------------------------------------------------------------------------------

post_max_size = 10000M ; Maximum size of POST data that PHP will accept.max_execution_time = 600 ; Maximum execution time of each script, in secondsmax_input_time = 600 ; Maximum amount of time each script may spend parsing request datamemory_limit = 1024M ; Maximum amount of memory a script may consume (1024MB)file_uploads = On ; Whether to allow HTTP file uploads.upload_max_filesize = 10000M; Maximum allowed size for uploaded files.extension=php_ffmpeg.dll

----------------------------------------------------------------