Tech blog

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

Followers

Powered by Blogger.

Wednesday 19 November 2014

How To send sms using API in PHP??

No comments :
Today we guys mostly use sms services available on internet like way2sms,160by2.but have we ever thought to take them in our webapplications.

In PHP,We can do this with simple code of thirdparty api..
Here i have created simple code which sends sms to given mobile number using clickatell API.




Here is code:

<?php
    $user = "xxxxxx";
    $password = "xxxxxx";
    $api_id = "xxxxxx";
    $baseurl ="http://api.clickatell.com";

    $text = urlencode("This is an example message");
    $to = "+919408046690";

    // auth call
    $url = "$baseurl/http/auth?user=$user&password=$password&api_id=$api_id";

    // do auth call
    $ret = file($url);

    // explode our response. return string is on first line of the data returned
    $sess = explode(":",$ret[0]);
    if ($sess[0] == "OK") {

        $sess_id = trim($sess[1]); // remove any whitespace
        $url = "$baseurl/http/sendmsg?session_id=$sess_id&to=$to&text=$text";

        // do sendmsg call
        $ret = file($url);
        $send = explode(":",$ret[0]);

        if ($send[0] == "ID") {
            echo "successnmessage ID: ". $send[1];
        } else {
            echo "send message failed";
        }
    } else {
        echo "Authentication failure: ". $ret[0];
    }
?>

In this code,user,password and api id are needed for code,which is available on www.clickatell.com/
site.

Happy Coding guys!!! 

Simple Login With PHP

No comments :

Hello Friends,
Today I am going to show you simple login with php session and html form.First we will create html form as follow:



<form method="post" action="index.php" name="form1" id="form1">
      <h2>Login</h2>
      <p> 
        <input type="text" placeholder="Username" name="username" id="username">
      </p>
      <p> 
        <input type="password" placeholder="Password" name="pass" id="pass">
      </p>
      <input type="submit" name="submit1" id="submit1" value="Login" class="button"/>
    </form>

Here on above form there is two fields username and password.User will enter username and password into form and submit it to page.

After submitting form to same page,here see how following code will accept data.

if(isset($_POST['submit1']))
{
$username=addslashes($_POST['username']);
$pass=addslashes($_POST['pass']);
$sel="select * from admin where username='$username' AND password='$pass'";
$res=mysql_query($sel) or die(mysql_error());
$total=mysql_num_rows($res);
if($total > 0)
{
while($rows=mysql_fetch_array($res))
{
session_start();
$_SESSION['ID']=$rows['id'];
   $_SESSION['USERNAME']=$rows['username'];
header("location:dashboard.php");
}

}
}

Please see structure of table admin as follow:








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.


Saturday 30 August 2014

Iphone Push Notification using PHP

No comments :
In previous article we have learned android gcm notification using php but now we will see iphone notification using php.




Here I have wonderful code for it as below:



<?php
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', 
    $err, 
    $errstr, 
    60, 
    STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, 
    $ctx);

//if (!$fp)
//exit("Failed to connect amarnew: $err $errstr" . PHP_EOL);

//echo 'Connected to APNS' . PHP_EOL;

// Create the payload body
$body['aps'] = array(
    'badge' => +1,
    'alert' => $message,
    'sound' => 'default'
);

$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));

if (!$result)
    echo 'Message not delivered' . PHP_EOL;
else
    echo 'Message successfully delivered amar'.$message. PHP_EOL;

// Close the connection to the server
fclose($fp);
?>

Notification to android apps using PHP

No comments :
WE have created website but also created application for our website.here i have created small code for sending notification thru CURL to android apps using php.First try to create your google application on google developers and make android notification ON.

After completing above steps,you will get an application access key for your code.just paste that in your code.and get registration id from an android developer so that u will able to send notification to that device.




Code:

<?php

// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array( $_GET['id'] );

// prep the bundle
$msg = array
(
    'message' => 'first push notification message',
'title' => 'test title',
'subtitle' => 'subtitle',
'tickerText' => 'ticker',
'vibrate' => 1,
'sound' => 1
);

