Tech blog

PHP tutorials,a way to getting some thing new in web

Followers

Powered by Blogger.

Wednesday 24 September 2014

How to send email using php?

No comments :
$subject="Hi How are you??";
$body="Hi What's Up??Come to see me sometimes.";
//echo $body;

$from="ruchivsanghvi@gmail.com";
$reply_to="ruchivsanghvi@gmail.com";
$headers .= "Content-type: text/plain\r\n";
$headers .= "From:Ruchi Sanghvi <$from> \r\n";
$headers .= "Reply-To: Admin <$reply_to>\n";
$headers .= "X-Mailer: PHP". phpversion() ."\n";
   
$res=mail("kinjalashukla@gmail.com",$subject,$body,$headers);



PHP has fabulous function for sending simple text and html mails.

The function is mail() function.

This function takes 4 parameters as follow:


to ->Email of receiver;
subject->subject of email.
body->message of email.
header->it takes extra parameter combination like from email,type of data,php version,reply to attributes etc.

this is very simple script.I hope u will enjoy it.

Sunday 14 September 2014

Display Audio File On HTML5 page

No comments :
Today I am going to cover small but very useful topic of HTML5. In previous I explained you how to upload audio file in database using php.



Today we will see how to show audio file in our webpage with html <audio> tag.

<audio> tag is useful to stream audio mp3,wave,ogg files using html5. <audio> tag works fine with IE,Chrome,Safari,Mozilla Firefox.This tag supports 3 files i.e. mp3,wave,ogg.



Put following code with audio file path in html5 page.

<audio controls="controls">
<source src="ring.mp3" type="audio/mpeg">
</audio>

In above code,"controls" will show controls of audio."autoplay" will play audio at loading of page.

Thursday 11 September 2014

Upload audio using php and mysql

1 comment :
Today, I am going to show you one script for audio file uploads like mp3,wmv,mp4 etc..This is as easy as we upload image using php.We guys always go to site of songs to download our favourite singer songs.But how do these site allow user to upload audio is tricky.



But let us not waste time on discussing what they do.I am going to give you easy code for mp3 file upload.
the code is as below:

First we will create simple HTML code with form as below:

<form name="audio_form" id="audio_form" action="" method="post" enctype="multipart/form-data">
<fieldset>
<label>Audio File:</label>
<input name="audio_file" id="audio_file" type="file"/>
<input type="submit" name="Submit" id="Submit" value="Submit"/>
</fieldset>
</form>

Create one blank folder names "Audios" in your project to save audio files.

After Submitting form page will be redirect to same page.We can check file type using below:

<?php
if(isset($_POST['Submit']))
{
$file_name = $_FILES['audio_file']['name'];

if($_FILES['audio_file']['type']=='audio/mpeg' || $_FILES['audio_file']['type']=='audio/mpeg3' || $_FILES['audio_file']['type']=='audio/x-mpeg3' || $_FILES['audio_file']['type']=='audio/mp3' || $_FILES['audio_file']['type']=='audio/x-wav' || $_FILES['audio_file']['type']=='audio/wav')

$new_file_name=$_FILES['audio_file']['name'];

 // Where the file is going to be placed
$target_path = "Audios/".$new_file_name;

//target path where u want to store file.

//following function will move uploaded file to audios folder. 
if(move_uploaded_file($_FILES['audio_file']['tmp_name'], $target_path)) {

//insert query if u want to insert file
}
}
}

?>

In the Above code, $target_path is where you want to store file.
After successful execution of above code.you will be able to see your file uploaded in Audios file

Friday 5 September 2014

Excel Spreadsheet creation in PHP

No comments :
Spreadsheets are used everywhere and they are most useful to manage and organize data.They are quite popular.

PHP also supports creation of excel spreadsheets using PHP.I am wondered that PHP creates it without any class.


It only needs 4-5 lines of code using php.Mostly \t and \n tags are used.You can generate excel spreadsheets easilyusing PHP. You need to use below code to create excel file.




<?php
    header( "Content-Type: application/vnd.ms-excel" );
    header( "Content-disposition: attachment; filename=spreadsheet.xls" );
   
    // print your data here. note the following:
    // - cells/columns are separated by tabs ("\t")
    // - rows are separated by newlines ("\n")
   
    // for example:
    echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
    echo 'Ruchi' . "\t" . 'Sanghvi' . "\t" . '666-6666' . "\n";
?>


To define content type following line is used:

