SlideShare a Scribd company logo
USING FUNCTIONS IN PHP
Functions in PHP are blocks of code designed to perform specific
tasks.
They enhance code reusability, maintainability, and
organization.
PHP supports two main types of functions: built-in functions
and user-defined functions.
 PHP comes with a vast library of built-in functions, which are
pre-defined and ready to use. These functions cover a wide range
of tasks, including string manipulation, mathematical
calculations, and file handling.
Examples
 strlen(): Returns the length of a string.
 array_push(): Adds one or more elements to the end of an array.
 var_dump(): Displays structured information about one or more
variables.
Built-in Functions
USER-DEFINED FUNCTIONS
User-defined functions allow you to create your own functions tailored to
your specific needs.
function
functionName($parameter1,
$parameter2) {
// code to be executed
}
function sample($name) {
echo "Hello, $name!";
}
// Calling the function
sample("Abc");
Syntax Example
FUNCTION PARAMETERS
Functions can accept parameters, which are variables passed into the
function. You can define multiple parameters, separated by commas.
function add($a, $b)
{
return $a + $b;
}
$result = add(5, 10);
echo "The sum is: $result"; // Outputs: The sum is: 15
DEFAULT PARAMETER VALUES
You can set default values for parameters. If a value is not
provided during the function call, the default value will be used.
function greet($name = "Guest")
{
echo "Hello, $name!";
}
greet(); // Outputs: Hello, Guest!
greet("Bob"); // Outputs: Hello, Bob!
RETURNING VALUES
Functions can return values using the return statement. Once a return
statement is executed, the function stops executing.
function square($number)
{
return $number * $number;
}
echo "The square of 4 is: " . square(4); // Outputs: The square of 4 is: 16
CALL BY VALUE VS. CALL BY REFERENCE
By default, PHP passes arguments to functions by value, meaning a copy of the variable is
passed. If you want to pass a variable by reference (allowing the function to modify the
original variable), you can use the & symbol.
function increment(&$value)
{
$value++;
}
$num = 5;
increment($num);
echo $num; // Outputs: 6
UNIT - IV
PHP and Operating System
Managing Files USING FTP in PHP
Steps to manage files via FTP in
PHP
 Connect to an FTP Server
 Upload a File
 Download a File
 Delete a File
 List Files in a Directory
 Change Directory
 Create a Directory
 Close the FTP Connection
<?php
$ftp_server = "ftp.example.com";
$ftp_username = "your_username";
$ftp_password = "your_password";
$local_file = "localfile.txt";
$remote_file = "remotefile.txt";
// Establish FTP connection
$ftp_conn = ftp_connect($ftp_server) or
die("Could not connect to $ftp_server");
// Login to FTP server
if (@ftp_login($ftp_conn, $ftp_username,
$ftp_password)) {
echo "Connected to $ftp_server
successfully.n";
// Upload a file
if (ftp_put($ftp_conn, $remote_file,
$local_file, FTP_BINARY))
{
echo "Successfully uploaded
$local_file.n";
} else {
echo "Error uploading
$local_file.n";
}
// List files in root directory
$file_list = ftp_nlist($ftp_conn, "/");
if ($file_list) {
echo "Files in root directory:n";
foreach ($file_list as $file) {
echo "$filen";
}
}
// Close connection
ftp_close($ftp_conn);
} else {
echo "Could not log in to
$ftp_server.";
}
?>
Reading and Writing Files
in PHP
Writing to a
File
 To write to a file in PHP, you
can use the fwrite( ) function,
which writes content to an
open file.
 To open a file, use the fopen( )
function.
<?php
$filename = "example.txt";
$content = "Hello, this is a sample text.";
// Open the file for writing (creates the file if it
doesn't exist)
$file = fopen($filename, "w");
// Write content to the file
if (fwrite($file, $content)) {
echo "File written successfully.";
} else {
echo "Error writing to the file.";
}
// Close the file
fclose($file);
?>
File Modes
•"w": Write-only. Opens and clears the file content (if the file exists) or
creates a new file.
•"w+": Read and write. Clears the file content or creates a new one.
•"a": Write-only. Opens and writes to the end of the file (append mode).
•"a+": Read and write. Writes to the end of the file.
•"r": Read-only. Opens the file for reading. Fails if the file does not exist.
•"r+": Read and write. Does not clear the file content.
Reading from a File
 To read content from a
