> January 2013 ~ Online tutorial

delete directory in php

delete directory in php



<?php
// delete a new directory path
rmdir("C:\wamp\www\uploaddata1");
if(rmdir)
{
    echo "directory removed";
}
else
{
    echo "directory can't removed";
}
?>


output:
before





After the code

create directory in php

create directory in php
Now we are going to create directory that is folder in php.In the PHP we are having mkdir()to create directory.

Program

<?php
// create a new directory path
mkdir("C:\wamp\www\uploaddata1");
if(mkdir)
{
    echo "directory created";
}
else
{
    echo "directory can't created";
}
?>


Output


In this program we are create directory called uploaddata will created .

read directory php

read directory php
<?php
// assign folder into variable
$currdir='/var/www';
//open the directory for reading $dir=opendir($currdir);
//read a filename
while($file = readdir($dir)
{
// Display all file name in the specified folder
echo "$file<br/>";
}
closedir($dir);
}?>
Output:

index.html
est.html
first.php

Explanation
Now opendir simply opens a directory,replace folder with the name of the folder and if needed, the path too.The while loop then goes through file by file in the directory .the if statement exclude s showing two non-files.you can exclude any files you wish too.After a simpl e echo displaying the filename




login form using php

Login form using php
Now we are going to create login form by using PHP validation technique.now we are create database for the login called Login
then we can use the database .
Then we are simple HTML form for get user name and password from the system
Program


<html>
<body>


<form name='form1' method="post" action="logo.php">
    <table width='200' height='300' border='1'>
User Name <input type='text' name='name' placeholder='Enter user name' size='15'><br/>    <br/>

Password<input type='password' name='pass' size='15' placeholder='Password'><br/>              <br/>
</table>

<input type='submit' value='Login'>
</form></body></html>

Output









Now we are going to create PHP form for validation
Program

<?php
$conn=mysql_connect("localhost","root","");
$sel=mysql_select_db("login",$conn);
$name=$_POST['name'];
$pass=$_POST['pass'];
$check=mysql_query("select * from logdata where name='$name' and pass='$pass'");
$count=mysql_num_rows($check);
if($count == 1)
{
    echo "Login ";

}
else
{
    echo "failed";
}
?>



Output

If the given data are correct then following output will produced


writes file in php

writes file in php



In PHP we are using fwrite() function to retrieve data in file.we are using fwrite() function that will return how many character will placed in the file only it is display.



html>


<body>
<?php
$content="hello world";
$f=fopen('today.txt','w');
// today.txt must in read.php location
$fh=fwrite($f,$content);
// it is no of character in content
echo $fh;
fclose($f);
?>
</body>
</html>

Output:





read file in php

read from file in php
the fread() reads from an open file.The function will stop at the end of the file or when it reaches the specified length.whichever comes first.this function the read string or false on failure
syntax

frad(file,length)

Example
<html>

<body>
<?php
$f=fopen('today.txt','r');
// today.txt must in read.php location
$fh=fread($f,"6");
echo $fh;
fclose($f);
?>
</body>
</html>

Output


Opening a File in php


Opening a File in php

The fopen() function is used to open files in PHP.
Syntax:

fopen('file name','mode of operation')
  • The first parameter of this function contains the name of the file to be opened
  • the second parameter specifies in which mode the file should be opened:

  • <html>
    <body>
    <?php
    $file=fopen("welcome.txt","r");
    ?>
    </body>
    </html> 





update query in php

Update data from Php:

  In this tutorial we are show the table value can be update from old one to new one.In this example name in the field value henry will changed to the mathavan

Syntax:

update table_name set attri_name='value' where attr_value='value to be changed'

this syntax for update value in table


<?php
$conn=mysql_connect("localhost","root","");
$sel=mysql_select_db("proj",$conn);
$c = mysql_query("select * from data");
echo "<table border='1'>";
echo "<tr><td>name</td><td>Last name</td><td>Address</td><td>Email id</td><td>Phone</td></tr>";
while($fetch = mysql_fetch_array($c))
{
echo "<tr><td>$fetch[0]</td><td>$fetch[1]</td><td>$fetch[2]</td><td>$fetch[3]</td><td>$fetch[4]</td></tr>";
}
echo "</table>";
$q=mysql_query("update data set name='mathavan' where name='kenry'");
if($q)
{
echo"update";
}
$c = mysql_query("select *from data");
echo "after updating";
echo "<table border=
'1'>";
echo "<tr><td>name</td><td>Last name</td><td>Address</td><td>Email id</td><td>Phone</td></tr>";
while($row = mysql_fetch_array($c))
{
echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td></tr>";
}
echo "</table>";
?>
Output