$message_array = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);

$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $message_array ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>

You will get notification as output of this code.This is known as Android GCM notification from PHP.



Sunday 17 August 2014

Getting Video Thumbnails in PHP using ffmpeg

No comments :
Developers always create awesome codes by knowing language deeply.He can create ideas to make new innovative system.In PHP,same thing happens.As you all know extensions of php.ffmpeg is one of popular extension of php to take images from video.

Now,you can create images of your video.The video can be mp4,wmv,mkv etc..But here some lines are different.I have created code for windows system and with ffmpeg.exe

Download ffmpeg.exe for windows and paste following code in your editor.




Code:
<?php

$ffmpeg = 'ffmpeg.exe';

//video dir
$video = 'song.mp4';

//where to save the image
$image = 'image.jpg';

//interval
$interval = 5;

//image size
$size = '320x240';

//ffmpeg command
$cmd = "$ffmpeg -i $video -deinterlace -an -ss $interval -f mjpeg -t 1 -r 1 -y -s $size $image 2>&1";       
$return = `$cmd`;
?>

if you want to define directory you can define it  with "/".



Creating Facebook Apps

No comments :
Now a days,Facebook has socialized a lot.People want to advertise everything on social sites.Facebook Application is main interface to interact with Facebook functionality.To login,to post data on Facebook wall we need to create Facebook application.

Here are few steps which will help you to create Facebook Application:

Step-1:-

Go to https://developers.facebook.com/
Step-2:-

Go to Apps tab at top and click "create an app" button.
Finally you will get popup following page:

Step-3:-

Fill all above data and click on create app.Fill security text and go ahead.


Finally you are ready with Facebook application.

Thursday 14 August 2014

Creating Twitter Apps

No comments :
Today I will tell you about how to create twitter application in your account

Step-1:
go to twitter application site:

http://dev.twitter.com/



Step-2:

Log-in to site with your username and password

Step-3:

Go to Below page and click on create new app button

When you click on this button the following page will open.Enter Application name,Application Description,website url and call back url.Check "Yes,I agree" box.

Now, click on create new app button below.

Congratulations!!Your application has been created.


Tuesday 5 August 2014

How To Read Text Files using PHP

No comments :
I have posted tutorials for creating and posting of data.But here is good code and easy way in php to read text files which is stored in folder.In last post, I have posted code for making text file and directory.We will read data of same file.As assumed in code,files are same but contents in text file may be different.



Check out code for the same as follow:

<?php
$newdir='RuchiS';
echo  readfile($newdir.'/' ."newfile.txt");
?>


The above codee show one line which is reason for execution or say function names readfile.
 readfile is function in php which helps to read text file. 


Create Directory and text File using PHP

No comments :

We have been regularly in use of making directory using windows. and also text file.




Here is code which will help u to make folder and text files using php script.

<?php
$newdir='RuchiS';
$thisdir = getcwd();
echo "The Current Directory is ".$thisdir;
if(mkdir($thisdir . '/' . $newdir, 0777))
{
    $myfile = fopen($newdir.'/' ."newfile.txt", "w") or die("Unable to open file!");
    $txt = "Ruchi\n";
    fwrite($myfile, $txt);
    $txt = "Sanghvi\n";
    fwrite($myfile, $txt);
    fclose($myfile);
echo 'Directory has been created successfully...';
}
else
{
echo 'Failed to create directory...';
}
?>


The first line of code will be name of directory which you want to create in short,name of directory.Second line is for pointing current directory which u will create.

Here if condition will check wheather directory is made or not.and 777 will give write permission to folder.
under if condition text file will be created with fopen function.which will be in write mode.

In that text we can write text like Ruchi and Sanghvi. and fwrite function will write text into it.
 

Monday 4 August 2014

Password Strength Meter using PHP and Jquery

No comments :
you can create password strength meter using php and jquery with following code:




JQuery:

