0% found this document useful (0 votes)
7 views43 pages

PHP Notes

This document provides an overview of PHP, including its syntax, variables, operators, and control statements. It covers essential topics such as PHP scripting blocks, variable declaration, different types of operators, and conditional statements like if, while, do-while, for loops, and switch statements. Additionally, it introduces arrays as a way to store multiple values in a single variable.

Uploaded by

saravanan.mgk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views43 pages

PHP Notes

This document provides an overview of PHP, including its syntax, variables, operators, and control statements. It covers essential topics such as PHP scripting blocks, variable declaration, different types of operators, and conditional statements like if, while, do-while, for loops, and switch statements. Additionally, it introduces arrays as a way to store multiple values in a single variable.

Uploaded by

saravanan.mgk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PHP Scripting Language

Unit I
Essentials of PHP - Operators and Flow Control - Strings and Arrays.

PHP stands for “Hypertext preprocessor” but it’s also still known its original name Personal
Home Page. It is the server-side programming language that’s taken the web world by strom-php is
far and away the most popular programming language for use on web servers. It was created by
RasmusLerdorf in 1994 ( rasmus wanted a way of logging who was looking at his online resume).
Php got such a good reputation that by 1995 it was available for use by other people.

Basic PHP Syntax

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block
can be placed anywhere in the [Link] servers with shorthand support enabled you can start a
scripting block with <? and end with ?>.

For maximum compatibility, we recommend that you use the standard form (<?php) rather
than the shorthand form.

A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting
code below, we have an example of a simple PHP script which sends the text "Hello World" to the
browser:

<html>
<body>
<?php
echo "Welcome to PHP";
?>
</body>
</html>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used
to distinguish one set of instructions from another.

There are two basic statements to output text with PHP: echo and print. In the example
above we have used the echo statement to output the text " Welcome to PHP".

Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be
executed.

Comments in PHP
In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

Variables in PHP
Variables are used for storing values, like text strings, numbers or [Link] a variable is
declared, it can be used over and over again in your [Link] variables in PHP start with a $ sign
symbol.

1 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


The correct way of declaring a variable in PHP:

$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will
not [Link]'s try creating a variable containing a string, and a variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>
PHP is a Loosely Typed Language. In PHP, a variable does not need to be declared before
adding a value to [Link] the example above, you see that you do not have to tell PHP which data type
the variable [Link] automatically converts the variable to the correct data type, depending on its
value.
In a strongly typed programming language, you have to declare (define) the type and name of
the variable before using [Link] PHP, the variable is declared automatically when you use it.

Naming Rules for Variables


A variable name must start with a letter or an underscore "_".
A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ).
A variable name should not contain spaces. If a variable name is more than one word, it should be
separated with an underscore ($my_string), or with capitalization ($myString).

String Variables in PHP


String variables are used for a value that contains [Link] we create a string we can
manipulate it. A string can be used directly in a function or it can be stored in a [Link], the
PHP script assigns the text "Welcome to php" to a string variable called $txt:

<?php
$txt="Welcome to php";
echo $txt;
?>
The output of the code above will be:Welcome to php

2 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


PHP Operators
This section lists the different operators used in PHP.
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 , x+2 4

- Subtraction x=2 , 5-x 3


* Multiplication x=4, x*5 20

/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0

Assignment Operators

Operator Example Is The Same As


= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y

Unary operator

++ Increment x=5 , ++x x=6

-- Decrement x=5, --x x=4

Comparison Operators
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

3 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


BIT-WISE OPERATORS
Operator Description Example Explanation.
& Evaluates to a binary value after X & Y AND results in a 1 if both the bits are
( AND) a bit wise AND on the operand 1. any other combination results in a
0.
| Evaluates to a binary value after X | Y OR results in a 0 if the both the bits
(OR) a bit wise OR on the two are 0. any other combination results
operand in a 1.
^ Evaluates to a binary value after X ^ Y XOR results in a 0 if both the bits are
(XOR) a bit wise XOR on the two of the same value and 1if the bits
operand. have diff. values.
~ Converts all 1 bits to 0s and all Example given bellow
0s bits to 1s
Example: a=1010001 a~ = 0101110

LOGICAL OPERATORS
&& Evaluates to true if both the X>5 && The result is true if condition1(x>5)
condition evaluate to true other Y <5 and condition2 (y<5) are both true. If
wisefalse. one of them false , the result is false.
|| Evaluates to true if at least one X > 5 || The result is true if either
of the conditions evaluates to y <10 condition1(x>5) or condition2 (y<10)
true, and false if none of the or both evaluate to true. If both the
conditions evaluates to true. conditions are false, the result is false
CONDITIONAL OPERATOR

(Condition) ? Evaluates to val1 if the X = (y>z) X is assigned the value of y if y is


val1 : val2 condition returns true and ? y :z greater than z , else x is assigned
val2 if the condition returns the value of z.
false
SHIFT OPERATORS

>> Shifts bits to the right, filling sign X=10 >>3 The result of this is 10 divided by
bits at the left and it is also called 23. an explanation is given bellow.
the signed right shift operator
<< Shifts bits to the left filling zeros at X=10<<3 Result of this is 10 multiplied by 23.
the right.
>>> Also called the unsigned shift X= -10 An explanation is given bellow.
operator works like the >> operator, >>> 3
but fills in zeroes for the left.