select query in php

select query in php
From the select query in php.we are going to select entire or extract data from the table .we are using mysql_query()to retrieve the data.here example for go to get data from database.

?php
$conn=mysql_connect("localhost","root","");
$sel=mysql_select_db("proj",$conn);
$c = mysql_query("select * from data");

echo "<table border='1'>";
echo "<tr><td>name</td><td>Last name</td><td>Address</td><td>Email id</td><td>Phone</td></tr>";
while($row = mysql_fetch_array($c))
{
echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td></tr>";
}
echo "</table>";




?>

Output




Buy it 40% discount

insert form data into database php

Insert Data From a Form Into a Database
Now we will create an HTML form that can be used to add new records to the "data" table.
Here is the HTML form:

<html>
<body>
<form action="in.php" method="post">
Firstname:<input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

                    When a user clicks the submit button in the HTML form in the example above, the form data is sent to "in.php". The "in.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables. Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the database table.

Below is the code in the "in.php" page:


<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO person (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "one record added";
mysql_close($con)
?>
Buy it 40% discount

insert query in php

PHP MySQL Insert Into

The INSERT INTO statement is used to insert new records into a database table.
Insert Data Into a Database Table The INSERT INTO statement is used to add new records to a database table.

Syntax

INSERT INTO table_name
VALUES (value1, value2,....)


You can also specify the columns where you want to insert the data:

INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)


Note: 
          SQL statements are not case sensitive. INSERT INTO is the same as insert into. To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('kanna', 'kumar', '15')");
mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('senthil', 'godwin', '13')");
mysql_close($con);
?>
Buy it 40%discount

create table in mysql

Create a Table
The CREATE TABLE statement is used to create a database table in MySQL.
Syntax


CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)

We must add the CREATE TABLE statement to the mysql_query() function to execute the command.
Example
The following example shows how you can create a table named "person", with three columns.
The column names will be "FirstName", "LastName" and "Age":

≤?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE data",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table in my_db database
mysql_select_db("data", $con);
$sql = "CREATE TABLE person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
mysql_close($con);
?>

Important:

A database must be selected before a table can be created. The database is selected
with the mysql_select_db() function.
Note: When you create a database field of type varchar, you must specify the maximum length of the field, e.g. varchar(15).

Closing a Connection in mysql

Closing a Connection
The connection will be closed as soon as the script ends. To close the connection before, use the mysql_close() function.

?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>

connecting mysql with php

Connecting to a MySQL Database
Before you can access and work with data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.

Syntax


mysql_connect(servername,username,password);
Parameter Description
  • servername Optional. Specifies the server to connect to. Default value is "localhost:3306"
  • username Optional. Specifies the username to log in with. Default value is the name ofthe user that owns the server process
  • password Optional. Specifies the password to log in with. Default is ""
Note:
There are more available parameters, but the ones listed above are the most important.

