Tampilkan postingan dengan label PHP. Tampilkan semua postingan
Tampilkan postingan dengan label PHP. Tampilkan semua postingan

Sabtu, 24 Oktober 2015

PHP Do While Tutorial with Working Example

On reaching the control to do statement, the program proceeds to evaluated the body of the loop first. At the end of the loop, the test-condition in the while statement is evaluated,so it is categorized as post tested loop.
The basic format of do while() statement is:
do{
      body of the loop
     }while(test-conditon);

Lets have a working example
a program to enter a number and check entered number is Armstrong or Not (153 is a Armstrong number).               
<?php  
if(isset($_POST['b1'])) {
                                $number=$_POST['t1'];
                                $cp=$number;
                                $digit=0;
                                $cube_plus=0;
                                do{
                                   $digit=$number%10;
                                   $cube_plus=$cube_plus+($digit*$digit*$digit);
                                   $number=(int)($number/10);
                                  }while($number>0);
                                 if($cube_plus==$cp)
                                 $msg="Armstrong";
                                 else
                                 $msg="Not Armstrong";
                }
                ?>
                <form action="" method="post">
                Enter Number<input type="text" name="t1"><br>
                Status<input type="text" value="<?php echo $msg;?>"><br>
                <input type="submit" name="b1" value="Check">
                </form>
 

Rabu, 16 September 2015

PHP Switch Statement Tutorial with Practical Example

What is PHP Switch Statement?

According to php.net The Switch Statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

PHP Switch  Statement Syntex

switch (n)
{
case label1:
  code to be executed if n=label1;
  break;
case label2:
  code to be executed if n=label2;
  break;
default:
  code to be executed if n is different from both label1 and label2;
}

PHP Switch  Statement Practical Example

Objective : Creating a program to enter two number and select task from list then display the result.

Coding
<?php
$n1=$_POST['t1'];
$n2=$_POST['t2'];
$ch=$_POST['choice'];
if(isset($_POST['done']))
{
switch($ch)
{
case 'add':
$res=$n1+$n2;
break;
case 'sub':
$res=$n1-$n2;
break;
case 'mul':
$res=$n1*$n2;
break;
case 'div':
$res=$n1/$n2;
break;
}
}
?>
<html><head><title>Form</title></head>
<body>
<form action="" method="post">
Enter First Number<input type="text" name="t1"><br>
Enter Second Number<input type="text" name="t2"><br>
Result<input type="text" value="<?php echo $res;?>"><br>
Select Task:&nbsp;&nbsp;&nbsp;
<input type="radio" name="choice" value="add">ADD
<input type="radio" name="choice" value="sub">SUB
<input type="radio" name="choice" value="mul">MUL
<input type="radio" name="choice" value="div">DIV<br>
<input type="submit" name="done" value="DONE">
</form>
</body>
</html>

Kamis, 10 September 2015

Learn PHP Preg_match with working Example

preg_match is a wonder ful function of PHP( 4,5,6) to Perform a regular expression match. Its little bit difficult to learn but extremely useful when you properly understand it. Extensively use to extract string in SEO process, in validation of E-mail ID and so its impossible for me to describe its utilization in PHP Development.

Structure :
preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
Simplified Version
preg_match(pattern, Subject ,array)
Pattern-  The pattern to search for, as a string. 
like 
xyz@openplus.in 
+91-8564123356
<title>openplus.in</title>

Subject = Variable that contains that value
like
$sanjay='xyz@openplus.in';
Array-  to store extracted value.
For more details visit PHP.net

A Simple Example:
This example extract title from title tags, heavily used is SEO industry.
<?php
$sanjay='<title>Please share this page to twitter, Google Plus and Twitter</title>';
preg_match('/<title>(.*)<\/title>/i',$sanjay,$mt);
echo $mt['1'];
?>

Note : use / to start a pattern and /i to end. Use (.*) to find the desired value.
Above Code will give a out put
Please share this page to twitter, Google Plus and Twitter

Sabtu, 15 Agustus 2015

Lets enjoy power of PHP Function

function(): 

A set of specific program and source code which complete a specific task is function.
Function separates the complexity of a large program and provides a modular approach. There are two type of function user define function and library function. Now focus on user defines function and try to understand.
PHP Function

Syntex of PHP function :