CONTROL STATEMENTS:

Very often when you write code, you want to perform different actions for different
[Link] can use conditional statements in your code to do [Link] PHP we have the following
conditional statements:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if a condition is true and another code if
the condition is false
if...elseif....else statement - use this statement to select one of several blocks of code to be executed
switch statement - use this statement to select one of many blocks of code to be executed

4 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


if ..else statements.
The ifdecision construct is followed by a logical expression in which data is compared and a
decision is made based on the result of comparison. The condition is true then true part statement is
to be executed and exit the loop otherwise else part statement is to be executed and exit the loop.

Syntax:
if (boolean_expr)
{
statements;
}
else
{
statements;
}

example:

<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
<input type="submit"/>
</form>
</body>
</html>
<?php
if($a%2 ==0)
echo "Given number " , $a ,"is even";
else
echo "Given number " ,$a, "is odd ";
?>

while Loop statements.


The while loop continues until the evaluating condition becomes false. The evaluating
condition has to be a logical expression and must return a true or false value. The variable that is
checked in the Boolean expression is called the loop control variable.

Syntax:
While(Boolean_expr)
{
statements
}
example:

<html>
<body>
<form action="[Link]" method="post">
Enter the value of n <input type ="text" name="n"/><br>
<input type="submit"/>
</form>
</body>
</html>

5 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


<?php
$i=1;
while($i<=$n)
{
echo "i value is ", $i;
$i=$i+1;
}
?>

do ..whileLoop:
In a while loop, the condition is evaluated at the beginning of the loop. If the
condition is false, the body of the loop is not executed. If the body of the loop must be executed at
least once, than thedo..while construct should be used. The do ..while construct places the test
expression at the end of the loop.
The keyword do marks the beginning of the loop. The braces delimit the body of the
loop. Finally, a while statement provides the condition and ends the body of the loop.

Syntax:
do
{
statements;
}while(boolean_expr);

Example program:

<html>
<body>
<form action="[Link]" method="post">
Enter the value of n <input type ="text" name="n"/><br>
<input type="submit"/>
</form>
</body>
</html>
<?php
$f=1;$i=1;
do
{
$f=$f * $i;
$i=$i+1;
}while($i<=$n);
echo $n,” ! value is”, $f;
?>
for Loop:
The while and the do..while loops are used when the number of iterations(the number of the
times the loop body is executed) is not known. The for loop is used in situations when the number of
iterations is known in advance. For example, it can be used to determine the square of each of the
first ten numbers.
The for statement consists of the keyword for, followed by parentheses containing three
expressions each separated by a semicolon. These are the initialization expression, the test
expression and the increment/decrement expression.
Syntax:
for(initialization_expr;test_expr;increment/decrement_expr)
{
statements;
}
6 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
Initialization expression:
The initialization expression is executed only once, when the control is passed to the
loop for the first time. It gives the loop variable an initial value.
Test expression:
The condition is executed each time the control passes to the beginning of the loop.
The body of the loop is executed only after the condition has been checked. If the condition
evaluated to true, the loop is executed otherwise, the control passes to the statement following the
body of the loop.
Increment / Decrement expression:
The increment / decrement expression is always executed when the control returns
to the beginning of the loop.

example:
<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
<input type="submit"/>
</form>
</body>
</html>

<?php
for ( $i=1;$i<=10;$i++)
echo $i,"X",$a,"=",$i * $a,"<br>";
?>

switch statement:

The switch statement is php’s multi way branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As such, it
often provides a better alternative than a large series of if-else-ifstatements .

Syntax:
Switch(expression)
{
casevalue1:
stt.
break;
casevalue2:
Stt.
break;
casevalue n:
Stt.
break;
default: stt.
}

The expression must be of type byte, short, int, or char; each of the values specified in the
case statements must be of a type compatible with the expression. Each case value must be a unique
literal(that is, it must be a constant, not a variable). Duplicate case values are not allowed.

The switch statement works like this: The value of the expression is compared with each of
the literal values in the case statements. If a match is found, the code sequence following that case
statement is executed.

7 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


If none of the constants matches the value of the expression, then the default statement is
executed. However, the default statement is optional. If no case matches and no default is present,
then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a
break statement is encountered, execution branches to the first line of code that follows the entire
switch statement. This has effect of “jumping out” of the switch.

<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
Enter the value of b <input type ="text" name="b"/><br>
<input type="submit"/>
</form>
</body>
</html>

<?php
switch($a)
{
case "+":
$g=$b+$c;
echo "add value is",$g;
break;
case "-":
$g=$b-$c;
echo "sub value is",$g;
break;
case "*":
$g=$b*$c;
echo "mul value is",$g;
break;
case "/":
$g=$b/$c;
echo "divide value is",$g;
break;

default:
echo "out of the choice";
}
?>
Conditional operator: ? :
If the condition is true after the ?part will be executed, condition is false after the : part will
be executed.
<html>
<body>
<form action="[Link]" method="post">
Enter the value of a <input type ="text" name="a"/><br>
Enter the value of b <input type ="text" name="b"/><br>
<input type="submit"/>
</form>
</body>
</html> <?php
$c=($a > $b) ?$a : $b;
echo “biggest value is”, $c;
?>

