Category Archives: php

PHP Headers

In PHP HTTP HEADER are some extra information passed to browser such as type of program making the request, date requested, should it be displayed as a HTML document, how long the document is, and a lot more besides. One of the things HTTP HEADER also does is to give status information.

Some of the basic uses of HTTP HEADER are:

  • Redirect Page
  • Send content types
  • Tell the browser to not cache some pages

Note:- Headers are preferred to be the first one to be sent to the browser. That is only when it can work properly.

Location Header

This will send a new location to the browser and it will immediately redirect.

It’s recommended to put a full url there, however almost all browsers support relative urls.

Content Type Header

You can also control the content type using the header that the browser will treat the document as:

You can also force the browser to display the download prompt and have a recommended file name for the download.

You can also send specific errors to the browser using the header function. It’s important to remember the different error messages and what they mean.

You can prevent the browser to cache pages by using the following code:

The above code will let the browser load the page fresh from the server every time it is called. The reason is simple, we tell the browser that the content just expired and it was just last modified too. Furthermore we also tell it Pragma: no-cache to make sure it gets a fresh server copy each time.

PHP Coding Standard

There are few points need to be followed while coding in PHP.

  • Proper Indenting and line space
  • Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.
  • You are strongly encouraged to always use curly braces even in situations where they are technically optional.
  • Code should be properly commented using C style comments (/* */) and standard C++ comments (//) are both fine. Its increase the readability.
  • Always use <?php ?> to delimit PHP code, not the <? ?> shorthand.
  • There should be only one statement per line unless it will create a mess.
  • Block of declarations should be aligned.
  • Proper Identifier naming convention is necessary.

PHP File Uploading

PHP built in support for you to upload files using a HTML form from your web page directly to the server. There are few things that need to do to make it working – page with web form, uploading script, folder on your server with permission set to be able to write in it.

The most important about the form is that you should make it uses POST and not GET method and also you should use enctype=”multipart/form-data” so it knows that a file will be transferred.
Now we need to make a folder (names ‘uploads’) on our web server and set its permissions to 777 so the upload.php script that we will do is able to write the file in it.

Code for “upload.php”

Now, I will explain what the above code do. When, a file is uploaded it is first given a temp filename and then put in the temp folder of your web server. That temp filename is accessible using the global $_FILES array variable. On our web form we have our browse field named “filename” (<input type=”file” name=”filename” />), so the name of that temp file is:

The real name of the file being uploaded is stored in another variable called $_FILES[‘filename’][‘name’]. As you can see this just another array element named “name” in the $_FILES[‘filename’] array.

Now after having that file upload in our web server temp folder we need to move it to the folder specified $folder=“uploads”. This is done using the move_uploaded_file() function.

the first parameter that it takes is the temp filename and the second parameter is the destination folder and filename. If it successfully moves the temp file to the folder that we want it returns TRUE and we made it print “File uploaded” message on the screen.

PHP Sending Emails

The PHP mail() Function

The PHP mail() function is used to send emails from inside a script.

Syntax:

to The recipient’s email address.Multiple recipients can be specified.
subject The email’s subject line.
message The email body(Original Message).
headers Additional header fields such as “From”, “Cc”, “Bcc” etc.
parameters Any additional parameters.

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

Mail() In Action

 

PHP Sessions

PHP Sessions are information passing mechanism that allows to make data accessible across the various pages of an entire website using the super global array.PHP session allows us to keep track of visitor across website.The main difference between a cookie and a session is that a cookie is stored on client’s computer while session variables stores on the server.

Before using session you need to start the session and as the session starts it creats unique id (UID) for each visitor and store variables based on this UID this ID can be accessed using “PHPSESSID”.

Starting a PHP Session

Note: The session_start() function must appear BEFORE the <html> tag

Define Session Variable

Reading Session Variable

Destroying a Session

 

PHP Cookies

PHP Cookies enables the web programmer to store information about the site visitor on the client computer and can be retrieve again to track the visitor. PHP Cookies are stored in text files.

Creating PHP Cookies:

Cookies can be created using the setcookie() function. The syntax is as follows:

Param Description
name Name of the cookie.
value Value of the cookie.
expiration Time when this cookie will expire. Unix timestamp is used here.

Example:

Retrieve Cookies:

Cookies can be retrieved using the $_COOKIE or the $_HTTP_COOKIE_VARS arrays.

Delete Cookies:

To delete a cookie from a client computer, simply use the setcookie() function and set the expiration time as a time in the past.

 

PHP Functions

PHP functions are block of code defined to perform a specific task. PHP functions are like other programming languages. A function is a block of code which can takes one more input in the form of arguments and perform some processing and may or may not returns a value.

Syntax for Creating function in PHP :

Example1:

Example2:

Function with one parameter

Example2:
Function with parameter with default value

 

PHP Files

PHP has the built in support and wide range of functions to perform file IO operations like –

  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

Reading a file in PHP

fopen() function is used to open a file. It requires two parameters first the file name and then mode in which to open.

r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

So here are the steps required to read a file with PHP.

  • Open a file using fopen() function.
  • Get the file’s length using filesize() function.
  • Read the file’s content using fread() function.
  • Close the file with fclose() function.

Example:

 

Writing a file in PHP

A new file can be created or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written.

Example:

 

PHP File Inclusion

In PHP, you can call the content of one PHP Script into another PHP Script using PHP File Inclusion Mechanism.The include and require statements are used to insert script written in other files.

include and require are same in functionality, but:

  • require will produce a fatal error and stop the script.
  • include will only produce a warning and the script will continue.

The include() Function

The require() Function

 

PHP GET & POST

PHP GET & POST are information passing mechanism. PHP GET & POST methods are used to submit or pass form data to the web server. Information is encoded using the Url Encoding method in which key/value pairs are joined with equal signs and different pairs are separated by the ampersand, spaces are removed and replaced with the + character and other non-alphanumeric characters are replaced with a its hexadecimal values.

The GET Method

The GET method appends the encoded user information to the query string. The page and the encoded information are separated by the ? character.All variable names and values are visible in URL.
Note: This method should not be used when submitting sensitive information!
GET method allows bookmark the page. This can be useful in some cases like search.The get method is not suitable for very large variable values. It s length should not exceed 1024 characters.

The PHP provides $_GET super global array to access information sent using GET method.

The POST Method

The POST method transfers encoded form information via HTTP headers to the web server.Information sent from a form by the POST method is more secured and has no restriction over the amount of information to be passed.

The PHP provides $_POST super global array to access information sent using POST method.

The $_REQUEST variable

PHP $_REQUEST variable can be used to access the contents of both $_GET, $_POST at same time.

PHP Strings

PHP Strings variable represents sequences of characters, like “Hello World”. String variable can be any length.PHP String can include escape sequence and are replaced with corresponding character.

PHP Escape Sequence

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \” is replaced by a single double-quote (“)
  • \\ is replaced by a single backslash (\)

Examples of string:

Singly quoted strings are treated and will display things almost completely “as is.” Variables and most escape sequences will not be interpreted whereas doubly quoted strings are interpreted before output.

The String Concatenation Operator in PHP

The concatenation operator (.) is used to bind two string values together.

The strlen() function

The strlen() function is used to find the length of a string.

Triming String in PHP

Function Description
trim() Removes whitespace at beginning and end of a string.
ltrim() Removes whitespace at the beginning of a string.
rtrim() Removes whitespace at the end of a string.

Presenting String in PHP

Function Description
htmlentities() Escapes all HTML entities.
nl2br() Inserts a <br /> tag before each newline character in a string.
strtoupper() Converts a string to uppercase.
strtolower() Converts a string to lowercase.
ucfirst() Converts the first character of a string to uppercase.
ucwords() Converts the first character of each word in a string to uppercase.

String Array Conversion

Function Description
explode() Splits a string into an array on a specified character or group of characters.
implode() Converts an array into a string, placing a specified character or group of characters between each array element.
join() Same as implode().

Substring – substr() function in PHP

Function Description
substr(str,pos) Returns the substring from the character in position pos to the end of the string.
substr(str,-len) Returns the substring from len characters from the end of the string to the end of the string.
substr(str,pos,len) Returns a len length substring beginning with the character in position pos.
substr(str,pos,-len) Returns a substring beginning with the character in position pos and chopping off the last len characters of the string.
strstr(haystack,needle,before_needle) If the third argument (before_needle) is false (default), then it returns the part of the haystack from the needle on.

If the third argument (before_needle) is true, then it returns the part of the haystack before the needle.

The needle can be a string or an integer (or a number that can be converted to an integer).

stristr(haystack,needle,before_needle) Same as strstr(), but case insensitive.
strpos(haystack,needle) Finds the position of the first occurrence of a specified needle in a haystack (string).

The needle can be a string or an integer (or a number that can be converted to an integer).

strrpos(haystack,needle) Finds the position of the last occurrence of a specified needle in a haystack (string).

The needle can be a string or an integer (or a number that can be converted to an integer).

str_replace() Replaces all occurrences of one string with another string.

String Comparison – strcmp() function in PHP

Function Description
strcmp() Compares two strings. Returns < 0 if str1 is less than str2, > 0 if str1 is greater than str2, and 0 if they are equal.
strcasecmp() Like strcmp() but case insensitive.

PHP Arrays

PHP array is a series of elements of the similar type placed in contiguous memory locations that can be accessed individually by adding an index to a unique identifier. An array is made up of a key and a value pair, and the key points to the value.

There are three types of arrays: Indexed array ,Associative array and Multidimensional array.

Indexed Array in PHP

In an indexed array, the keys on index are numeric and starts with 0.

Associative Array in PHP

in associative array, the keys are not necessarily numeric, they are similar to Index arrays in functionality but they are different in terms of their indexing. In associative array indexing is string based.

Multidimensional Array in PHP

Multidimensional arrays can be described as “arrays of arrays”.Multidimensional arrays are not limited to two indices . They can contain as many indices as needed. The amount of memory needed for an array rapidly increases for each dimension.