file, you can use the
fread() function,
 For smaller files,
file_get_contents() can be
used, which reads the
entire file into a string.
Reading with
file_get_contents()
<?php
$filename = "example.txt";
// Read entire file content
$content =
file_get_contents($filename);
if ($content !== false) {
echo "File content:n$content";
} else {
echo "Error reading the file.";
}
?>
Steps to Read a File Using
fread()
<?php
$filename = "example.txt";
// Open the file for reading
$file = fopen($filename, "r");
// Read file content
if ($file) {
$filesize = filesize($filename);
$content = fread($file, $filesize);
echo "File content:n$content";
} else {
echo "Error opening the file.";
}
// Close the file
fclose($file);
?>
 fopen() Opens a file.
 fwrite() Writes data to a file.
 fread() Reads data from a file.
 file_get_contents() Reads entire file
content.
 fgets() Reads a line from a
file.
 file_exists() Checks if a file exists.
 unlink() Deletes a file.
 chmod() Changes file
permissions.
 move_uploaded_file() Handles file uploads
Common PHP File
Functions
DEVELOPING OBJECT-ORIENTED SCRIPT USING PHP
create reusable and modular code by organizing it into
objects. Let's go over the basic structure for creating an
object-oriented script in PHP.
 Classes: Blueprint for creating objects. Classes define
properties (variables) and methods (functions) that can
be used by the objects created from the class.
 Objects: Instances of a class.
 Properties: Variables within a class.
 Methods: Functions defined inside a class that can
<?php
// Define a class
class Car {
// Properties
public $make;
public $model;
public $year;
// Constructor (automatically called when an object is created)
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
// Method
public function getCarInfo() {
return "Car: " . $this->make . " " . $this->model . " (" . $this->year .
")";
}
// Setter method
public function setYear($year)
{
$this->year = $year;
}
// Getter method
public function getYear() {
return $this->year;
}
}
// Create an object (instance of the Car class)
$myCar = new Car("Toyota", "Corolla", 2020);
// Accessing a method
echo $myCar->getCarInfo();
//Output: Car: Toyota Corolla (2020)
// Changing the year using a setter method
$myCar->setYear(2022);
// Accessing the updated value
echo $myCar->getCarInfo();
?>
Output: Car: Toyota Corolla (2022)
($make, $model, and $year) and methods (getCarInfo, setYear,
getYear).
 Constructor: The __construct() method initializes an object
when it is created. Here, it sets the car’s make, model, and year.
Methods
 getCarInfo() is a method that returns a string with the car’s
details.
 setYear() and getYear() are setter and getter methods to
update and retrieve the value of the year property.
 Object Instantiation: $myCar = new Car("Toyota", "Corolla",
2020); creates a new object of the Car class, passing initial
values.
 Accessing Methods and Properties: $myCar->getCarInfo();
accesses the object’s method, and $myCar->setYear(2022);
EXCEPTION HANDLING
 Exception handling is a mechanism in programming that allows a system to handle unexpected events or errors that
occur during the execution of a program.
 These unexpected events, known as exceptions, can disrupt the normal flow of an application.
 Exception handling provides a controlled way to respond to these exceptions, allowing the program to either correct
the issue or gracefully terminate.
Why Do We Need Exception Handling?
1.Maintaining Application Flow: Without exception handling, an unexpected error could
terminate the program abruptly. Exception handling ensures that the program can continue
running or terminate gracefully.
2.Informative Feedback: When an exception occurs, it provides valuable information about the
problem, helping developers to debug and users to understand the issue.
3.Resource Management: Exception handling can ensure that resources like database
connections or open files are closed properly even if an error occurs.
4.Enhanced Control: It allows developers to specify how the program should respond to specific
types of errors.
Here is an example of a basic PHP try catch statement.
try {
// run your code here
}
catch (exception $e) {
//code to handle the exception
}
finally {
//optional code that always runs
}
PHP error handling keywords
The following keywords are used for PHP exception handling.
 Try: The try block contains the code that may potentially throw an exception. All of the code