8 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


What is an Array?

An array is a special variable, which can store multiple values in one single variable.

If you have a list of items (a list of student names, for example), storing the student name in single
variables could look like this:

$std1=”ram”;
$std2=”anbu”;
$std3=”kumar”;
However, what if you want to loop through the student and find a specific one? And what if
you had not 3 students, but 300?The best solution here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by
referring to the array [Link] element in the array has its own index so that it can be easily
[Link], there are three kind of arrays:

 Numeric array - An array with a numeric index


 Associative array - An array where each ID key is associated with a value
 Multidimensional array - An array containing one or more arrays

Numeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$std=array("ram","anbu","kumar","rose");

2. In the following example we assign the index manually:

$std[0]=”ram”;
$std[1]=”anbu”;
$std[2]=”kumar”;
$std[3]=”rose”;

Example

In the following example you access the variable values by referring to the array name and index:

<?php
$std[0]=”ram”;
$std[1]=”anbu”;
$std[2]=”kumar”;
$std[3]=”rose”;
echo $std[0] . " and " . $std[1] . " are bright sudents.";
?>

The code above will output:ram and anbu are bright students.

Associative Arrays
An associative array, each ID key is associated with a [Link] storing data about specific
named values, a numerical array is not always the best way to do [Link] associative arrays we can
use the values as keys and assign values to them.

9 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Example 1
In this example we use an array to assign ages to the different persons:

$ages = array(mani=>20, pradeep=>21, ragu=>22);

Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages[mani]=20;
$ages[pradeep]=21;
$ages[ragu]=22;

The ID keys can be used in a script:

<?php
$ages[mani]=20;
$ages[pradeep]=21;
$ages[ragu]=22;
echo” mani is” ,$ages[mani],”years old”;
?> output of the program is: mani is 20 years old

<?php
$ar = array(100,75,150,25);
for ($i=0; $i<= 4; $i++) //prints the array elements
echo $ar[$i]."<br \>";
sort($ar);
echo " sorted values are";
for ($i=0; $i<= 4; $i++)
{
echo $ar[$i]."<br \>";
}
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on.

String functions:

Strlen  to find length of the given string


Strtolower to display lower case of string in given string
Strtoupper to display upper case of string in given string
Strrev to display reverse of the given string
Strcmp to compare both the strings are equal or not
Strops Find the position of the first occurrence of a substring in a string
Str_replace Replace all occurrences of the search string with the replacement string
.  There are two string operators. The first is the concatenation operator ('.'), which returns the
concatenation of its right and left arguments.

10 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


<html>
<body>
<font size ="6">
<form action="[Link]" method="post">
concat first string: <input type="text" name="a"/><br>
concat second string: <input type="text" name="b"/><br>
string length string: <input type="text" name="c"/><br>
upper string: <input type="text" name="d"/><br>
lower string: <input type="text" name="e"/><br>
string reverse: <input type="text" name="f"/><br>
<input type="submit" />
</form>
</body>
</html>

[Link].
<html>
<body>
<font size ="6">

<?php
$x=array($a,$b,$c,$d,$e,$f);
for($i=0;$i<=5;$i++)
{
echo "given ",$i,"string is:",$x[$i],"<br>";
}
echo "concatnation of first & second string is:",$a.$b,"<br>";
echo "string length of the given 3rd string is:", strlen($c),"<br>";
echo "upper case functon of 4th string: ",strtoupper ($d),"<br>";
echo "lower case functon of 5th : ",strtolower ($e),"<br>";
echo "string reverse function of 6th string is: ", strrev($f),"<br>";
echo "string comparision first & second :",strcmp($a,$b),"<br>";
echo "string replace functin given string is php lab output is project lab:",
str_replace("php","lab","projectphp")."<BR>";
echo "string possiton function: given string is bcaphp lab, php :",
strpos("bcaphp lab!","php","<br>");
$f=strrev($a);
if(strcmp($a,$f)==0)
echo "given string is polyndrome";
else
echo "given string is not polyndrome";

?>
</font>
</html>

I unit over

11 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Unit II
Creating Functions - Reading Data in Web Pages - PHP Browser - Handling Power.

FUNCTIONS:
It is a sub program. It will be reduce the size of the program by calling and using them at
different places in the program.
The advantages are: Re-usability, modularity, overall programming simplicity.

Function function_name([argument_list …] )
{ statements;
return ([return value] );
}
Example:
<?php
display();
function display()
{
echo "welcome to php function program";
}
?>
Passing functions some data:
In this method php program to call the function with argument that value passing to that
particular function then only it will be executed.
<?
echo "function with argument";
sqr(4);
functionsqr($a)
{
$b=$a * $a;
echo "square of ", $a, " is : ", $b;
}
?>

12 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Return type of functions:
All functions, except those of type void, return a value. This value is specified by the return
statement. A non-void function must be contain a return statement that returns a value.

