PHP Help [Explained With Code Examples]

This post provides PHP Help (with example code) for both beginners and advanced web developers. You can always refer to this post whenever you want to know about any PHP functions, PHP variables, or anything else related to PHP.

Every function and variable in this post is explained with an example PHP code that will help you understand everything easily. PHP is still the major language used for WordPress Theme Development.

PHP is a very easy-to-learn programming language. It’s almost impossible to get “lost in the woods” when learning PHP. On the other hand, PHP is dynamic. This means that your website can respond to changes in the information on your web server with almost no effort on your part.

In addition, this post explains many of the basic concepts you must know in order to write “clean” and efficient code.

What is include() Function?

include() function is the recommended function for adding other PHP files in the current PHP file. Because, even if the included file has an error, your page will still be visible to the user, including the error message from the included file.
Example: <?php include ‘myfile.php’; ?>

What is include_once() Function?

include_once() function is good because it avoids the duplication of including the same PHP file twice or more on the same page.
Example<?php include_once ‘myfile.php’; ?>

What is require() Function?

require() function works the same as to include() function but if a file added with require() function gives an error then the whole page will not display until the error is cleared.
Example: <?php require ‘myfile.php’; ?>

What is require_once() Function?

require_once() function is good because it avoids the duplication of including the same PHP file twice or more on the same page.
Example: <?php require_once ‘myfile.php’; ?>

What is $_GET?

$_GET[] is a superglobal variable. This Super Global Variable is used to receive form data from one file to another file. It works with the method = “get” type of form submission. The data being submitted can be seen in the browser’s address bar. That means, whatever you are submitting in the form, is visible to everyone in the address bar.

Not a good option, if you want to submit your form data secretly or securely.

Example: $var = $_GET[“element_data_from_other_file”];

What is $_POST?