within the try block is executed until an exception is potentially thrown.
 Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP
runtime will then try to find a catch statement to handle the exception.
 Catch: This block of code will be called only if an exception occurs within the try code block. The
code within your catch statement must handle the exception that was thrown.
 Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be specified
after or instead of catch blocks.
 Code within the finally block will always be executed after the try and catch blocks, regardless of
whether an exception has been thrown, and before normal execution resumes. This is useful for
scenarios like closing a database connection regardless if an exception occurred or not.
PHP try catch with multiple exception types
try {
// run your code here
}
catch (Exception $e) {
echo $e->getMessage();
}
catch (InvalidArgumentException $e)
{
echo $e->getMessage();
}
When to use try catch-finally
Example for try catch-finally:
try {
print "this is our try block n";
throw new Exception();
} catch (Exception $e) {
echo "something went wrong, caught yah! n";
} finally {
print "this part is always executed n";
}
Ad

Recommended

Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Php advance
Php advance
Rattanjeet Singh
 
Php basics
Php basics
sagaroceanic11
 
DIWE - File handling with PHP
DIWE - File handling with PHP
Rasan Samarasinghe
 
Files in php
Files in php
sana mateen
 
PHP Programming and its Applications workshop
PHP Programming and its Applications workshop
S.Mohideen Badhusha
 
Php mysql
Php mysql
Ajit Yadav
 
Php.ppt
Php.ppt
Nidhi mishra
 
Php Tutorial
Php Tutorial
SHARANBAJWA
 
Php mysql
Php mysql
Alebachew Zewdu
 
Unit 1
Unit 1
tamilmozhiyaltamilmo
 
phpwebdev.ppt
phpwebdev.ppt
rawaccess
 
Php Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
slidesharenew1
slidesharenew1
truptitasol
 
My cool new Slideshow!
My cool new Slideshow!
omprakash_bagrao_prdxn
 
Introduction to php basics
Introduction to php basics
baabtra.com - No. 1 supplier of quality freshers
 
php programming.pptx
php programming.pptx
rani marri
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PHP Unit-1 Introduction to PHP
PHP Unit-1 Introduction to PHP
Lariya Minhaz
 
PHP
PHP
sometech
 
Phpwebdevelping
Phpwebdevelping
mohamed ashraf
 
php part 2
php part 2
Shagufta shaheen
 
How to Write the Perfect PHP Script for Your Web Development Class
How to Write the Perfect PHP Script for Your Web Development Class
Emma Jacob
 
Phpwebdev
Phpwebdev
Luv'k Verma
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
Guni Sonow
 
DBMS-Unit-3.0 Functional dependencies.ppt
DBMS-Unit-3.0 Functional dependencies.ppt
BackiyalakshmiVenkat
 
Functional Dependencies in rdbms with examples
Functional Dependencies in rdbms with examples
BackiyalakshmiVenkat
 

More Related Content

Similar to object oriented programming in PHP & Functions (20)

Php Tutorial
Php Tutorial
SHARANBAJWA
 
Php mysql
Php mysql
Alebachew Zewdu
 
Unit 1
Unit 1
tamilmozhiyaltamilmo
 
phpwebdev.ppt
phpwebdev.ppt
rawaccess
 
Php Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
slidesharenew1
slidesharenew1
truptitasol
 
My cool new Slideshow!
My cool new Slideshow!
omprakash_bagrao_prdxn
 
Introduction to php basics
Introduction to php basics
baabtra.com - No. 1 supplier of quality freshers
 
php programming.pptx
php programming.pptx
rani marri
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PHP Unit-1 Introduction to PHP
PHP Unit-1 Introduction to PHP
Lariya Minhaz
 
PHP
PHP
sometech
 
Phpwebdevelping
Phpwebdevelping
mohamed ashraf
 