<?php
echo "return type of function : ",sqr($a);
functionsqr($a)
{
$b=$a * $a;
return $b;
}
?>

Nested function:
A function within another one function is called nested [Link] functions will not
exist before their parent function has been called. Knowing this, you should be able to avoid some
common developer mistakes.
Once you have called the parent function, the child function will become accessible
anywhere in the script.

<?
sqr($a);
sqr1();
functionsqr($a)
{
echo "welcome to nested function <br>";
function sqr1()
{
echo "welcome to inner function <br>";
}
$b=$a * $a;
echo "square value of : ", $b, "<br>";
}
?>

13 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Recursive function:
A function that calls itself is known as recursive function and the process of calling function
itself is known as recursion.
<?
echo $n, " ! value is : ",fact($n);
function fact($n)
{
if ($n==1)
return 1;
else
$res=fact($n-1)*$n;
return $res;
}
?>

Reading Data in Web Pages


Text field:
To get at the text that a user entered into a text box, the text box needs a NAME attribute.
You then tell PHP the NAME of the textbox you want to work with. Our text box hasn't got a
NAME yet, so change your HTML to this:

<INPUT TYPE = "Text" VALUE ="username" NAME = "username">

The NAME of our textbox is username. It's this name that we will be using in a PHP scrip

<html>
<body>
<form action="[Link]" method ="get">
What's your name ?<input type ="text" name="data"><br>
<input type ="submit" value ="send">
<input type ="reset" value ="reset">
</form>
</body>
</html>

14 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


<html>
<body>
thanks for answering:
<?PHP
echo $_REQUEST["data"];
?>
</body> </html>

Text area:

<html>
<body>
<form action="[Link]" method ="post">
Enter the data into text areas

<textarea name="data" cols ="50" rows = "5">


1.
2.
3.
4.
5.
</textarea>

<input type ="submit" value ="send">

</form>
</body>
</html>

text area data reading: <br>

<?PHP
$text =$_REQUEST["data"];
echostr_replace("\n","<br>",$text);

15 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


?>

Check boxes:

<html>
<body>
<form action="[Link]" method ="post">
Enter your course detail:

<input type="checkbox" name="check1" value="ug">ug


<input type="checkbox" name="check" value="i year">i year
<input type="checkbox" name="check" value="ii year">ii year
<input type="checkbox" name="check" value="iii year">iii year

<input type="checkbox" name="check5" value="A SECTION">A SECTION


<input type="checkbox" name="check5" value="B SECTION">B SECTION <br>
select your sex :
<input type="radio" name="radios" value="male">male
<input type="radio" name="radios" value="female">female<br>
<input type ="submit" value ="send">
</form>
</body>
</html>

example of check box and radio buttons <br>


<font size=10>
<?PHP
echo " you are in ",$_REQUEST["check1"],"<BR>";
echo " you are in ", $_REQUEST["check"],"<BR>";
echo " you are in ", $_REQUEST["check5"],"<BR>";
echo " you are ",$_REQUEST["radios"];
?>

List boxes:
<html>
<body>
<form action="[Link]" method ="post">
select your ice cream flavors:

16 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


<select name="icecream" multiple>
<option>venilla</option>
<option>strawberry</option>
<option>chocolate</option>
<option>fruit</option>

<input type ="submit" value ="send">

</form>
</body>
</html>

your favorite ice cream flavour is: <br>

<?PHP
echo $_REQUEST["icecream"];
?>
Password control:
<html>
<body>
<form action="[Link]" method ="post">
Enter your password :
<input type ="password" name="password">
<input type ="submit" value ="send">
</form>
</body>
</html>

reading data from password control: <br>

<?PHP

if($_REQUEST["password"]=="arun")
{
echo " your password is correct","<br>";
echo " this is password control prgram";
}

17 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


else
{
echo " your password is incorrect","<br>";
echo " i think you are a wrong person";
}

?>

Image control:
<html>
<body>

Entering data with image maps:


<form action="[Link]" method ="post">

click the image:


<input type ="image" name="imap" src="[Link]">
</form>
</body>
</html>

reading data from image map control: <br>


you clicked the image map at location(
<?php

echo $_REQUEST["imap_x"], ", ",$_REQUEST["imap_y"] ;


?>

).

18 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


File uploads:

<html>
<body>

<form action="[Link]" enctype="multipart/form-data" method ="post">


upload file: <input name="userfile" type="file"/>
<input type="submit" value="send file" />
</form>
</body>
</html>

reading file upload control: <br>

the file contained:

<?php

$handle=fopen($_FILES['userfile']['tmp_name'],"r");
while(!feof($handle))
{
$text=fgets($handle);
echo $text,"<br>";
}
fclose($handle);

?>

Button control:
<html>
<body>
<form action="[Link]" method ="post">
enter the a value <input type="text" name="a"/><br>
enter the b <input type="text" name="b"/><br>
<input type ="submit" value ="add" name = "button">
<input type ="submit" value ="sub" name = "button">
<input type ="submit" value ="mul" name = "button">

19 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


</form>
</body>
</html>

20 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


example of buttons: <br>
<?PHP

