force download file using php



By default most of the file types (eg: txt, jpg, png, gif, html, pdf, etc.) displayed in browser instead of download. But we can force browser to download these files instead of showing them.This tutorial goes over how to force file download in php.

<?php
   //file path to download
    $file_name=$_GET['file'];
    $outputfilename = "<DOWNLOAD_FILE_NAME>";
    header('Content-Description: File Transfer');
    //set content type
    header('Content-Type: application/octet-stream');
    //file name to save it may be different from original filename
    header("Content-Disposition:  attachment; filename=\"" . basename($outputfilename) . "\";" );
    //sends file size header to browser
    header('Content-Length: ' . filesize($file_name));
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: public');
    header('Pragma: public');
    ob_clean();
    //outputs file content to download stream
    readfile($file_name);
    exit;
?>

Add Google Plus Share Button to your site



Simple Tutorial to Create Google Plus Share Popup Window.

function shareongplus()
{
 var url2='https://plus.google.com/share?url='+encodeURIComponent("<URL_TO_SHARE>")+'&title='+encodeURIComponent('<TITLE_OF_SHARE>');

    newwindow=window.open(url2,'<TITLE_OF_POPUP>','height=450,width=650');
    if (window.focus) {newwindow.focus()}

}

Note :- You can use encodeURIComponent('Text To Encode') javascript function to encode text into url format.

Import csv file in mysql using php


This tutorial will go over how to import CSV ( comma separated value ) file data into Mysql Database using Php . 

CSV file is should be like below



<!-- form to submit csv file -->
<form enctype="multipart/form-data" method="post" role="form">
    <div class="form-group">
        <label for="exampleInputFile">File Upload</label>
        <input type="file" name="file" id="file" size="150">
        <p class="help-block">Only CSV File Import.</p>
    </div>
    <button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>


//php code to process csv file and store data into mysql database
<?php
if(isset($_POST["Import"]))
{
    //First we need to make a connection with the database
    $host='localhost'; // Host Name.
    $db_user= ''; //DB User Name
    $db_password= '';  //DB Password
    $db= ''; // Database Name.

    //Create connection with databse
    $conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
    mysql_select_db($db) or die (mysql_error());
    echo $filename=$_FILES["file"]["tmp_name"];

    if($_FILES["file"]["size"] > 0)
    {
        $file = fopen($filename, "r");
$count = 0;
        while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
        {
$count++;
                        // ignore first row for column names
if($count>1)
{
                                //insert into database
$sql = "INSERT into demo1(id,name) values ('$emapData[0]','$emapData[1]')";
mysql_query($sql);
}
        }
        fclose($file);
        echo 'CSV File has been successfully Imported';
    }
    else
        echo 'Invalid File:Please Upload CSV File';
}
?>

Export MS SQL SERVER data in MS Excel using php



This tutorial will go over how to download MS SQL Server data into Excel file. This is Very useful for generating Excel Reports of Php and MS SQL Server Applications. 

<?php
$myServer = "host_name";
$myUser = "user_name";
$myPass = "password";
$myDB =  "database_name";

//create an instance of the  ADO connection object
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");

//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database

//declare the SQL statement that will query the database
$query = "SELECT col1, col2, col3, .... , coln FROM table_name";

//execute the SQL statement and return records
$rs = $conn->execute($query);

$num_columns = $rs->Fields->Count();
//echo "col:".$num_columns . "<br>";

for ($i=0; $i < $num_columns; $i++) {
    $fld[$i] = $rs->Fields($i);
}

$contents="<table border='1'>";

while (!$rs->EOF)  //carry on looping through while there are records
{
    $contents.="<tr>";
    for ($i=0; $i < $num_columns; $i++) {
        $contents.="<td>" . $fld[$i]->value . "</td>";
    }
    $contents.="</tr>";
    $rs->MoveNext(); //move on to the next record
}

$contents.="</table>";

$file="File_name.xls";
$test="<table border=1><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=File_name".date('Y-m-d').".xls");
echo $contents;

//close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();

$rs = null;
$conn = null;
?>

Display MS Sql Server Data using PHP



This tutorial will go over how to Display MS SQL Server datausing PHP.

<?php
$myServer = "host_name";
$myUser = "user_name";
$myPass = "password";
$myDB =  "database_name";

//create an instance of the  ADO connection object
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");

//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database

//declare the SQL statement that will query the database
$query = "SELECT col1, col2, col3, .... , coln FROM table_name";

//execute the SQL statement and return records
$rs = $conn->execute($query);

$num_columns = $rs->Fields->Count();
//echo "col:".$num_columns . "<br>";