function functionName()
{
code to be executed;

Complete Example of PHP Function


<!DOCTYPE html>
<html lang="en">
<head>
<title>IP Address</title>
<meta charset="utf-8" />
</head>
<body>
<?php
function crdt(){
$dt=date("m/D/Y");
return $dt;
}
echo crdt();
?>
</body>
</html>

 

Selasa, 11 Agustus 2015

PHP File Uploading easy to learn tutorial with complete script

PHP is world's no. 1 server side scripting language, it comes with plenty of features and one of the most famous one is file uploading which is extensively used world wide.
Self Explanatory PHP File Uploading Example

Self Explanatory PHP File UploadingExample

First Create a directory called  gallary/ .
Save this file as gallery.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>File Uploading</title>
<meta charset="utf-8" />
</head><body>
 <?php
$path="gallery/";
$path=$path.$_FILES['file_upload']['name'];
if(isset($_POST['upload']))
{
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo "The file ".basename($_FILES['file_upload']['name'])." has been uploaded";
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
?>
<form action="gallery.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</body></html>

Jumat, 17 Juli 2015

HTML FORM tutorial with CSS based Example

FORMS are used to pass data to a server and contain input elements like
text, check box, radio, button, submit, reset, password.HTML FORM tutorial with CSS based Example
A form is incomplete with out input box . Data sent to server through forms using input elements  and executed on the server.





Lets have a example of a form

<form action="name.php" method="post">
<input type="text" name="name" />
<input type="submit" name="submit" value="Go"/>
</form>
Output
Explanation:
action- pointed to page where programming codes will be there.
type- we have to define type of input box whether it is text, password,submit or so on..
method- we have to define which method we are using GET or POST , remember POST is secure compare to GET.

Lets have Complete example -
In this example used PHP as Programming language, CSS for making the form look good and html5.

Complete Script -

 <!DOCTYPE html>
<html lang="en">
<head>
<title>Form Tutorial</title>
<meta charset="utf-8" />
<style type="text/css">
.input{
background:#fff;
border: 1px solid #999;
box-shadow:inset 0 0 2px #000000; 
color: #222; 
}
.input:hover{
background:#f6f6f6;
border: 1px solid #999;
color: #222;
}
</style>
</head><body>
<?php
if(isset($_POST['submit')){
$name=$_POST['name'];
echo "Hello ". $name. " its Working naa";
}
?>
<form action="" method="post">
<input type="text" name="name"  class="input"/>
<input type="submit" name="submit" value="Go" class="input"/>
</form>
</body>
</html>

If you have any question then please comment .

Jumat, 10 Juli 2015

How To find out Visitors IP ADDRESS using PHP

 IP ADDRESS using PHPI f you a PHP programmer then you will find it very easy to track your visitors IP Address, if someone spaming on your site you can also block him. PHP is alway easy and powerful than other scripting language lets check the whole code .



Codding:

<!DOCTYPE html>
<html lang="en">
<head>
<title>IP Address</title>
<meta charset="utf-8" />
</head>
<body>
<?php
$ip=$_SERVER['REMOTE_ADDR'];
echo "<br/>Your IP Address is ".$ip;
// suppose IP 127.0.0.1 for localhost and it redirects to prevent spam
if($ip=='127.0.0.1')
{
echo "You are blocked for Spaming";
header("refresh:5; http://www.openplus.in");
}
?>
</body>
</html>



Kamis, 09 Juli 2015

PHP Constant tutorial with practicle example

PHP Constant tutorialConstant: Constant refers to fixed value that does not change the value during the execution of program. Constant are defined using PHP’s define () function which accept two arguments. The $ prefixed is not required for constant.



A simple Example :

<?php
//define constant
define('PI',3.14);
$r=5;
//use constant
$area=PI*$r*$r;
echo "Area of circle=".$area;
?>

Result - 78.5

Practical example:
This script is used for data base connection.

<?php
   define('MYSQL_HOST','localhost');
   define('MYSQL_USER','root');
   define('MYSQL_PASS','');
?>

Rabu, 08 Juli 2015

Install XAMPP on 32/64 bit Linux Distro

Today Linux has become number one choice in Open Source world whether it is Desktop experience, programming, server or Web Development Linux has no match. Its Secure , fast and comes in many flavor.
In this tutorial we will focus how to install Xampp on linux 64 bit OS. Earlier day the Linux version of XAMPP called as LAMPP. But it comes as XAMPP with more improvements.
For Installing and running XAMPP on 64 bit linux distro install wine  through package manager , it will install 32 bit packages so you can run  32 bit application also. Please note that  XAMPP is till now a 32 bit application.
After installing Wine Download XAMPP  latest version from
After downloding Xampp copy it to home folder, and rename it to xampp.tar.gz

Note : Some distro allows root login such as PCLinuxOS, OpenSUSE so if your distro allows root login then logged as root. Some distro doesnot allow root login like Ubuntu, Kubuntu ... don't worry login as default.

Go to a Linux shell and login as the system administrator root
su tar xvfz xampp.tar.gz -C /opt
or if fail try
sudo tar xvfz xampp.tar.gz -C /opt
it will ask password , use your root password and hit enter.
To start XAMPP simply call this command:
sudo /opt/lampp/lampp start
or
su  /opt/lampp/lampp start
You should now see something like this on your screen:
Starting XAMPP 1.7.7...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.
Ready. Apache and MySQL are running.
Just type in the following URL at your favourite web browser:
http://localhost
Now you should see the start page of XAMPP containing some links to check the status of the installed software and some small programming examples.
xampp 64 bit linux
Xampp on Kubuntu 12.04 64 bit
Some Usedful commands to remeber while playing with xampp.
startStarts XAMPP.
stopStops XAMPP.
restartStops and starts XAMPP.

This tutorial tested on Ubuntu, Linux Mint ,OpenSUSE and Fedora

Minggu, 05 Juli 2015

My way learn MySQLI and PHP by examples

MySQL is world most used database and when its works PHP then they have no match. Learning MySQL is very is one can found thousand of tutorial on net but these are now old as MySQLI(or MySQL Advanced) next version are now on demand as implementation is easy, secure and little bit faster. In this tutorial I am going to share Uses of MySQli in your next project.

MySQLI and PHP by examples

For Connecting to database, create a PHP file name dbsettings.php with following code :

$sanjay=new mysqli('localhost','root','','mysqlifirst');
if($sanjay->connect_errno){
     echo $sanjay->connect_error;
 }

I think above line is quite easy to understand, mysqlifirst is the name of your database.

Data query :
Suppose you have a table name billings which has coloumn trans_id, amount and so on.
Create a another file name dataquery.php with following code:

require('dbsettings.php');
$query="select * from billings where trans_id='2013' ";
$sendq=$sanjay->query($query);
$rows=$sendq->fetch_assoc();
echo "Transaction ID. 2013 amount is Rs.".$rows['amount'];

This is I think a very simple example of using MySqli. If you have any doubt then comment below , I will try to explain it later.
+Sanjay Prasad 

Jumat, 20 Maret 2015

upload user profile image and save to data base -PHP MYSQLI

   If you are working on customized CMS or Social networking website then user profile image may be or may not be a head ache I have developed my own where we can upload and rename the image username.jpg/png/gif with size restriction to 200KB.

PHP MYSQLI Upload Image Tutorial

First design a table where database name is Sanjay.
Create a table userImage  fileds
user - username will be stored
url - url of img stored
lastUpload- when the upload was done.
create a folder upload/   where  all images will stored.
<?php
$user=$_SESSION['user'];
$db=new mysqli('localhost','root','','Sanjay');
if($db->connect_errno){
echo $db->connect_error;}
$pull="select * from userImage  where user='$user'";

$allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
$extension = @end(explode(".", $_FILES["file"]["name"]));
if(isset($_POST['pupload'])){
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/JPG")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo '<div class="plus">';
    echo "Uploaded Successully";
    echo '</div>';
     
    echo"<br/><b><u>Image Details</u></b><br/>";
   
    echo "Name: " . $_FILES["file"]["name"] . "<br/>";
    echo "Type: " . $_FILES["file"]["type"] . "<br/>";
    echo "Size: " . ceil(($_FILES["file"]["size"] / 1024)) . " KB";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      unlink("upload/" . $_FILES["file"]["name"]);
      }
    else
      {
          $pic=$_FILES["file"]["name"];
            $conv=explode(".",$pic);
            $ext=$conv['1'];

      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/". $user.".".$ext);
      echo "Stored in as: " . "upload/" . $user.".".$ext;
      $url=$user.".".$ext;
   
      $query="update userImage set url='$url', lastUpload=now() where user='$user'";
      if($upl=$db->query($query)){
          echo "<br/>Saved to Database successfully";
              }
      }
    }
  }
else
  }
  echo "File Size Limit Crossed 200 KB Use Picture Size less than 200 KB";

  }
}
?>
<form action="" method="post" enctype="multipart/form-data">   
  <?php
    $res=$db->query($pull);
    $pics=$res->fetch_assoc();
    echo '<div class="imgLow">';
    echo "<img src='upload/$pics[url]' alt='profile picture' width='80' height='64'   class='doubleborder'/></div>";
   
    ?>
   
    <input type="file" name="file" />
    <input type="submit" name="pupload" class="button" value="Upload"/>
  