Example
In the following example we store the connection in a variable ($con) for later use in the script.
The "die" part will be executed if the connection fails:

  • <?php
    $con = mysql_connect("localhost","root","");
    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }
    // some code
    ?>
  • create database in mysql

    PHP MySQL Introduction
    MySQL is the most popular open source database server.

    What is MySQL?
    • MySQL is a database. A database defines a structure for storing information.
      In a database, there are tables. Just like HTML tables, database tables contain rows, columns, and cells.
    • Databases are useful when storing information categorically. A company may have a database
    • with the following tables: "Employees", "Products", "Customers" and "Orders". 
       Database Tables:
       A database most often contains one or more tables. Each table has a name (e.g. "Customers" or"Orders"). Each table contains records (rows) with data. Below is an example of a table called "Persons": 

      LastName

      FirstName 
      Address   City            
      Hansen OlaTimoteivn10Sandnes
      SvendsonToveBorgvn 23Sandnes
      PettersenKariStorgt20Stavanger
       
       The table above contains three records (one for each person) and four columns (LastName,FirstName, Address, and City)

    die() in php

    Basic Error Handling: Using the die() function
    The first example shows a simple script that opens a text file:

    <?php
    $file=fopen("welcome.txt","r");
    ?>

    If the file does not exist you might get an error like this:

    Warning:

    fopen(welcome.txt) [function.fopen]: failed to open stream:
    No such file or directory in C:\webfolder\test.php on line 2
    To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:




    <?php
    if(!file_exists("welcome.txt"))
    {
    die("File not found");
    }
    else
    {
    $file=fopen("welcome.txt","r");
    }
    ?>

    Now if the file does not exist you get an error like this:
    File not found


    The code above is more efficient than the earlier code, because it uses a simple error handling
    mechanism to stop the script after the error.
    However, simply stopping the script is not always the right way to go. Let's take a look at
    alternative PHP functions for handling errors. 
    Buy with 40% discount

    error handling in php

    PHP Error Handling
    The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser.
    PHP Error Handling
    When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
    We will show different error handling methods:

    • Simple "die()" statements
    • Custom errors and error triggers
    • Error reporting

    php mail function

    PHP Simple E-Mail
    The simplest way to send an email with PHP is to send a text email.
    In the example below we first declare the variables ($to, $subject, $message, $from, $headers),
    then we use the variables in the mail() function to send an e-mail:


    ?php
    $to = "someone@example.com";
    $subject = "Test mail";
    $message = "Hello! This is a simple email message.";
    $from = "someonelse@example.com";
    $headers = "From: $from";
    mail($to,$subject,$message,$headers);
    echo "Mail Sent.";
    ?


    Buy today get 20% discount

    sending mail in php

    PHP Sending E-mails
    PHP allows you to send e-mails directly from a script.
    The PHP mail() Function .
    The PHP mail() function is used to send emails from inside a script.
    Syntax
    mail(to,subject,message,headers,parameters)

      Parameter Description
    • to Required. Specifies the receiver / receivers of the email
    • subject Required. Specifies the subject of the email. Note: This parameter cannot
      contain any newline characters
    • message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
    • headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
    • parameters Optional. Specifies an additional parameter to the sendmail program

    Note:
     
    For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file.

    destroying session in php

    Destroying a Session
    If you wish to delete some session data, you can use the unset() or the session_destroy() function.

    The unset() function is used to free the specified session variable:

    <?php

    unset($_SESSION['views']);
    ?> 
    function:
    You can also completely destroy the session by calling the session_destroy()


    <?php
    session_destroy();
    ?>


    Note:
     
    session_destroy() will reset your session and you will lose all your stored session data.

    storing session data php

    Storing a Session Variable
    The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

    <?php
    session_start();
    // store session data
    $_SESSION['views']=1;
    ?>
    <html>
    <body>;
    <?php
    //retrieve session data
    echo "Pageviews=". $_SESSION['views'];
    ?>
    </body>
    </html>
    Output:

    page views 1

    <?php
    session_start();
    if(isset($_SESSION['views']))
    $_SESSION['views']=$_SESSION['views']+1;
    else
    $_SESSION['views']=1;
    echo "Views=". $_SESSION['views'];
    ?>


    output:

    In the example , we create a simple page-views counter. The isset() function checks if the
    "views" variable has already been set. If "views" has been set, we can increment our counter. If
    "views" doesn't exist, we create a "views" variable, and set it to 1

    php session

    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.

    PHP Session Variables

    When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

    A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to
    store the data in a database.
    Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
    The UID is either stored in a cookie or is propagated in the URL.

    Starting a PHP Session
    Before you can store user information in your PHP session, you must first start up the session.
    Note: 
    The session_start() function must appear BEFORE the <html> tag


    <?php session_start(); ?>
    <html>

    <body>
    </body>
    </html>   

    The code above will register the user's session with the server, allow you to start saving user
    information, and assign a UID for that user's session.

    Function in session
    Destroying session
    Storing value in session

    remove cookie value in php

    How to Delete a Cookie?
    When deleting a cookie you should assure that the expiration date is in the past.
    Delete example:

    <?php
    // set the expiration date to one hour ago
    setcookie("user", "", time()-3600);
    ?>
    What if a Browser Does NOT Support Cookies?

    If your application deals with browsers that do not support cookies, you will have to use other
    methods to pass information from one page to another in your application. One method is to pass
    the data through forms (forms and user input are described earlier in this tutorial).
    The form below passes the user input to "welcome.php" when the user clicks on the "Submit"
    button:


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

    Retrieve the values in the "welcome.php" file like this:

    <html>
    <body>
    Welcome <php echo $_POST["name"]; ?>.
    You are <php echo $_POST["age"]; ?> years old. 
    <body>
    <html>

    retrieve data from cookie php

    How to Retrieve a Cookie Value?
    The PHP $_COOKIE variable is used to retrieve a cookie value.
    In the example below, we retrieve the value of the cookie named "user" and display it on a page:

    <?php
    // Print a cookie
    echo $_COOKIE["user"];
    // A way to view all cookies
    print_r($_COOKIE);
    ?>
    In the following example we use the isset() function to find out if a cookie has been set:

    <html>
    <body>
    <?php
    if (isset($_COOKIE["user"]))
    {
    echo "Welcome " . $_COOKIE["user"] . "!";
    }
    else
    echo "Welcome guest!";
    }
    ?>
    </body>
    </html>

    PHP Cookies

    PHP Cookies
    A cookie is often used to identify a user.
    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.
    How to Create a Cookie?
    The setcookie() function is used to set a cookie.
    Note:
              The setcookie() function must appear BEFORE the <html> tag. 
     Syntax
    setcookie(name, value, expire, path, domain);
    Example
    In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour:

    <?php
    setcookie("user", "Alex Porter", time()+3600);
    ?>
    Note:
    The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

    PHP Functions with Return values

    PHP Functions - Return values
    Functions can also be used to return values.

    Example


    <html>
    <body>
    <?php
    function add($x,$y)
    {
    $total = $x + $y;
    return $total;
    }
    echo "1 + 16 = " . add(1,16)
    ?>
    <body>
    </html>


    The output of the code above will be:


    1 + 16 = 17

    php functions with multiple parameters

    PHP Functions - Adding parameters
    Our first function (writeMyName()) is a very simple function. It only writes a static string.
    To add more functionality to a function, we can add parameters. A parameter is just like a variable. You may have noticed the parentheses after the function name, like:
    writeMyName(). The parameters are specified inside the parentheses.
    Example 1
    The following example will write different first names, but the same last name:

    <html>
    <body>
    <?php
    function writeMyName($fname)
    {
    echo $fname . " Refsnes.";
    }
    echo "My name is ";
    writeMyName("Kai Jim");
    echo "My name is ";
    writeMyName("Hege");
    echo "My name is ";
    writeMyName("Stale");
    ?>
    <body>
    </html>
    The output of the code above will be:
    My name is Kai Jim Refsnes.
    My name is Hege Refsnes.
    My name is Stale Refsnes.

    Example 2

    The following function has two parameters:

    <html>
    <body>
    <?php
    function writeMyName($fname,$punctuation)
    {
    echo $fname . " Refsnes" . $punctuation . "
    ";
    }
    echo "My name is ";
    writeMyName("Kai Jim",".");
    echo "My name is ";
    writeMyName("Hege","!");
    echo "My name is ";
    writeMyName("Ståle","...");
    ?>
    <body>
    </html>

    The output of the code above will be:

    My name is Kai Jim Refsnes.
    My name is Hege Refsnes!
    My name is Ståle Refsnes...

    function in php

    PHP Functions
    The real power of PHP comes from its functions.
    In PHP - there are more than 700 built-in functions available.

    PHP Functions:
    In this tutorial we will show you how to create your own functions.
    For a reference and examples of the built-in functions.
    Creating PHP functions:
    • All functions start with the word "function()"
    • Name the function - It should be possible to understand what the function does by its
    name. The name can start with a letter or underscore (not a number)
    • Add a "{" - The function code starts after the opening curly brace
    • Insert the function code
    • Add a "}" - The function is finished by a closing curly brace

    Use a PHP Function
    Now we will use the function in a PHP script:

    <html>
    <body>
    <?php
    function writeMyName()
    {
    echo "Kai Jim Refsnes";
    }
    echo "Hello world!";
    echo "My name is ";
    writeMyName();
    echo ".That's right, ";
    writeMyName();
    echo " is my name.";
    ?>
    </body>
    </html>


    The output of the code above will be:


    Hello world!
    My name is Kai Jim Refsnes.
    That's right, Kai Jim Refsnes is my name.

    More about Function
    Function with multiple parameter
    Function with return value