$x=$_REQUEST["button"];
if($x=="add")
{
echo "you click button 1";
$c=$a+$b;
echo " add value is",$c;
}
elseif($x=="sub")
{
echo "you click button 2";
$c=$a-$b;
echo " sub value is",$c;
}
else
{
echo "you click button3";
$c=$a*$b;
echo " mul value is",$c;
}
?>

21 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


example of php browser handling power: <br>
<?PHP
if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE"))
{
echo("<marquee><h1>you are using the internet explorer</h1></marquee>");
}
elseif(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox"))
{
echo("<marquee><h1>you are using the firefox</h1></marquee>");
}
else
{
echo("<marquee><h1>you are not using internet explorer or firefox</h1></marquee>");
}
?>

22 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


UNIT V
PHP : Functions - Classes and Objects - HTML forms - HTTP authentication with PHP -
Cookies - Handling file uploads - Using remote files - Connection handling - Database
Connections
FUNCTIONS:
It is a sub program. It will be reduce the size of the program by calling and using them at
different places in the program.
The advantages are: Re-usability, modularity, overall programming simplicity.

Create a PHP Function

A function will be executed by a call to the function.

Syntax
function functionName()
{
code to be executed;
}

PHP function guidelines:

 Give the function a name that reflects what the function does
 The function name can start with a letter or underscore (not a number)

PHP Functions - Adding parameters

To add more functionality to a function, we can add parameters. A parameter is just like a variable.

Parameters are specified after the function name, inside the parentheses.

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

R. ARUN KUMAR HEAD, DEPT OF C.A , SCAS,


PBLR

23 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


PHP Functions - Return values

To let a function return a value, use the return statement.

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

class

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of
curly braces which enclose the definitions of the properties and methods belonging to the class.

The class name can be any valid label which is a not a PHP reserved word. A valid class name starts
with a letter or underscore, followed by any number of letters, numbers, or underscores

Class program:
<?php
class one
{
function show()
{
echo "welcome to php class";
}
}
$a=new one();
$a->show();
?>

Constructor
To allocate a memory.

Often an object will require some form of initialization when it is created. To


accommodate this, php allows you to define constructors for your classes. A constructor is a
special method that creates and initializes an object of a particular class. It has the same name
as its class and may accept arguments. In this respect, it is similar to any other function
However, a constructor does not have a return type. Instead, a constructor returns a reference
to the object that it creates.
A constructor is invoked automatically when the objects are created.

R. Arun kumar Head, Dept of C.A , SCAS, PBLR

void __construct ([ mixed $args [, $... ]] ) or function one()

PHP 5 allows developers to declare constructor methods for classes. Classes which have a
constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
24 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
<?php
class one
{
var $a,$b,$c,$d,$e;
function __construct($x,$y)
{
$this->a=$x;
$this->b=$y;
}
function show()
{
echo "a value is",$this->a,"<br>";
echo "b value is",$this->b,"<br>";
$this->c=$this->a + $this->b;
echo "add value is",$this->c,"<br>";
}
}
echo "example of constructor<br>";

$t=new one(4,6);
$t->show();

Destructor
A destructor, as the name implies, is used to destroy the objects that have been created by a
constructor. Like a constructor, the destructor is a member function whose name is the same as the
class name.
A destructor never takes any argument nor does it return any value. It will be invoked
implicitly be the compiler upon exit from the program to clean up storage that is no longer
accessible. It is good practice to declare destructors in a program since it releases memory space for
future use.

void __destruct ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as
C++. The destructor method will be called as soon as all references to a particular object are
removed or when the object is explicitly destroyed or in any order in shutdown sequence.

<?php
class one
{
var $a,$b,$c,$d,$e; R. Arun kumar Head, Dept of C.A , SCAS,
PBLR

function __construct($x,$y)

25 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


{
$this->a=$x;
$this->b=$y;
}
function show()
{
echo "a value is",$this->a,"<br>";
echo "b value is",$this->b,"<br>";
$this->c=$this->a + $this->b;
echo "add value is",$this->c,"<br>";
}
Function __destruct()
{
echo "example of destructor<br>";
} }
$t=new one(4,6);
$t->show();

Inheritance:

Inheritance is new class derived from old class. Some modification about particular class. It
should invoke super class(base class) & sub class(derived class).

Types of inheritance:
1. Single Inheritance (only one super class).
2. multiple inheritance (several super class).
3. Multilevel inheritance (derived from a derived class).
4. Hybrid Inheritance (combination of multiple and multilevel inheritance).
5. Hierarchical inheritance ( one super class, many subclasses).

Defining a subclass:
class subclass name extends super class name
{
variable declaration;
function declaration;

The keyword extends signifies that the properties of the super class name are extended to the
subclass name. The subclass will now contain its own variables and methods as well those of the
super class. This kind of situation occurs when we want to add some more properties to an existing
class without actually modifying it.

R. Arun kumar Head, Dept of C.A , SCAS,


PBLR

Example of Single inheritance:

26 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


<?php
class one
{var $a,$b,$c,$d,$e;
function cal($x,$y)
{
$this->a=$x;
$this->b=$y;
echo "a value is",$this->a,"<br>";
echo "b value is",$this->a,"<br>";
$this->c=$this->a + $this->b;
echo "add value is",$this->c,"<br>";
} }
class two extends one
{
var $b;
function cal1($x)
{
$this->d=$x;
echo "a value is",$this->a,"<br>";
echo "c value is",$this->c,"<br>";
echo "d value is",$this->d,"<br>";
$this->e=$this->a * $this->c *$this->d;
echo "mul value is",$this->e,"<br>";
} }
echo "single inheritance<br>";
$t=new two;
$t->cal(4,4);
$t->cal1(6);

Multilevel inheritance:

<?php
class one
{
var $a,$b,$c,$d,$e;
function cal($x,$y) R. Arun kumar Head, Dept of C.A , SCAS, PBLR

{
$this->a=$x;

27 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


$this->b=$y;
echo "a value is",$this->a,"<br>";
echo "b value is",$this->a,"<br>";
$this->c=$this->a + $this->b;
echo "add value is",$this->c,"<br>";
}
}
class two extends one
{
var $b;
function cal1($x)
{
$this->d=$x;
echo "a value is",$this->a,"<br>";
echo "c value is",$this->c,"<br>";
echo "d value is",$this->d,"<br>";
$this->e=$this->a * $this->c *$this->d;
echo "mul value is",$this->e,"<br>";
} }
class three extends two
{
var $v,$f;
function cal2($x)
{
$this->v=$x;
$this->f=$this->v+$this->d;
echo "add final value is",$this->f,"<br>";
} }
echo "multi level inheritance<br>";
$t=new three;
$t->cal(4,4);
$t->cal1(6);
$t->cal2(6);
R. Arun kumar Head, Dept of C.A , SCAS,
PBLR

28 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Php html forms:

We will briefly build an HTML form, and call the form data using PHP. PHP offers several
methods for achieving this goal, so feel free to substitute alternative methods as you follow along.
Our example will show you a method using a single .php file, combining both PHP and HTML in
one simple text file,

Input Fields:

As mentioned in the Forms Tutorial, just be sure to place the name attribute within the tags and
specify a name for the field. Also be aware that for our form's action we have placed the
$PHP_SELF super global to send our form to itself.

Text area:

In reality, textareas are oversized input fields. Treat them the same way, just be aware of
the wrap attribute and how each type of wrap will turn out. PHP relys on this attribute to display the
textarea

Radios and check boxes

The catch with radio buttons lies with the value attribute. The text you place under the value
attribute will be displayed by the browser when the variable is called with PHP.

Check boxes require the use of an array. PHP will automatically place the checked boxes into
an array if you place [] brackets at the end of each name.

Selection List:

To name a selection form, place the name attribute within the select tags at the beginning of the
form, and then place the appropriate value to fit each option.

Submission button:

We mentioned that the submission button was missing. Now's the time to throw it into the
existing code. The button is the same as any submission button, the only thing we need to be sure to
add is a name to it so we can call it later using PHP.

Example:

</head>
<body>
<form method="post" action="[Link]">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
Gender:<br />
Male:<input type="radio" value="Male" name="gender"><br />
Female:<input type="radio" value="Female" name="gender"><br />

Please choose type of food:<br />


vegitable:<input type="checkbox" value="vegitable" name="food[]"><br />
Pizza:<input type="checkbox" value="Pizza" name="food[]"><br />
Chicken:<input type="checkbox" value="Chicken" name="food[]"><br />

R. Arun kumar Head, Dept of C.A , SCAS, PBLR

<textarea rows="5" cols="20" name="quote" wrap="physical"> favorite quote!</textarea><br />

29 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Select a Level of Education:<br />
<select name="education">
<option value="[Link]">[Link]</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br />

Select your favorite time of day:<br />


<select name="TofD" size="3">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select><br />
<input type="submit" value="submit" name="submit">
</form>

[Link]
<font size=6>
<?php

$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];

echo "your first name is:", $Fname,"<br>";


echo "your last name is :", $Lname,"<br>";
echo "you are :", $gender,"<br>";
echo "your favirote food is :","<br>";
foreach ($food as $f)
{
echo $f."<br />";
}

echo $quote,"<br>";
echo "your education is :", $education,"<br>";
echo "your favirote time is: ", $TofD,"<br>";
?>

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);