for ($i=0; $i < $num_columns; $i++)
{
    $fld[$i] = $rs->Fields($i);
}

echo "<table>";

while (!$rs->EOF)  //carry on looping through while there are records
{
    echo "<tr>";
    for ($i=0; $i < $num_columns; $i++) {
        echo "<td>" . $fld[$i]->value . "</td>";
    }
    echo "</tr>";
    $rs->MoveNext(); //move on to the next record
}

echo "</table>";

//close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();

$rs = null;
$conn = null;
?>

Add a Pinterest button to site





Another Simple Tutorial to Add a Pinterest button to site.

Pins are like little bookmarks. Whenever you find something on the web that you want to keep, add it to Pinterest. If your site have multiple images and you want give facility to users to bookmark this images for later use. you can use this Pinterest plugin.

Steps to Add Pinterest Button to site.

1) Add following pinterest script to your site.

<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>

2) Create pin it button using simple Anchor Tag.

<a href="//www.pinterest.com/pin/create/button/?url=<SITE_URL>&media=<IMAGE_TO_PIN_IT>&description=<DESCRIPTION_TO_SHARE>" data-pin-do="buttonPin" data-pin-config="above"  target="_blank"><img src="images/btn_pinit.png" class="shares" ></a>

Its done. :)

for more information visit:- http://business.pinterest.com/widget-builder/#do_pin_it_button

Note :- You can use encodeURIComponent('Text To Encode') javascript function to encode text into url format.

Send Facebook Notification via Graph API using PHP



function fbnotification($userid,$message)
{
$app_id = "<APPLICATION_ID>";
$app_secret = "<APPLICATION_SECRET_KEY>";
$app_access_token = $app_id . '|' . $app_secret;

$facebook = new Facebook(array(
'appId'  => $app_id,
'secret' => $app_secret,
'cookie' => true,
));

$response = $facebook->api( '/'.$userid.'/notifications', 'POST', array(
'template' => $message,
'access_token' => $app_access_token
) );  
}

fbnotification($userid,$message)

Add LinkedIn Share Button




Simple Tutorial to Create LinkedIn Share Popup Window.

Sharing Any article on linkedin via your site or a web page is very simple. just follow below simple steps. linkedpopup() functions create a popup window for sharing content.

function linkedpopup()
{
var url1='http://www.linkedin.com/shareArticle?mini=true&url=<LINK_TO_SHARE>&title=<TITLE_TO_SHARE>&summary=<DESCRIPTION_TO_SHARE>&source=<YOUR_WEBSITE_NAME>';
      newwindow=window.open(url1,'<TITLE_OF_POPUP>','height=450,width=650');
      if (window.focus) {newwindow.focus()}

}

Parameter List:--

Parameter

Character Limit Description
mini

4 Must always be true
url

1024 The permanent link to the article. Must be URL encoded
title

200 The title of the article. Must be URL encoded
source

200 The source of the article. Must be URL encoded. Example: Wired Magazine
summary

256 A brief summary of the article. Must be URL encoded. Longer titles will be truncated gracefully with ellipses.


for more information visit:- http://developer.linkedin.com/documents/share-linkedin

Note :- You can use encodeURIComponent('Text To Encode') javascript function to encode text into url format.

Twitter tweet button



Simple Tutorial to Create Twitter Share Popup Window.

tweetpopup() function helps your visitor to create popup for tweeting content and connect on twitter.