</form>

Hope You will understand this simple script.

if you want complete script with foundation framework, profile mangement, password change, user profile picture management then download my open -source project Adminplus at githhub
download Zip file extract and save it to htdocs folder , if using Linux set permission . open phpmyadmin and create a database sanjay_plus now import  sql . Now we can login using username sanjay password openplus.in.
 

Minggu, 01 Februari 2015

PHP Image upload , Saving link to Database complete tutorial

This blog is dedicated to all our visitors who asked me to publish a working tutorial on  image upload  using PHP and Saving its path to Mysql Table.
PHP Image upload , Saving  link to Database

How to do that :
First we will create a file called install.php , it will create a database called
myimages and a table  named imgtables and also create a folder called gallery where we are going to store  images.

Create a file name install.php
------------------------------------------------------
<?php
/*
file name : Install.php
purpose : creating a database name myimages
and table imgtables
Create by : Sanjay Prasad
sonzoy@gmail.com
http://www.openplus.in
*/

$db=mysqli_connect("localhost","root","");

if($db->connect_errno){
    echo "Error <br/>".$sp->error;
}

$query="create database if not exists myimages";

if($db->query($query)){
     echo "Created database myimages ..<br/>";   
    
     $sp=mysqli_connect("localhost","root","","myimages");
         if($sp->connect_errno){
                echo "Error <br/>".$sp->error;
            }
           
            $tbquery="create table if not exists imgtables(
            id int unsigned auto_increment primary key,
            imgurl varchar(255),
            date varchar(100)


            )engine='InnoDB'";
           
            if($sp->query($tbquery)){
                echo "Table imgtables created Successfully  ..<br/> ";   
            }else{
                echo "Error <br/>".$sp->error;       
            }
           
            //creating directory gallery
           
            if(mkdir("gallery",0777)){
                echo "Folder gallery create successfully";
            }else{
                echo "Error Creating Directory";
            }

    }