header( "Content-Type: application/vnd.ms-excel" );

To define its name and download it following line is used:

header( "Content-disposition: attachment; filename=spreadsheet.xls" );

FirstName,LastName and Phone define Header of excel sheet.

Last line defines data to be displayed in excel sheet.

\t and \n is to define space and new line in code accordingly.

PHP Invoice Creation for Billing

No comments :
Today I will cover one great documentary topic which is know as pdf coding.or I will call it as pdf coding.

PHP has tremendous advantages.It has all aspects of features to get things done.Generating invoices is needed in every php developers life because they work with ecommerece and at the end ecommerece projects demand for invoice generation and billing system.so every php developer must know how to create invoice pdf using php.

PHP has pdf creation class which is very helpful for pdf class.There are fpdf,tcpdf classes which has different functions which is used to create PDF functions.Here I have created small code for billing invoice.I have used FPDF
Class and its functions.

You can get FPDF class from below link:

http://www.fpdf.org/

Go to Download Link and Download class which is as ZIP.
copy and paste fpdf.php class and fonts in your project folder and give path in your code like below:

require('u/fpdf.php');

Here u is folder and fpdf.php is class file.

create another folder named invoice where all invoices which you generate will be stored.

Take a look below code:

Here I have create one simple form which takes billing information:

<form action="" method="post" enctype="multipart/form-data">
<div id="body_l">
<div id="name"><input name="company" placeholder="Company Name" type="text" /></div>
<div id="name"><input name="address" placeholder="Company Address" type="text" /></div>
<div id="name"><input name="email" placeholder="Email" type="text" /></div>
<div id="name"><input name="telephone" placeholder="telephone number" type="text" /></div>
<div id="name"><input name="item" placeholder="Item" type="text" /></div>
</div>
<div id="body_r">
<div id="name"><input name="price" placeholder="price" type="text" /></div>
<div id="name"><input name="dis" placeholder="discount" type="text" /></div>
<div id="name"><input name="vat" placeholder="VAT" type="text" /></div>
</div>
<div id="up" align="center"><input name="submit" style="margin-top:60px;" value="Submit" type="submit" /><br /><br />
</div>
</form>

Here we can some CSS in code:


<style>

a{
color:#999999;
text-decoration:none;
}
a:hover{
color:#999999;
text-decoration:underline;
}
#content{
width:800px;
height:600px;
background-color:#FEFEFE;
border: 10px solid rgb(255, 255, 255);
border: 10px solid rgba(255, 255, 255, .5);
-webkit-background-clip: padding-box;
background-clip: padding-box;
border-radius: 10px;
opacity:0.90;
filter:alpha(opacity=90);
margin:auto;
}
#footer{
width:800px;
height:30px;
padding-top:15px;
color:#666666;
margin:auto;
}
#title{
width:770px;
margin:15px;
color:#999999;
font-size:18px;
font-family:Verdana, Arial, Helvetica, sans-serif;
}
#body{
width:770px;
height:360px;
margin:15px;
color:#999999;
font-size:16px;
font-family:Verdana, Arial, Helvetica, sans-serif;
}
#body_l{
width:385px;
height:360px;
float:left;
}
#body_r{
width:385px;
height:360px;
float:right;
}
#name{
width:width:385px;
height:40px;
margin-top:15px;
}
input{
margin-top:10px;
width:345px;
height:32px;
-moz-border-radius: 5px;
border-radius: 5px;
border:1px solid #ccc;

color:#999;
margin-left:15px;
padding:5px;
}
#up{
width:770px;
height:40px;
margin:auto;
margin-top:10px;
}
</style>




After submitting submit button we can get all data via form post and generate fine invoice:

