PHP Functions



PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you:
  • Creating a PHP Function
  • Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.
Creating PHP Function:
Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called write Message () and then calls it just after creating it.
Note that while creating a function its name should start with keyword functionand all the PHP code should be put inside { and } braces as shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>

<?php
/* Defining a PHP Function */
function writeMessage()
{
  echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result:
You are really a nice person, Have a nice time!
PHP Functions with Parameters:
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two numbers is : 30
Passing Arguments by Reference:
It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
   $num += 5;
}

function addSix(&$num)
{
   $num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result:
Original Value is 15
Original Value is 21
PHP Functions retruning value:
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>
This will display following result:
Returned value from the function : 30
Setting Default Values for Function Parameters:
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function printMe($param = NULL)
{
   print $param;
}
printMe("This is test");
printMe();
?>

</body>
</html>
This will produce following result:
This is test
Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
   echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
This will display following result:
Hello

Proxy Class


/**
* Wrapper around Zend_Db connection that performs logging
*/
class Zend_Db_LogWrapper {
private $conn;
private $logger;

public function __construct($conn, $logFilename) {
$this->conn = $conn;
$this->logger = new Logger($logFilename);
}

public function insert($table, array $bind) {
$this->logger->logDb($table, 'insert', $bind);
return $this->conn->insert($table, $bind);
}

public function update($table, array $bind, $where = '') {
$this->logger->logDb($table, 'update', $bind, $where);
return $this->conn->update($table, $bind, $where);
}

public function delete($table, $where = '') {
$this->logger->logDb($table, 'delete', '', $where);
return $this->conn->delete($table, $where);
}

/**
* Redirect all other calls to the wrapped connection
*/
public function __call($name, $arguments) {
return call_user_func_array(array($this->conn, $name), $arguments);
}
}

Why you must do it

I create this blog to every body who want learn about web programming PHP. But I don't tell what is PHP and the basic. In this blog, I assume that you had been familiar with PHP.

I just wanna share about tips and tricks in PHP programming. Why? Only one reason to answer. Make a light and more faster programming.

So, let's enjoy it. I hope this blog give you more beneficial at your web programming using PHP.

Resources

PHP includes free and open source libraries with the core build. PHP is a fundamentally Internet-aware system with modules built in for accessing FTP servers, many database servers, embedded SQL libraries such as embedded MySQL and SQLite, LDAP servers, and others. Many functions familiar to C programmers such as those in the stdio family are available in the standard PHP build. PHP has traditionally used features such as "magic_quotes_gpc" and "magic_quotes_runtime" which attempt to escape apostrophes (') and quotes (") in strings in the assumption that they will be used in databases, to prevent SQL injection attacks. This leads to confusion over which data is escaped and which is not, and to problems when data is not in fact used as input to a database and when the escaping used is not completely correct. To make code portable between servers which do and do not use magic quotes, developers can preface their code with a script to reverse the effect of magic quotes when it is applied.

PHP allows developers to write extensions in C to add functionality to the PHP language. These can then be compiled into PHP or loaded dynamically at runtime. Extensions have been written to add support for the Windows API, process management on Unix-like operating systems, multibyte strings (Unicode), cURL, and several popular compression formats. Some more unusual features include integration with Internet relay chat, dynamic generation of images and Adobe Flash content, and even speech synthesis. The PHP Extension Community Library (PECL) project is a repository for extensions to the PHP language.

Zend provides a certification program for programmers to become certified PHP developers.

How to configure phpMyAdmin to address Security Issues

This post is based on the instructions found in Murach's PHP and MySQL book, which I am using as a guide in my PHP Journey and I recommend that you do the same. 

The default location of the phpMyAdmin config file is: C:\xampp\phpmyadmin\config.inc.php

  1. Open the config.inc.php file in a text editor.
  2. Search for "$cfg['blowfish_secret'] = 'xampp'".  Replace 'xampp' with a random string of up to 46 characters.  This will be the encryption key.
  3. Search for "$cfg['Servers'][$i]['auth_type']".  Change the value from 'config'  to 'cookie'.
  4. Set the 'user' and 'password' options to empty strings. When you are done, it should look like this:

    $cfg['Servers'][$i]['auth_type']            = 'cookie';
    $cfg['Servers'][$i]['user']                 = '';
    $cfg['Servers'][$i]['password']             = '';
  5. Save your changes.

Now lets check to make sure the changes were made correctly:

  1. Open the XAMPP control panel and start Apache and MySQL.
  2. Click the "Admin" button next to MySQL to open phpMyAdmin.
  3. Log in by specifying "root" as the user.  Leave the password blank, because by default the root user doesn't have a password.
  4. Once you have logged in, you should set a password for the root user.  To do this, click "Change password" Under "Actions". And enter a password. You may want to save this password in a password protected file so that you can retrieve it later if you forget what you set it to.

Now you have successfully configured phpMyAdmin.

PHP tutorial introduction

Here this is your first attempt on PHP web development. You are here, because you want to learn PHP through our PHP tutorial. If you already knew a lot about PHP, this web site may help you in some aspects. But if you have no idea about PHP or if you are trying to learn PHP, then this website will show you the way. Before starting this expedition you have to know the following subject such as HTML & JavaScript. 


Learning PHP is very easy and simple, we hope it will be a funny way. PHP is very simple language by comparing other programming languages. You can learn php from our website easily. I hope you will enjoy our PHP tutorial. We start with written PHP tutorial, at the same time I will try to provide video tutorial as well as PHP pdf tutorial so that you can understand our PHP tutorial easily. I suggest that firstly try to read the whole written php tutorial and then you can go to watch our video tutorial. Also you can download each php tutorial in a pdf format. So now we can start our php tutorial learning mission....... 

Function for checking if file exists and if so returning a random file name

$filename = fileExists(FILE_PATH.$_FILES['photo_file']['name']);

function fileExists($file){
  
    if(!file_exists($file)){
        $path_parts = pathinfo($file);
        $filename = $path_parts['filename'].".".$path_parts['extension'];
        return $filename;
    }else{
        $path_parts = pathinfo($file);
        $filename = rand(100,1000).$path_parts['filename'].".".$path_parts['extension'];
        $file = $path_parts['dirname']."/".$filename;
        return fileExists($file);
    }
}