$(document).ready(function() {
    var password1       = $('#password1'); //id of first password field
    var password2       = $('#password2'); //id of second password field
    var passwordsInfo   = $('#pass-info'); //id of indicator element
 
    Passwordmeter(password1,password2,passwordsInfo); //call password check function
  
});

function Passwordmeter(password1, password2, passwordsInfo)
{
    //Must contain 5 characters or more
    var WeakPass = /(?=.{8,}).*/;
    //Must contain lower case letters and at least one digit.
    var MediumPass = /^(?=\S*?[a-z])(?=\S*?[0-9])\S{8,}$/;
    //Must contain at least one upper case letter, one lower case letter and one digit.
    var StrongPass = /^(?=\S*?[A-Z])(?=\S*?[a-z])(?=\S*?[0-9])\S{8,}$/;
    //Must contain at least one upper case letter, one lower case letter and one digit.
    var VryStrongPass = /^(?=\S*?[A-Z])(?=\S*?[a-z])(?=\S*?[0-9])(?=\S*?[^\w\*])\S{8,}$/;
  
    $(password1).keypress(function(e) {
       
        if(VryStrongPass.test(password1.val()))
        {
            passwordsInfo.removeClass().addClass('vrystrongpass').html("Very Strong! (Awesome, please don't forget your pass now!)");
        } 
        else if(StrongPass.test(password1.val()))
        {
            passwordsInfo.removeClass().addClass('strongpass').html("Strong! (Enter special chars to make even stronger");
        } 
        else if(MediumPass.test(password1.val()))
        {
            passwordsInfo.removeClass().addClass('goodpass').html("Good! (Enter uppercase letter to make strong)");
        }
        else if(WeakPass.test(password1.val()))
        {
            passwordsInfo.removeClass().addClass('stillweakpass').html("Still Weak! (Enter digits to make good password)");
        }
        else
        {
            passwordsInfo.removeClass().addClass('weakpass').html("Very Weak! (Must be 8 or more chars)");
        }
    });
  
    $(password2).keypress(function(e) {
      
        if(password1.val() !== password2.val())
        {
            passwordsInfo.removeClass().addClass('weakpass').html("Passwords do not match!"); 
        }else{
            passwordsInfo.removeClass().addClass('goodpass').html("Passwords match!");
        }
          
    });
}




HTML 

<form action="" method="post" id="passwordmeter">
<div><input type="password" id="password1" /></div>
<div><input type="password" id="password2" /></div>
<div id="pass-info"></div>

Login with Google using PHP

No comments :
You can create your website with google login.You can now socialize your website on google. here is code for it:

Please get google api client from google site

Please make sure you create application for google application on google developers.


Here is code:

<?php
@session_start();
require_once 'src/apiClient.php';
require_once 'src/contrib/apiOauth2Service.php';

$client = new apiClient();
$client->setApplicationName("Google Account Login");
$oauth2 = new apiOauth2Service($client);

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  unset($_SESSION['google_data']); //Google session data unset
  $client->revokeToken();
}

if ($client->getAccessToken()) {
  $user = $oauth2->userinfo->get();
   if (!empty($user ))
  {
      echo "<strong>Your Google details follows.</strong><br/>";
        echo "Name : ".$user['name']."<br/>";
        echo "Google ID : ".$user['id']."<br/>";
        echo "Google Email : ".$user['email']."<br/><br/><br/><br/>";
  }
 


  $_SESSION['google_data']=$user;
   

  $_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}
?>

<?php if(isset($personMarkup)): ?>
<?php print $personMarkup ?>
<?php endif ?>
<?php
  if(isset($authUrl)) {
    print "<a class='login' href='$authUrl'>Google Account Login</a>";
  } else {
   print "<a class='logout' href='?logout'>Logout</a>";
  }
?>
<a href="http://friendstaxi.com/" style="font-size:24px; color:#C00; font-family:Arial, Helvetica, sans-serif;  margin:100px;float:left">Goto HOME</a>