function tweetpopup() 
{
      var url2='https://twitter.com/intent/tweet?hashtags=<HASHTAG>&text=<TEXT_TO_TWEET>&url=<URL_TO_TWEET>&via=<HANDLE_FOR_TWEET>';

      newwindow=window.open(url2,<TITLE_OF_POPUP>','height=450,width=650');
      if (window.focus) {newwindow.focus()}

}

for more information visit:- https://about.twitter.com/resources/buttons#tweet

Note :- You can use encodeURIComponent('Text To Encode') javascript function to encode text into url format.

Add facebook share button




Simple Tutorial to Create Facebook Share Popup Window.

function facebookshare()
{
var url2='http://www.facebook.com/sharer.php?s=100&p[title]='+encodeURIComponent(' TITLE_OF_SHARE') + '&p[summary]=' + encodeURIComponent(' DESCRIPTION_TO_SHARE') + '&p[url]=' + encodeURIComponent(' URL_TO_SHARE ') + '&p[images][0]=' + encodeURIComponent(' IMAGE_TO_SHARE');
newwindow=window.open(url2," POPUP_WINDOW_HEADING",'height=480,width=680');
if (window.focus) {newwindow.focus()}

}

Note :- You can use encodeURIComponent('Text To Encode') javascript function to encode text into url format.

Export Mysql Table in XML using php



This tutorial will go over how to download Mysql Table into XML file. This is Very useful for generating XML Data files when you have to work with javascript to get data.

<?php
$conn = mysql_connect('localhost', 'user_name','password');
mysql_select_db('database_name');
$xml = '';

//query the db
$query = mysql_query("SELECT col1, col2, col3, col4 FROM TableName");
    $xml .='<main>';
//loop through query results
while ( $row = mysql_fetch_array ( $query ) )
{
 //Add to xml
$xml .= '<group>';
 $xml .= '<col1><![CDATA[' . $row['col1'] . ']]></col1>'; 
$xml .= '<col2><![CDATA[' . $row['col2'] . ']]></col2>'; 
 $xml .= '<col3><![CDATA[' . $row['col3'] . ']]></col3>'; 
$xml .= '<col4 ><![CDATA[' . $row['col4 '] . ']]></col4 >'; 
$xml .= '</group>';
}

    $xml .='</main>'; 

//Write to xml and override
$handle = fopen('data.xml', 'w+');
fwrite($handle, $xml);
?>

Note:- Please Assign 777 permission to folder to write file into it.

Simulating Pencil Tool in AS3



var drawing:Boolean = false;
this.graphics.lineStyle(1, 0x000000);
this.graphics.moveTo(mouseX, mouseY);
this.addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown, false, 0,true);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);

function onDown(evt:MouseEvent):void
{
     drawing = true;
}
function onUp(evt:MouseEvent):void
{
     drawing = false;
}

function onLoop(evt:Event):void
{
     if (drawing)
     {
          this.graphics.lineTo(mouseX, mouseY);
     }
     else
     {
          this.graphics.moveTo(mouseX, mouseY);
     }
}

Get long lived access_token for facebook pages


Facebook API’s allows a developer to update a cover photo of a page through code. I am creating a Live Cover photo change App for One of the client. this apps mechanism is to change cover photo depending on the no of likes of page.

for such type of apps. you need a long lived access_token so you can run a script from server itself.

Following it the step-by-step process.

1)   Make Sure you are the admin of FB Page.
2)   Create a FB App with same user account.
4)   On the Top Right , Select the FB App you created from the "Application" drop down list.
5)   Click "Get Access Token" Button.
    Select Permission Window will open.
6)   Click on "Extended Permission" Tab and Check "manage_pages" permission
7)   type "me/accounts" in FQL Query Box.
    It show you complete listing of page details like category, name, access_token, permissions..
    This Access token is short-lived-token. you have to convert this short live token to long lived token.
8)   https://graph.facebook.com/oauth/access_token?client_id={fb_app id}&client_secret={fb_app_secret}&grant_type=fb_exchange_token&fb_exchange_token={short-lived-access_token}
9)   Grab the new long-lived access token.
10) Make A Graph API call to see your account using the new long-lived access token
      https://graph.facebook.com/me/accounts?access_token={your_long_lived_access_token}
11) Grab the access_token for the page.
12) You can use following link to https://developers.facebook.com/tools/debug/  to get Access Token Info. 
It will provide info like Application ID, Profile ID, User ID, Issued, Expires, Scopes etc.

This step-by-step process will give you Long Lived Access Tokens.


Multiple image format change using photoshop


This tutorial will go over how to Change format of multiple images at  once using Photoshop. This is also known as Bulk image format change in Photoshop(bridge).

If you want to convert image from one format to another, Photoshop and Photoshop Tools allow you to do this in just few minutes. For doing this process you requires Photoshop File Browser (or Adobe Bridge in CS3 or higher).

1) Open Photoshop.

2) click on "FILE" menu.


 3) Select "Browse in Bridge" option.
    A new window will open.
    In a "content" window select images you want to rename.

4) click on "Tool" Menu   


5) Hover "Photoshop" Menu.
    select "Image Processor" option.
    A new window will open
 
6) Select various options as per requirement like
    Destination folder,
    Image type,
    Copyright info 

7) Click on "Run" Button.
   
    Its done :)

Rename multiple images ( Batch Rename Files in Photoshop )



This tutorial will go over how to Rename multiple images at  once using Photoshop. This is also known as Batch Rename Files in Photoshop.

If you want to rename a series of files -- such as several pictures from a digital camera. Photoshop and Photoshop Tools allow you to do this in just few minutes. For doing this process you requires Photoshop File Browser (or Adobe Bridge in CS3 or higher).

1) Open Photoshop.

2) click on "FILE" menu.


 3) Select "Browse in Bridge" option.
    A new window will open.
    In a "content" window select images you want to rename.

4) click on "Tool" Menu