php part 2
php part 2
Shagufta shaheen
 
How to Write the Perfect PHP Script for Your Web Development Class
How to Write the Perfect PHP Script for Your Web Development Class
Emma Jacob
 
Phpwebdev
Phpwebdev
Luv'k Verma
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
Guni Sonow
 

More from BackiyalakshmiVenkat (10)

DBMS-Unit-3.0 Functional dependencies.ppt
DBMS-Unit-3.0 Functional dependencies.ppt
BackiyalakshmiVenkat
 
Functional Dependencies in rdbms with examples
Functional Dependencies in rdbms with examples
BackiyalakshmiVenkat
 
database models in database management systems
database models in database management systems
BackiyalakshmiVenkat
 
Normalization in rdbms types and examples
Normalization in rdbms types and examples
BackiyalakshmiVenkat
 
introduction to advanced operating systems
introduction to advanced operating systems
BackiyalakshmiVenkat
 
Introduction to Database Management Systems
Introduction to Database Management Systems
BackiyalakshmiVenkat
 
Linked list, Singly link list and its operations
Linked list, Singly link list and its operations
BackiyalakshmiVenkat
 
Linked Lists, Single Linked list and its operations
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
Evlotion of Big Data in Big data vs traditional Business
Evlotion of Big Data in Big data vs traditional Business
BackiyalakshmiVenkat
 
AN ANALYSIS OF THE REASONS FOR NON-PERFORMING ASSETS (NPAs) TO THE STATE BANK...
AN ANALYSIS OF THE REASONS FOR NON-PERFORMING ASSETS (NPAs) TO THE STATE BANK...
BackiyalakshmiVenkat
 
DBMS-Unit-3.0 Functional dependencies.ppt
DBMS-Unit-3.0 Functional dependencies.ppt
BackiyalakshmiVenkat
 
Functional Dependencies in rdbms with examples
Functional Dependencies in rdbms with examples
BackiyalakshmiVenkat
 
database models in database management systems
database models in database management systems
BackiyalakshmiVenkat
 
Normalization in rdbms types and examples
Normalization in rdbms types and examples
BackiyalakshmiVenkat
 
introduction to advanced operating systems
introduction to advanced operating systems
BackiyalakshmiVenkat
 
Introduction to Database Management Systems
Introduction to Database Management Systems
BackiyalakshmiVenkat
 
Linked list, Singly link list and its operations
Linked list, Singly link list and its operations
BackiyalakshmiVenkat
 
Linked Lists, Single Linked list and its operations
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
Evlotion of Big Data in Big data vs traditional Business
Evlotion of Big Data in Big data vs traditional Business
BackiyalakshmiVenkat
 
AN ANALYSIS OF THE REASONS FOR NON-PERFORMING ASSETS (NPAs) TO THE STATE BANK...
AN ANALYSIS OF THE REASONS FOR NON-PERFORMING ASSETS (NPAs) TO THE STATE BANK...
BackiyalakshmiVenkat
 
Ad

Recently uploaded (20)

Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
FIRST DAY HIGH orientation for mapeh subject in grade 10.pptx
FIRST DAY HIGH orientation for mapeh subject in grade 10.pptx
GlysdiEelesor1
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
FIRST DAY HIGH orientation for mapeh subject in grade 10.pptx
FIRST DAY HIGH orientation for mapeh subject in grade 10.pptx
GlysdiEelesor1
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
Ad