R. Arun kumar Head, Dept of C.A , SCAS, PBLR

<?php
setcookie("user", "Alex Porter", time()+3600);
echo "cookie is set now";

30 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


?>

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:

<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
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);
?>
<a href="[Link]">[Link]</a>
</html>

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.

Storing a Session Variable

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

<?php
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?> R. Arun kumar Head, Dept of C.A , SCAS,
PBLR

Destroying a Session

31 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


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']); ?>

You can also completely destroy the session by calling the session_destroy() function:

<?php session_destroy(); ?>

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

HTTP authentication with PHP


It is possible to use the header() function to send an "Authentication Required" message to
the client browser causing it to pop up a Username/Password input window. Once the user has filled
in a username and a password, the URL containing the PHP script will be called again with the
predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name,
password and authentication type respectively. These predefined variables are found in the
$_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0)
authentication methods are supported.

<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Test Authentication System"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid login ID and password to access this resource\n";
exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) ||
($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER']))
{
authenticate();
} else
{
echo "<p>Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "<br />";
echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']);
echo "<form action='' method='post'>\n";
echo "<input type='hidden' name='SeenBefore' value='1' />\n";
echo "<input type='hidden' name='OldAuth' value=\"" .
htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "\" />\n";
echo "<input type='submit' value='Re Authenticate' />\n";
echo "</form></p>\n";
} ?>
Another example:
<?php
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>"; ?>
It will give current username and password.

Create an Upload-File Form


32 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
To allow users to upload files from a form can be very useful.

 The enctype attribute of the <form> tag specifies which content-type to use when submitting
the form. "multipart/form-data" is used when a form requires binary data, like the contents of
a file, to be uploaded
 The type="file" attribute of the <input> tag specifies that the input should be processed as a
file. For example, when viewed in a browser, there will be a browse-button next to the input
field

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file
uploads.

By using the global PHP $_FILES array you can upload files from a client computer to the remote
server.

The first parameter is the form's input name and the second index can be either "name", "type",
"size", "tmp_name" or "error". Like this:

 $_FILES["file"]["name"] - the name of the uploaded file


 $_FILES["file"]["type"] - the type of the uploaded file
 $_FILES["file"]["size"] - the size in bytes of the uploaded file
 $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the
server
 $_FILES["file"]["error"] - the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on
what the user is allowed to upload.

File upload:

<html>
<body>

<form action="[Link]" method="post" enctype="multipart/form-data">


<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<arun>
</body>
</html>

<?php
echo " this is the content of the file","<br>";
$file=fopen($_FILES["file"]["tmp_name"],"r");
while(!feof($file))
{
$text=fgets($file);
echo $text,"<br>";
}
fclose($file);

?> R. Arun kumar Head, Dept of C.A , SCAS,


PBLR

Another example:
33 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
<?php
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"],"<br>";
echo " this is the content of the file","<br>";
$file=fopen($_FILES["file"]["tmp_name"],"r");
while(!feof($file))
{
$text=fgets($file);
echo $text,"<br>";
}
fclose($file);?>

database:

Create a Connection to a MySQL Database


Before you can access 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 of the
user that owns the server process

password Optional. Specifies the password to log in with. Default is ""

Closing a Connection
The connection will be closed automatically when the script ends. To close the connection before,
use the mysql_close() function:
A database holds one or multiple tables.
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax

CREATE DATABASE database_name

To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.

Create a Table
34 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR
The CREATE TABLE statement is used to create a 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.
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).