else{
    echo "Error <br/>".$sp->error;   
    }   

?>

Now We have to create a file name gallery.php, which will upload images to folder gallery and saved their name like flower.jpg on table filed imgurl.

gallery.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>File Uploading</title>
<meta charset="utf-8" />
</head><body>
<?php
$sp=mysqli_connect("localhost","root","","myimages");
         if($sp->connect_errno){
                echo "Error <br/>".$sp->error;
}

$path="gallery/";

if(isset($_POST['upload']))
{

$path=$path.$_FILES['file_upload']['name'];
   
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
    $query="insert into imgtables (imgurl,date) values('$img',now())";
    if($sp->query($query)){
     echo "<br/>Inserted to DB also";   
    }else{
        echo "Error <br/>".$sp->error;       
    }


}
else
{
echo "There is an error,please retry or ckeck path";
}
}
?>
<form action="gallery.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</body></html>

Selasa, 13 Januari 2015

Installing Xampp 1.8 on 32 bit and 64 bit linux and solve phpmyadmin Access error

What is Xammp ?
XAMMP is now become number one choice for web developer for its ease of use and stability. XAMPP is an easy way  to install Apache distribution containing MySQL, PHP and Perl.
In this tutorial I am going to share how to install Xampp 1.8 on 32 bit and 64 bit linux and solve phpmyadmin Access error. In previous tutorial I already shared xampp 1.7 installation guide .

First Download Xampp 1.8 from apachefriends and copy it to home directory and rename it to xampp1.8.tar.gz. If you run 64 bit OS install Wine or ia32-libs otherwise you will not able to enjoy xampp as it is 32 bit application.

Installation guide of xampp 1.8 :

Run terminal and use following command
sudo tar xvfz xampp1.8.tar.gz -C /opt
if fails use
su tar xvfz xampp1.8.tar.gz -C /opt
Now xampp install successfully in /opt/ folder. we can start xampp by simply by command
sudo /opt/lampp/lampp start
Xampp 1.8 installation
 launch the url in firefox localhost but when launching phpmyadmin you will get following error.
xampp 1.8 phpmyadmin error
Don't worry We will soon solve this error . But first we have to make /opt/htdocs/ writable so we can easy create folders and files there by following command
 sudo chmod 777 -R /opt/lampp/htdocs
Now  we have to solve phpmyadmin Access error by simply editing httd-xampp.conf file.
Open terminal and run command
sudo kate
or sudo following by your favorite editor like gedit to open as root.
and open file httd-xampp.conf located at /opt/lampp/etc/extra/httd-xampp.conf
Look for following lines
<Directory "/opt/lampp/phpmyadmin">
    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all
</Directory>
and replace with following
<Directory "/opt/lampp/phpmyadmin">
    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all 
   Require all granted
</Directory>

After this , you will not able to open phpmyadmin same error will displayed on browser.
We have to restart Xampp in order to work. use following command
sudo /opt/lampp/lampp stop 
to stop xampp and
sudo /opt/lampp/lampp start
to start xampp 1.8

or you can use simgle command to restart
sudo /opt/lampp/lampp restart

Open localhost/phpmyadmin , after changing default language to english
it will look like
PHPMYADMIN  xampp 1.8

This tutorial is tested on Linux Mint KDE 14 Nadia.
@https://plus.google.com/111215709458999120537