object oriented programming in PHP & Functions

  • 1. USING FUNCTIONS IN PHP Functions in PHP are blocks of code designed to perform specific tasks. They enhance code reusability, maintainability, and organization. PHP supports two main types of functions: built-in functions and user-defined functions.
  • 2.  PHP comes with a vast library of built-in functions, which are pre-defined and ready to use. These functions cover a wide range of tasks, including string manipulation, mathematical calculations, and file handling. Examples  strlen(): Returns the length of a string.  array_push(): Adds one or more elements to the end of an array.  var_dump(): Displays structured information about one or more variables. Built-in Functions
  • 3. USER-DEFINED FUNCTIONS User-defined functions allow you to create your own functions tailored to your specific needs. function functionName($parameter1, $parameter2) { // code to be executed } function sample($name) { echo "Hello, $name!"; } // Calling the function sample("Abc"); Syntax Example
  • 4. FUNCTION PARAMETERS Functions can accept parameters, which are variables passed into the function. You can define multiple parameters, separated by commas. function add($a, $b) { return $a + $b; } $result = add(5, 10); echo "The sum is: $result"; // Outputs: The sum is: 15
  • 5. DEFAULT PARAMETER VALUES You can set default values for parameters. If a value is not provided during the function call, the default value will be used. function greet($name = "Guest") { echo "Hello, $name!"; } greet(); // Outputs: Hello, Guest! greet("Bob"); // Outputs: Hello, Bob!
  • 6. RETURNING VALUES Functions can return values using the return statement. Once a return statement is executed, the function stops executing. function square($number) { return $number * $number; } echo "The square of 4 is: " . square(4); // Outputs: The square of 4 is: 16
  • 7. CALL BY VALUE VS. CALL BY REFERENCE By default, PHP passes arguments to functions by value, meaning a copy of the variable is passed. If you want to pass a variable by reference (allowing the function to modify the original variable), you can use the & symbol. function increment(&$value) { $value++; } $num = 5; increment($num); echo $num; // Outputs: 6
  • 8. UNIT - IV PHP and Operating System Managing Files USING FTP in PHP Steps to manage files via FTP in PHP  Connect to an FTP Server  Upload a File  Download a File  Delete a File  List Files in a Directory  Change Directory  Create a Directory  Close the FTP Connection
  • 9. <?php $ftp_server = "ftp.example.com"; $ftp_username = "your_username"; $ftp_password = "your_password"; $local_file = "localfile.txt"; $remote_file = "remotefile.txt"; // Establish FTP connection $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server"); // Login to FTP server if (@ftp_login($ftp_conn, $ftp_username, $ftp_password)) { echo "Connected to $ftp_server successfully.n"; // Upload a file if (ftp_put($ftp_conn, $remote_file, $local_file, FTP_BINARY)) { echo "Successfully uploaded $local_file.n"; } else { echo "Error uploading $local_file.n"; } // List files in root directory $file_list = ftp_nlist($ftp_conn, "/"); if ($file_list) { echo "Files in root directory:n"; foreach ($file_list as $file) { echo "$filen"; } } // Close connection ftp_close($ftp_conn); } else { echo "Could not log in to $ftp_server."; } ?>
  • 10. Reading and Writing Files in PHP Writing to a File  To write to a file in PHP, you can use the fwrite( ) function, which writes content to an open file.  To open a file, use the fopen( ) function. <?php $filename = "example.txt"; $content = "Hello, this is a sample text."; // Open the file for writing (creates the file if it doesn't exist) $file = fopen($filename, "w"); // Write content to the file if (fwrite($file, $content)) { echo "File written successfully."; } else { echo "Error writing to the file."; } // Close the file fclose($file); ?>
  • 11. File Modes •"w": Write-only. Opens and clears the file content (if the file exists) or creates a new file. •"w+": Read and write. Clears the file content or creates a new one. •"a": Write-only. Opens and writes to the end of the file (append mode). •"a+": Read and write. Writes to the end of the file. •"r": Read-only. Opens the file for reading. Fails if the file does not exist. •"r+": Read and write. Does not clear the file content.
  • 12. Reading from a File  To read content from a file, you can use the fread() function,  For smaller files, file_get_contents() can be used, which reads the entire file into a string. Reading with file_get_contents() <?php $filename = "example.txt"; // Read entire file content $content = file_get_contents($filename); if ($content !== false) { echo "File content:n$content"; } else { echo "Error reading the file."; } ?>
  • 13. Steps to Read a File Using fread() <?php $filename = "example.txt"; // Open the file for reading $file = fopen($filename, "r"); // Read file content if ($file) { $filesize = filesize($filename); $content = fread($file, $filesize); echo "File content:n$content"; } else { echo "Error opening the file."; } // Close the file fclose($file); ?>
  • 14.  fopen() Opens a file.  fwrite() Writes data to a file.  fread() Reads data from a file.  file_get_contents() Reads entire file content.  fgets() Reads a line from a file.  file_exists() Checks if a file exists.  unlink() Deletes a file.  chmod() Changes file permissions.  move_uploaded_file() Handles file uploads Common PHP File Functions
  • 15. DEVELOPING OBJECT-ORIENTED SCRIPT USING PHP create reusable and modular code by organizing it into objects. Let's go over the basic structure for creating an object-oriented script in PHP.  Classes: Blueprint for creating objects. Classes define properties (variables) and methods (functions) that can be used by the objects created from the class.  Objects: Instances of a class.  Properties: Variables within a class.  Methods: Functions defined inside a class that can
  • 16. <?php // Define a class class Car { // Properties public $make; public $model; public $year; // Constructor (automatically called when an object is created) public function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $this->year = $year; } // Method public function getCarInfo() { return "Car: " . $this->make . " " . $this->model . " (" . $this->year . ")"; } // Setter method public function setYear($year) { $this->year = $year; } // Getter method public function getYear() { return $this->year; } } // Create an object (instance of the Car class) $myCar = new Car("Toyota", "Corolla", 2020); // Accessing a method echo $myCar->getCarInfo(); //Output: Car: Toyota Corolla (2020) // Changing the year using a setter method $myCar->setYear(2022); // Accessing the updated value echo $myCar->getCarInfo(); ?> Output: Car: Toyota Corolla (2022)
  • 17. ($make, $model, and $year) and methods (getCarInfo, setYear, getYear).  Constructor: The __construct() method initializes an object when it is created. Here, it sets the car’s make, model, and year. Methods  getCarInfo() is a method that returns a string with the car’s details.  setYear() and getYear() are setter and getter methods to update and retrieve the value of the year property.  Object Instantiation: $myCar = new Car("Toyota", "Corolla", 2020); creates a new object of the Car class, passing initial values.  Accessing Methods and Properties: $myCar->getCarInfo(); accesses the object’s method, and $myCar->setYear(2022);
  • 18. EXCEPTION HANDLING  Exception handling is a mechanism in programming that allows a system to handle unexpected events or errors that occur during the execution of a program.  These unexpected events, known as exceptions, can disrupt the normal flow of an application.  Exception handling provides a controlled way to respond to these exceptions, allowing the program to either correct the issue or gracefully terminate. Why Do We Need Exception Handling? 1.Maintaining Application Flow: Without exception handling, an unexpected error could terminate the program abruptly. Exception handling ensures that the program can continue running or terminate gracefully. 2.Informative Feedback: When an exception occurs, it provides valuable information about the problem, helping developers to debug and users to understand the issue. 3.Resource Management: Exception handling can ensure that resources like database connections or open files are closed properly even if an error occurs. 4.Enhanced Control: It allows developers to specify how the program should respond to specific types of errors.
  • 19. Here is an example of a basic PHP try catch statement. try { // run your code here } catch (exception $e) { //code to handle the exception } finally { //optional code that always runs }
  • 20. PHP error handling keywords The following keywords are used for PHP exception handling.  Try: The try block contains the code that may potentially throw an exception. All of the code within the try block is executed until an exception is potentially thrown.  Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP runtime will then try to find a catch statement to handle the exception.  Catch: This block of code will be called only if an exception occurs within the try code block. The code within your catch statement must handle the exception that was thrown.  Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be specified after or instead of catch blocks.  Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes. This is useful for scenarios like closing a database connection regardless if an exception occurred or not.
  • 21. PHP try catch with multiple exception types try { // run your code here } catch (Exception $e) { echo $e->getMessage(); } catch (InvalidArgumentException $e) { echo $e->getMessage(); }
  • 22. When to use try catch-finally Example for try catch-finally: try { print "this is our try block n"; throw new Exception(); } catch (Exception $e) { echo "something went wrong, caught yah! n"; } finally { print "this part is always executed n"; }