<?php 
if(isset($_POST["submit"]))
{
$company = $_POST["company"];
$address = $_POST["address"];
$email = $_POST["email"];
$telephone = $_POST["telephone"];
$number = $_POST["number"];
$item = $_POST["item"];
$price = $_POST["price"];
$dis = $_POST["dis"];
$vat = $_POST["vat"];
$final_amt=$price - ($dis/100) + ($vat/100);
$pay = 'Payment information';
$price = str_replace(",",".",$price);
$vat = str_replace(",",".",$vat);
$p = explode(" ",$price);
$v = explode(" ",$vat);
$re = $p[0] + $v[0];
function r($r)
{
$r = str_replace("$","",$r);
$r = str_replace(" ","",$r);
$r = $r." $";
return $r;
}
$price = r($price);
$vat = r($vat);
require('u/fpdf.php');

class PDF extends FPDF
{
function Header()
{
if(!empty($_FILES["file"]))
  {
$uploaddir = "logo/";
$nm = $_FILES["file"]["name"];
$random = rand(1,99);
move_uploaded_file($_FILES["file"]["tmp_name"], $uploaddir.$random.$nm);
$this->Image($uploaddir.$random.$nm,10,10,20);
unlink($uploaddir.$random.$nm);
}
$this->SetFont('Arial','B',12);
$this->Ln(1);
}
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial','I',8);
$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
function ChapterTitle($num, $label)
{
$this->SetFont('Arial','',12);
$this->SetFillColor(200,220,255);
$this->Cell(0,6,"$num $label",0,1,'L',true);
$this->Ln(0);
}
function ChapterTitle2($num, $label)
{
$this->SetFont('Arial','',12);
$this->SetFillColor(249,249,249);
$this->Cell(0,6,"$num $label",0,1,'L',true);
$this->Ln(0);
}
}

$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
$pdf->SetTextColor(32);
$pdf->Cell(0,5,$company,0,1,'R');
$pdf->Cell(0,5,$address,0,1,'R');
$pdf->Cell(0,5,$email,0,1,'R');
$pdf->Cell(0,5,'Tel: '.$telephone,0,1,'R');
$pdf->Cell(0,30,'',0,1,'R');
$pdf->SetFillColor(200,220,255);
$pdf->ChapterTitle('Invoice Number ',$number);
$pdf->ChapterTitle('Invoice Date ',date('d-m-Y'));
$pdf->Cell(0,20,'',0,1,'R');
$pdf->SetFillColor(224,235,255);
$pdf->SetDrawColor(192,192,192);
$pdf->Cell(170,7,'Item',1,0,'L');
$pdf->Cell(20,7,'Price',1,1,'C');
$pdf->Cell(170,7,$item,1,0,'L',0);
$pdf->Cell(20,7,$price,1,1,'C',0);
$pdf->Cell(0,0,'',0,1,'R');
$pdf->Cell(170,7,'Discount',1,0,'R',0);
$pdf->Cell(20,7,$dis,1,1,'C',0);
$pdf->Cell(170,7,'VAT',1,0,'R',0);
$pdf->Cell(20,7,$vat,1,1,'C',0);
$pdf->Cell(170,7,'Total',1,0,'R',0);
$pdf->Cell(20,7,$final_amt." $",1,0,'C',0);
$filename=rand(0,1999).".pdf";
$pdf->Output("invoice/".$filename,'F');
}
?>

Above code I have used rand() function for pdf name so that every pdf class is recognized with unique name.then we will store it in folder invoice which we have created at starting of tutorial.




Wednesday 3 September 2014

Show Your Address on Google Maps

No comments :
Hello Friends,

Today I am going to introduce you simple google map integration on html page.it is just 2steps  process.

Step:-1:
go to https://www.google.co.in/maps/preview site.put your address on left top corner and search it.

Step-2:-

Click on shown icon on google map and get embed code from embed source.copy that code in your html page.The code contain <iframe> </iframe> tags.




Tuesday 2 September 2014

How to upload video on Youtube using PHP

No comments :
Today, I am going to show you code for very advance API.We use youtube in daily basis but this time php will be used to post video on youtube.I have got new code for it and here I thought to  share with you all.

The code is so simple.you should download zend package from zend site.and got developer key from google.also your gmail username and password will work in this code.








Here is code:

<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
 try 
 {
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient =  Zend_Gdata_ClientLogin::getHttpClient(
 $username = 'XXXX', //your gmail password and username
 $password = 'XXXXX',
 $service = 'youtube',
 $client = null,
 $source = 'Yoh Money',            
 $loginToken = null,
 $loginCaptcha = null,
 $authenticationURL);
 } 
 catch (Zend_Gdata_App_Exception $e) 
 {
 $arry['data']['flag'] = false;
 $arry['data']['msg'] = 'Username or Password Invalid.';
 print_r(json_encode($arry));
 die();
 }

$developerKey='XXXXXX';//make an application and get its developer key
$applicationId = 'not require';
$clientId = 'not require';
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$fileName = "Offo.mp4";   
$fileType = "video/mp4"; 

$newEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource($fileName);
$filesource->setContentType('video/mp4');
$filesource->setSlug($fileName); 
$newEntry->setMediaSource($filesource);
$newEntry->setVideoTitle("Offo"); 
$newEntry->setVideoDescription("Offo is awesome song of 2states"); 
$newEntry->setVideoCategory("Comedy"); 
$newEntry->setVideoTags("2 States,Offo");  
try {
$newEntry = $yt->insertEntry($newEntry, 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads', 'Zend_Gdata_YouTube_VideoEntry');
$state = $newEntry->getVideoState();
if ($state) 
{
$videourl = $newEntry->getVideoWatchPageUrl();
$arry['data']['flag'] = true;
$arry['data']['url'] = $videourl;
$arry['data']['msg'] = "Video Uploaded Successfully.";


else 
{
$arry['data']['flag'] = false;
$arry['data']['msg'] = "Not able to retrieve the video status information yet. " ."Please try again later.\n";
}


catch (Zend_Gdata_App_Exception $e) {
 $arry['data']['flag'] = false;
 $arry['data']['msg'] = $e->getMessage();
}
echo "<pre>";
print_r($arry);

?>

Deleting All files from Folder using PHP

No comments :
Next topic I would take is very easy one.but i thought it bcoz i have done very tinycode which is yet not seen by me.






Here I am giving you code to delete files from  folder at once.

<?php
$dir='test';
foreach (glob($dir."/*") as $image)
{

  unlink($image);

}


?>


Here $dir is variable where you can give directory which you want to make empty.

Try this out!! you will feel very happy!!

Getting Geolocation from geotagged Photos of Camera using PHP

No comments :

Hi guys,Today I am going to teach you about one function of PHP which will help you to get geolocation

(i mean latitude and longitude of location) then you can set them in google maps and show location of image where image is taken.

We routinely took images in camera but if our phone camera's geo location is ON then it will automatically recorded where this image is taken.

So for testing took one image which have geo location information stored and get it's information.store your image in one folder and give then folder name in $dir variable.

 

 

Please check out below code:


<?php

$dir = "./img";


function readGPSinfoEXIF($image_full_name)
{
   $exif=exif_read_data($image_full_name, 0, true);
     if(!$exif || $exif['GPS']['GPSLatitude'] == '') {
       return false;
    } else {
    $lat_ref = $exif['GPS']['GPSLatitudeRef'];
    $lat = $exif['GPS']['GPSLatitude'];
    list($num, $dec) = explode('/', $lat[0]);
    $lat_s = $num / $dec;
    list($num, $dec) = explode('/', $lat[1]);
    $lat_m = $num / $dec;
    list($num, $dec) = explode('/', $lat[2]);
    $lat_v = $num / $dec;

    $lon_ref = $exif['GPS']['GPSLongitudeRef'];
    $lon = $exif['GPS']['GPSLongitude'];
    list($num, $dec) = explode('/', $lon[0]);
    $lon_s = $num / $dec;
    list($num, $dec) = explode('/', $lon[1]);
    $lon_m = $num / $dec;
    list($num, $dec) = explode('/', $lon[2]);
    $lon_v = $num / $dec;

    $gps_int = array($lat_s + $lat_m / 60.0 + $lat_v / 3600.0, $lon_s
            + $lon_m / 60.0 + $lon_v / 3600.0);
    return $gps_int;
    }
}


         function dirImages($dir)
         {
             $d = dir($dir);
             while (false!== ($file = $d->read()))
             {
             $extension = substr($file, strrpos($file, '.'));
             if($extension == ".jpg" || $extension == ".jpeg" || $extension == ".gif"                                        
               |$extension == ".png")
     $images[$file] = $file;
    }
    $d->close();        
    return $images;
}


$array = dirImages('./img');
$counter = 0;

foreach ($array as $key => $image)
{
    echo "<br />";
    $counter++;
    echo $counter;
    echo "<br />";
    $image_full_name = $dir."/".$key;
    echo $image_full_name;
    $results = readGPSinfoEXIF($image_full_name);
    $latitude = $results[0];
    echo $latitude;
            echo "<br />";
    $longitude = $results[1];
    echo $longitude;
    echo "<br />";   
}
?>
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
var myCenter=new google.maps.LatLng(<?=$latitude;?>,<?=$longitude;?>);
var marker;
function initialize()
{
var mapProp = {
  center:myCenter,
  zoom:5,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
marker=new google.maps.Marker({
  position:myCenter,
  animation:google.maps.Animation.BOUNCE
  });
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>

Try above code and you will get one fantastic result.