Insert Data Into a Database Table

The INSERT INTO statement is used to add new records to a database table.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:

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

The second form specifies both the column names and the values to be inserted:

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

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.
Select Data From a Database Table

The SELECT statement is used to select data from a database.


Syntax

SELECT column_name(s) FROM table_name

To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.

R. Arun kumar Head, Dept of C.A , SCAS, PBLR

35 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


<?php
$con=mysql_connect("localhost","root","vertrigo");
$db=mysql_select_db("arun",$con);
$query="create table mca1(name varchar(10),rno varchar(5))";
$result=mysql_query($query);
echo "table created";

$query="insert into mca1 values('raja','456')";


$result=mysql_query($query);

$query="insert into mca1 values('ramu','567')";


$result=mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>name</th><th>gender</th>";
$query="select * from mca1";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>",$row['name'],"</td><td>",$row['rno'];
echo "</tr>";
}
echo"</table>";
mysql_close($con);
?>
The WHERE clause

The WHERE clause is used to extract only those records that fulfill a specified criterion.
Syntax

SELECT column_name(s) FROM table_name WHERE column_name operator value

To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.

R. Arun kumar Head, Dept of C.A , SCAS,


PBLR

36 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Update Data In a Database

The UPDATE statement is used to update existing records in a table.


Syntax

UPDATE table_name SET column1=value, column2=value2,.WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
<?php
$con=mysql_connect("localhost","root","vertrigo");
$db=mysql_select_db("arun",$con);
$query="update mca1 set name='arun' where name='kumar'";
$result=mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>name</th><th>gender</th>";
$query="select * from mca1";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>",$row['name'],"</td><td>",$row['rno'];
echo "</tr>";
}
echo"</table>";
mysql_close($con);
?>
R. Arun kumar Head, Dept of C.A , SCAS,
PBLR

37 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


Delete Data In a Database

The DELETE FROM statement is used to delete records from a database table.
Syntax

DELETE FROM table_name WHERE some_column = some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record
or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
To get PHP to execute the statement above we must use the mysql_query() function. This function is
used to send a query or command to a MySQL connection.
<?php
$con=mysql_connect("localhost","root","vertrigo");
$db=mysql_select_db("arun",$con);

echo "<table border='1'>";


echo "<tr>";
echo "<th>name</th><th>gender</th>";
$db=mysql_query("delete from mca where name='saran')");
echo "one record added","<br>";

$query="select * from mca1";


$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>",$row['name'],"</td><td>",$row['gender'];
echo "</tr>";
}
echo"</table>";
mysql_close($con);
?> R. Arun kumar Head, Dept of C.A , SCAS,
PBLR