$_POST[] is a superglobal variable. This Super Global Variable is used to receive form data from one file to another file. It works with the method = “post” type of form submission.
The data being submitted can not be seen in the browser’s address bar (like it can be seen with the $_GET variable.
Therefore, the $_POST variable is a secure and safe way of submitting sensitive data from one file to another file using a form.

Example: $var = $_POST[“element_data_from_other_file”];

What is $_REQUEST?

$_REQUEST[] is a superglobal variable. This Super Global Variable is used to receive form data. It works with both types of form submission methods i.e method = “get” and method = “post”.

Example: $var = $_REQUEST[“element_data_from_other_file”];

What is $_SERVER?

$_SERVER[] is a superglobal variable. This variable is used to retrieve server-related information like HTTP connection info, file structure info, port info, host info, hence all the information that is coming with the URL. It is also used to submit the form data to the database while staying on the same form page and also printing the response on the same page.

Example: echo $_SERVER[‘PHP_SELF’];
This command will print the path of the current PHP file, in which this variable is called. This is one of the many key values that can be used with the $_SERVER superglobal variable.

Another example:
<form action=”<?php echo $_SERVER[‘PHP_SELF’] ?>” method=”post”>
The above line shows how you can perform the form submit action within the same PHP file. And at the end of the </form> tag, you can paste the following code to retrieve and print the form values, on the same form page.

<?php
if( isset( $_POST[ ‘submit’ ] ) ) {
echo $_POST[ ‘form_value_1’ ] . “<br/>”;
echo $_POST[ ‘form_value_2’ ] . “<br/>”;
}
?>
The above code will print the given two values from the form, on the same form page.

What is $_COOKIE?

$_COOKIE is a superglobal variable. $_COOKIE variable is used to store user information and save it in the user’s web browser.
There are two steps to set up a cookie: (PHP Cookies)

For creating the cookie:
setcookie( cookie_name, cookie_value, cookie_expiry_time, path, domain, is_secure, httponly );

For viewing the cookie:
$_COOKIE[‘cookie_name’];

IMPORTANT: If the browser doesn’t allow to save cookies, then you can’t save or retrieve cookies! In that case, you’ll receive an error. Therefore, to avoid errors, you should always check that if the cookie is set or not, by using the isset() function.

What is $_SESSION?

$_SESSION[] is a superglobal variable. $_SESSION variable is used to save the user information on the server (not on the visitor’s computer, like in $_COOKIE variable.) $_SESSION variable information is stored on the server in a ‘Session Store‘ which is temporary storage.

If you want to store the information permanently on the server, then you’ll have to use the databases (MySQL, etc) to store the information. You can store and also get the session information easily from your database.

Mostly, the $_SESSION variable is used on login pages. The session starts when the user logs in to the website and the session ends when the user logs out of the website (normally).

For example, when you log in to a website and while surfing the website you continuously keep seeing your username at top of the website, showing that you are logged in to the website. This is done with the help of the $_SESSION variable!

There are three steps for creating a session:

Step-1. session_start(); //starting the session. Keep in mind that whenever you’ll start anything related to the session on any new page, you must use this statement at top of the PHP file and then do whatever you want to do with the session data. If this statement is not used, your session won’t work on the new webpage.

Step-2. $_SESSION[name] = value; //creating the session. the ‘name’ in the session works as a session ID and we’ll assign a value to this name (please see the example for details). You have to create the session only once, you don’t have to use this statement, again and again, to show the session details on other pages of your website.

Step-3. echo $_SESSION[name]; // For accessing the session details on any page, you should use this statement.

When the user leaves the website (logs out) you can delete the session with the following two steps:

Step-1. session_unset(); // It is a PHP function used to remove all the session variables which were created for the session.

Step-2. session_destroy(); // You cannot destroy a session without UnSetting the session first. This will destroy the session completely, from the server.

Example:
<?php
session_start();
$_SESSION[“UserName”] = “Yaaver”;
echo “Session variable is set!”;
print_r($_SESSION); // If you want to see complete session data, then print the session array with the help of this statement.
?>

You can access the above session variable in your HTML code as well, in the following way:
<?php
if ( isset( $_SESSION[ “UserName” ] ) ) {
echo “Current User: ” . $_SESSION[ “UserName” ];
} else {
echo “No active session found.”;
}
?>

The above line of code will display the value “Yaaver” which you have stored at the start of the session.
Even if you’ll come after a few days and access the page, you’ll see this session value. Because you haven’t destroyed/deleted the session yet.

The following example can be used to delete/destroy the current session:
<?php
session_start(); // Accessing the current session.
session_unset(); // Removing all the values of current session, otherwise we won’t be able to destroy the session.
session_destroy(); // Session is destroyed now!
echo “Session is destroyed!”;
?>

What is $_FILES?

$_FILES[] is a superglobal variable. $_FILES variable is used to submit a file or upload a file to the server (website) via a form or any file upload method.

For example, when you upload a CV to any website by submitting a form, the $_FILES variable is the method that uploads your CV file to the website’s server.

Here is the HTML code which can be used in the form for uploading any document/file to the server/database of your website:
<input type=”file” name=”myFile” />

We can use this statement $_FILES[“myFile”]; to upload the file from the above HTML code to the server.

This FILES array will return us four types of values, which are:
{
name, // The name of the uploaded file.
size, // The size of the uploaded file (in KBs(default)/MBs/GBs/etc). You can also define the limit of file_size here so that the user should not be able to upload a file greater than the given file size.
temp_name, // This is the temporary filename. The server always uses this temporary filename for uploading the file on the server.
type // Define the type of files, which are allowed to be uploaded on the server.
}

Once we have received all the information through the above statement, then we have to use a PHP function move_uploaded_file(file, dest);. This function uploaded the file from the client-side to the server-side.

The first parameter ‘file’ is used to mention  temp_namethat we have defined in the $_FILES variable array.

The second parameter ‘dest’ is used to mention the destination location (folder) on the server, where you want to upload the file.

Whenever you use the HTML input type=”file” for a form, you must have to write this enctype=”multipart/form-data” in the <form> tag.

Example:
<?php
if ( isset( $_FILES[ ‘myFile’ ] ) ) {
    echo “<pre>”;
print_r( $_FILES ); // Until this statement file is not uploaded but you can see the parsed data in the form of array. You can delete this statement if not needed or can comment it.
    echo “</pre>”;
    $file_name      = $_FILES[ ‘myFile’ ][ ‘name’ ]; // Saving the ‘name’ of file in file_name variable.
    $file_size      = $_FILES[ ‘myFile’ ][ ‘size’ ]; // Saving the file size in file_size variable.
    $file_temp_name = $_FILES[ ‘myFile’ ][ ‘tmp_name’ ]; // Saving the temporary file name in file_temp_name variable.
    $file_type      = $_FILES[ ‘myFile’ ][ ‘type’ ]; // Saving file type in file_type variable.
    if ( move_uploaded_file( $file_temp_name, “uploads/” . $file_name ) ) { // Uploading the file to ‘uplaods’ folder on the server.
        echo “File is successfully uploaded.”;
    } else {
        echo “File is not uploaded.”;
    } } ?>

<html>
<body>
<form action=”” method=”POST” enctype=”multipart/form-data”>
<input type=”file” name=”myFile” />
<br/>
<input type=”submit” />
</form>
</body>
</html>

What is die() and exit()?

die() function and exit() function both have same purpose in PHP coding. The main purpose of both of these functions is to stop the code execution flow.

The benefit of using this function is that if we are getting some error on any line and we are not able to understand that the error is exactly on which line. In that case, we use the die() or exit() function after every line, one by one, to trace the error line.

You can also print a message with these functions as exit(“Error!”);

Example:
<?php
echo “Message-1”;
echo “Message-2”;
echo “Message-3”;
die(); // You can replace it with exit(); as well.
echo “Message-4”;
echo “Message-5”;
?>

In this example, the code will execute until Message-3 and then it will stop and exit (or die) without executing the next two lines.

How to create SQL Table? (MySQL)

Use this command for creating the table:
CREATE TABLE Table_name(
column1 datatype,
column1 datatype,
column1 datatype,

);

In the above statement:
Replace Table_name with any name that you want to write for your table (without spaces).
Replace column1, column2, column3 with your required column names (without spaces). You can add as many columns as you want, in the same manner. Just make sure not to add a comma at the end of the last column, as we don’t add a comma in the last item of any PHP array.
Replace datatype with the type of data that you want to save in the respective column. (see MySQL Data Types)

What is the MySQL Data Types?

There are three categories of SQL Data Types for MySQL which are listed in detail as follow:

1- String: (has 14 data types)
01- CHAR(size) (allowed length: 0-255 characters)
02- VARCHAR(size) (allowed length: 0-65535 characters)
03- BINARY(size) (allowed length: 0-255 bytes)
04- VARBINARY(size) (allowed length: 0-65535 bytes “for MySQL 5.0.3 and above”)
05- TINEYTEXT (allowed length: FIXED 255 characters)
06- TEXT(size) (allowed length: 65535 bytes)
07- MEDIUMTEXT (allowed length: FIXED 16777215 characters)
08- LONGTEXT (allowed length: FIXED 4294967295 characters)
09- TINYBLOB (allowed length: FIXED 255 bytes)
10- BLOB(size) (allowed length: FIXED 65535 bytes)
11- MEDIUMBLOB (allowed length: FIXED 16777215 bytes)
12- LONGBLOB (allowed length: FIXED 4294967295 bytes)
13- ENUM(val1, val2, val3, …) (allowed length for this list: up to 65535 values)
14- SET(val1, val2, val3, …) (allowed length for this list: up to 64 values)

2- Numeric: (has 13 data types)
01- BIT(size) (allowed length: 1 to 64 values)
02- TINYINT(size) (allowed length: -128 to 127 values)
03- INT(size) (allowed length: -2147483648 to 2147483647 values)
04- INTEGER(size) (allowed length: -2147483648 to 2147483647 values)
05- SMALLINT(size) (allowed length: -32768 to 32767 values)
06- MEDIUMINT(size) (allowed length: -8388608 to 8388607 values)
07- BIGINT(size) (allowed length: -9223372036854775808 to 9223372036854775807 values)
08- BOOL (allowed length: 0 or 1 value)
09- BOOLEAN (allowed length: 0 or 1 value)
10- FLOAT(p) (allowed length: 255.568 values “both sides of decimal will have equal values in it”)
11- DOUBLE(size, d) (allowed length: 255.568 values “size means left side of decimal and ‘d’ means right side of decimal”)
12- DECIMAL(size, d) (allowed length: size = max 60 values, d = max 30 values)
13- DEC(size, d) (allowed length: size = max 60 values, d = max 30 values)

3- Date and Time: (has 5 data types)
01- DATE (allowed length: ‘1000-01-01’ to ‘9999-12-31’ (Format: ‘YYYY-MM-DD’)
02- DATETIME(fsp) (allowed length: ‘1000-01-01 to 9999-12-31′ ’00:00:00 to 23:59:59’ (Format: ‘YYYY-MM-DD hh:mm:ss’)
03- TIMESTAMP(fsp) (allowed length: (‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC) (Format: ‘YYYY-MM-DD hh:mm:ss’)
04- TIME(fsp) (allowed length: ‘-838:59:59’ to ‘838:59:59’) (Format: ‘hh:mm:ss’ or ‘hhh:mm:ss’)
05- YEAR (allowed length: 1901 to 2155, and also 0000 “it has even more ranges, see here.”) (Format: YYYY)

How to insert data in MySQL Table?

Syntax for inserting data in MySQL table:
INSERT INTO table_name (column1, column2, column3, …)
VALUES (value1, value2, value3, …)

Example:
INSERT INTO my_table (id, name, phone, gender)
VALUES (1, “Yaaver”, “123456789”, “M”);

How to insert multiple rows using a single command in MySQL Table/Database?

Syntax for inserting/adding multiple rows of data in MySQL table/database:
INSERT INTO table_name (column1, column2, column3, …)
VALUES
(value1, value2, value3, …),
(value1, value2, value3, …),
(value1, value2, value3, …);

Example:
INSERT INTO my_table (id, name, phone, gender)
VALUES (1, “Joey Tribbiani”, “123456789”, “M”),

VALUES (2, “Janice OMG”, “321456789”, “F”),
VALUES (3, “Mona Darling”, “911456789”, “F”);

Also, don’t forget to check out my list of Freelancing Resources.

Share This Page:

Leave a Comment

Your email address will not be published.