5) select "Batch Rename" option
    A new window will open

6) Select various options like
    Destination folder,
    New File Names
        You can use Text, Sequence number, date and time for names of files
    You can see preview in preview box.


7) Click on "Rename" Button.
   
    Its done :)

Export Mysql data in MS Excel using php



This tutorial will go over how to download Mysql data into Excel file. This is Very useful for generating Excel Reports of Php Applications, and database. 


<?php
      //database credentials
      $username = "user_name";
      $password = "password";
      $host = "host_name";
      $dbname = "database_name";

      //Connect to database      $connector = mysql_connect($host,$username,$password)
          or die("Unable to connect");
        //echo "Connections are made successfully::";


     //Select database
      $selected = mysql_select_db($dbname, $connector)
        or die("Unable to connect");

      //execute the SQL query and return records
      $result = mysql_query("SELECT col1, col2, col3 FROM tablename");

    $contents="<table border='1'><tr><th>COL1</th><th>COL2</th><th>COL3</th></tr>";
    while($row = mysql_fetch_array($result))
    {
        $contents.="<tr><td>".$row['col1']."</td>";
        $contents.="<td>".$row['col2']."</td>";
        $contents.="<td>".$row['col3']."</td></tr>";
       
    }
   
    $contents.="</table>";

//header to make force download the file
$file="Report.xls";

header("Content-type: application/vnd.ms-excel");
//.date() functions add current date to file name
header("Content-Disposition: attachment; filename=Report".date('Y-m-d').".xls");
echo $contents;

mysql_close($connector);
?>

Note:- When you run this script Force download of Excel file starts.

Disable right click on web page using javascript



This tutorial will go over how to DisableRight Mouse Click using javascript

<!-- turn off right click -->

<script language=javascript>
var message="";
function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {if
(document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers)
{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
document.oncontextmenu=new Function("return false")
</script>

Note:- This only stops people from right clicking on your page and there is no real way to stop people from viewing your html, if someone is determined to see your code they will.

Write Data to file in .Net ( VB and C# )



This tutorial will go over how to write data to a text file in VB.Net and C#.Net

.Net uses StreamWriter Class To write data to file. StreamWriter is designed for character output in a particular encoding, whereas classes derived from Stream are designed for byte input and output.

VB .Net

Dim objWriter As New System.IO.StreamWriter("d:\abc.txt", True)  
objWriter.WriteLine("Some Text here")
objWriter.Close()

C# .Net

using (System.IO.StreamWriter objWriter = new System.IO.StreamWriter(@"abc.txt", true))
{
       objWriter.WriteLine("Some Text here");
}
objWriter.Close(); 
 

Read Data from text file in .Net ( VB and C#)



This tutorial will go over how to read data from a text file in VB.Net and C#.Net

.Net uses StreamReader Class To read data. StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.

VB .Net

Dim line As String = ""
Dim objReader As New System.IO.StreamReader("d:\abc.txt", True) 
Do line = objReader.ReadLine()
Console.WriteLine(line)
Loop Until line Is Nothing
objReader.Close()

C# .Net
using (StreamReader objReader = new StreamReader("abc.txt")) 
{
    string line;
    // Read and display lines from the file
    while ((line = objReader.ReadLine()) != null) 
    {
         Console.WriteLine(line);
    }
}

Load random images from folder in Php



This tutorial will go over how to pull any image from a specified folder, store path in an array and display random image on a page.

Step 1:-
//Specify path to search images from directory
$dir = 'images/';

Step 2:-
//scan directory content using scandir() function
$filesscandir($dir);

Step 3:-
//take random value from array
$random_index = array_rand($files);

Step 4:- 
finally display image
echo "<img src=" .$dir . $files[$random_index] . ">";


But when you display images some times it displays some hidden files. you can check contents of array by using print_r() command.
==> print_r($files);
it will show output as follows.
==> Array ( [0] => . [1] => .. [2] => HHRCK.png [3] => dsgsdg.jpg 

I don't have enough rep to explain about this dots. This tradition comes from the Unix world. I guess it is because it allows you to quickly see the permissions for the current and parent directories on each call of ls.

. refers to the current directory .. refers to the parent directory.


You will have to filter them out manually.

As of PHP 5.3 there is the FilesystemIterator which extends the DirectoryIterator and skips dot-files by default. 
here i used another array with the value [ '.' , '..']
and then find the difference between two arrays

So final code is as follows

<?php
$dir = 'images/';
$files =array_diff(scandir($dir), array('..', '.'));
$random_index = array_rand($files);
echo "<img src=" .$dir . $files[$random_index] . ">";
?>


whenever you refresh page random images will display.