38 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


File Transfer protocol (FTP)

FTP Functions

Function Description
ftp_alloc() Allocates space for a file to be uploaded to the FTP server
ftp_cdup() Changes to the parent directory on the FTP server
ftp_chdir() Changes the current directory on the FTP server
ftp_chmod() Sets permissions on a file via FTP
ftp_close() Closes an FTP connection
ftp_connect() Opens an FTP connection
ftp_delete() Deletes a file on the FTP server
ftp_exec() Executes a command on the FTP server
Downloads a file from the FTP server and saves it into an open local
ftp_fget()
file
ftp_fput() Uploads from an open file and saves it to a file on the FTP server
ftp_get_option() Returns runtime options of the FTP connection
ftp_get() Downloads a file from the FTP server
ftp_login() Logs in to the FTP connection
ftp_mdtm() Returns the last modified time of a specified file
ftp_mkdir() Creates a new directory on the FTP server
ftp_nb_continue() Continues retrieving/sending a file (non-blocking)
Downloads a file from the FTP server and saves it into an open file
ftp_nb_fget()
(non-blocking)
Uploads from an open file and saves it to a file on the FTP server
ftp_nb_fput()
(non-blocking)
ftp_nb_get() Downloads a file from the FTP server (non-blocking)
ftp_nb_put() Uploads a file to the FTP server (non-blocking)
ftp_nlist() Returns a list of files in the specified directory on the FTP server
ftp_pasv() Turns passive mode on or off
ftp_put() Uploads a file to the FTP server
ftp_pwd() Returns the current directory name
ftp_quit() An alias of ftp_close()
ftp_raw() Sends a raw command to the FTP server
ftp_rawlist() Returns a list of files with file information from a specified directory
ftp_rename() Renames a file or directory on the FTP server
ftp_rmdir() Deletes an empty directory on the FTP server
ftp_set_option() Sets runtime options for the FTP connection
ftp_site() Sends an FTP SITE command to the FTP server
ftp_size() Returns the size of the specified file
ftp_ssl_connect() Opens a secure SSL-FTP connection
ftp_systype() Returns the system type identifier of the FTP server

39 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


FTP get(): (Download file)
Save into local file
Syntax:
ftp_get(ftp_connection,local_file,server_file,mode,startpos);
Example:
<?php
$ftp_server=”[Link]”;
$ftp_conn=ftp_connect($ftp_server);
$login=ftp_login($ftp_conn,$ftp_username,$ftp_userpassword);
$local_file=”[Link]”;
$server_file=”[Link]”;
if(ftp_get($ftp_con,$local_file,$server_file,FTP_ASCII))
{
echo $local_file;
}
else
{
echo $server_file;
}
$ftp_close($ftp_conn);
?>

FTP_put():(upload file)
Syntax:
ftp_put(ftp_connection,remote_file,local_file,mode,startpos);
Example:
if(ftp_get($ftp_con,$local_file,$server_file,FTP_ASCII))
{
echo $file;
}
else
{
echo $file;
}
ftp_close($ftp_conn);

40 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


?>

PHP ftp_fput() Function

Example

Open local file, and upload it to a file on the FTP server:

<?php
// connect and login to FTP server
$ftp_server = "[Link]";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

// open file for reading


$file = "[Link]";
$fp = fopen($file,"r");

// upload file
if (ftp_fput($ftp_conn, "[Link]", $fp, FTP_ASCII))
{
echo "Successfully uploaded $file.";
}
else
{
echo "Error uploading $file.";
}

// close this connection and file handler


ftp_close($ftp_conn);
fclose($fp);
?>

Parameter Description
ftp_connection Required. Specifies the FTP connection to use
remote_file Required. Specifies the file path to upload to
open_file Required. Specifies an open local file. Reading stops at end of file
Required. Specifies the transfer mode. Possible values: FTP_ASCII or
mode
FTP_BINARY
startpos Optional. Specifies the position in the remote file to start uploading to

41 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


PHP ftp_close() Function

Example

Connect, login, and close an FTP connection:

<?php
// connect and login to FTP server
$ftp_server = "[Link]";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

// then do something...

// close connection
ftp_close($ftp_conn);
?>

Definition and Usage

The ftp_close() function closes an FTP connection.

Syntax

ftp_close(ftp_connection);

Parameter Description
ftp_connection Required. Specifies the FTP connection to close

PHP ftp_login() Function

Example

Connect, login, and close an FTP connection:

<?php
// connect to FTP server
$ftp_server = "[Link]";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");

// login
if (@ftp_login($ftp_conn, $ftp_username, $ftp_userpass))
{
echo "Connection established.";
}
else
{
echo "Couldn't establish a connection.";
}

42 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR


// do something...

// close connection
ftp_close($ftp_conn);
?>

Definition and Usage

The ftp_login() function logs in to the specified FTP connection.

Syntax

ftp_login(ftp_connection,username,password);

Parameter Description
ftp_connection Required. Specifies the FTP connection to use
username Required. Specifies the username to login with
password Required. Specifies the password to login with

43 [Link] [Link], DEPT OF CA, SCAS, PERAMBALUR

You might also like