PHP cheat sheet for exams

December 3, 2016 · 61 mins read
Categories:

PHP is one of the most widely used programming language out there.

This might be because of the usability and ease of learning it.

**Php cheatsheet**
// write php code here
?>
The PHP code can be embedded anywhere in the HTML document.
PHP stands for PHP: Hypertext Preprocessor.
Php is open-source and free to download and use.
PHP scripts are executed on the server and resulted markup is displayed on the browser.
PHP file must end with the extension of .php.
**Tasks of PHP**
It generates dynamic content.
It can create, delete and make new files on the server.
Form handling is one of the most important tasks of PHP.
It can work with our database and keep stuff for further examination and use.
It can also be used for the encryption of the data.
**The Installation process**
The process of PHP installation is very easy.
First of all, we need a server, Apache is the best and freely available and fit for every task.
Apache installation is very easy. Use any of the tutorials out their and install the server.
After this install PHP parser, that will execute the PHP code on the server and pushes the result onto the browser.
If someone want to make use of the data entered by the users than it is good option to use a database. MySQL will be a good option.
**Comments**
After so much of experience as a programmer, I have found that comments are the most important thing in the total code.
So almost all the languages have a similar kind of comment but it is good to discuss them before looking toward the code.
/* ... This is multiline comment */
// ... This a single line comment
# ... This is also a single line comment
**Case sensitivity**
Now PHP case sensitivity is something that one should talk about. It is not like most of the programming languages that I have encountered till now.
In PHP variables are case sensitive and rest stuff is not case sensitive.
i.e. we can use ECHO, echo or EcHo for the printing something on the browser, but if the name of the variable is ‘myname’ than we can’t write it as something else. Now this is something awkward. I don’t know why PHP creators did this but I am sure their might be a good reason.
**PHP variables**
PHP variables are very easy to create.
$me = “ranvir”;
$you = “somename”;
$me_age = 21;
?>
Now I want to mention here that semicolon is very important in PHP and cause a very bad and unrecognizable error. So always keep in mind to put the semicolons.
**Rules of naming variables:**
Variables must start with a $ sign.
The variables name must not start with the number.
Underscores can be included in the beginning of the variable name.
**Printing the variable**
Now there are two ways of doing this.Command echo is used to print something on the browser.
echo “my name is $me”;
echo “my name is “ . $me;
?>
It is up to you to choose anyone of them but I prefer the second one because it provides with more clarity.
As we know that we cannot provide the datatype of the variable before declaring it in PHP, that is why PHP is known as **“Loosely typed language”.**
Some other such languages are JavaScript and Python.
**Variable scopes**
The variable named in the starting of the PHP tags are almost global for the whole document.
The variables that are inside a function are called a local variable.
If we place a keyword global before any variable name then it accesses the global variable, even if the function is being executed. PHP also stores all the global variables in an array.
Example:
$x = 10;
function newFunc(){
global $x;
static $y = 20;
echo $x;
echo $GLOBALS[‘x’]; // Both will give the same result.
}
echo $y; // As the variable is static it still exist.
?>
Static variables are not deleted as soon as the execution of the execution of the function is ended. This is needed a sometimes one may want to use the variable further.
**Writing or Printing on the users Browser**
Writing on the browser can be done by using echo or print. Both are same but there is a minor difference.
Echo doesn’t return anything while print does return 1.
Echo is also somewhat faster than print.
Print can be used in the expression for checking successful printing.
Example:
echo “Oh! It’s hot out their.”;
print “It’s okay.”;
print(“No it’s not”);
?>
**Data types in PHP**
String:
$me = “knowledge”;
Integer:
$x = 10;
Float:
Fractional numbers,
$x = 10.9;
Boolean:
True or flase,
$x = true;
Array:
More than one value can be stored,
$x = array(‘you’, ‘it’, ‘me’);
Object:
The variable that stores the value and some additional value related to that value. This allows us to introduce the concept of classes.
class Person() {
// constructor that works whenever a object of this class is made.
function Person() {
$this->name = “Knowledge”;
}
}
// Now create a object and the constructer will work on its own.
$me = new Person();
echo $me->name;
?>
We will see ‘Knowledge’ on the screen.
Null:
While creating a variable if no value is assigned to that variable by the programmer then by default the null value is assigned. Also, we can specifically keep a variable null to assign a new variable afterward.
$x = NULL;
**Strings**
Strings are one of the most used datatypes in any programming languages. Many string operations are very difficult to perform
String data type has many build in functions which can be used to make our work easier. For studying some of these please refer to this link.
[http://www.w3schools.com/php/php_ref_string.asp](http://www.w3schools.com/php/php_ref_string.asp)
****CONSTANTS****
Constants are the variables whose values never change during the execution of the program. Similarly, PHP constants are used for similar purposes.
define keyword is used to declare a constant.
Also, the CONSTANTS are global no matter where they are defined.
SYNTAX:
define(“variable_name”, “Value_of_the_variable”, “case-insensitive( true/false)”);
> > define(“PI”, “3.14”); > echo PI; > ?>
case-insensitive is used if you want to make it case insensitive with string constants.
**Operators**
Arithmetic operators:
These include operators like additions, subtraction, multiplication etc.
Assignment operator:
This includes ‘=’ and ‘+=’, ‘-=’ etc. Operators.
Comparison Operators:
This include operators like ==, ===, <, <= and many more
Increment/Decrement operators:
++, -- are the two basic operators of this category.
Logical Operators:
and, or, not are the operators of this category.
****Conditional Statements****
*
if
*
if-else
*
if-life
*
nested if
*
switch statements
These statements are all similar to the statements in any other language.
****LOOPS****
*
while
*
do while
*
for
*
for each
All other loops are similar but for each is somewhat different.
> > $numbers = array(‘1’, ‘2’, ‘3’, ‘4’); > foreach($number as $value){ > echo ‘$value +
’;
> } > ?> > This will print all the numbers in the array with one value in a line.
****Function********s****
Functions are also similar to other languages.
SYNTAX:
> function functioname(){ > //…. Somestuff > return some_variable; > } > echo functionname();
****Arrays****
There are three types of arrays in PHP.
*
Indexed Array : Accessed using the numbers
$x = array(“me”, ”they”, “we”);
*
Associative Array : Elements are accessed using the programmer given values. These form a set of key and value pairs.
$x = array(“me”=>”knowledge”);
*
Multi-dimensional Array : Similar to matrices.
> echo count($arrayname);
This function will print the total number of elements in an array. That’s it for now. With the provided knowledge you can easily build anything that you want. Think of something that you want to build. If you get any problem ask below.
**Superglobals**
These are the variables that are always accessible no matter what the scope is.
Some of these are:
$GLOBALS:
As already discussed these contain all the global variables.
$_SERVER:
This holds the information of header, state, paths and scripts of a server.
$_REQUEST:
This is used to collect the data when a form is submitted to a particular script.
<form method=”post” action=””>
This means that the form is submitted to the script running on this page only.
$_POST:
This is used to collect the posted data.
$_GET:
This is used to collect data send by the method “GET”.
**FORMS**
Now we are going to talk about the handling form and doing various things with the data received.
A fully working example of form validation and posting.
<!DOCTYPE html>
</span></span></span></div>
</span></span></span></div>
<form method="post" action="">
Name:
*


E-mail:
*


Website:


Comment:


Gender:
Female
Male
*


</form>
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
// if the server receives some data with post request.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
// Now remove the special characters from the data received.
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
**PHP sessions**
Session variables are not stored on the user's computer that is why they are different from the cookies.
These are used to store the information of the user so that it can be used in multiple web pages.
For example, If you log in to a website on your one web page and open another web page of the same browser and found yourself still logged in. This is done with the help of Sessions.
Session stores the information of single user across all the web pages of a variable.
Session variables remain intact until and unless the browser window is not closed. Once closed the session variables are lost.
Content of file session1.php
// Start the session
session_start();
?>
<!DOCTYPE html>
</span></span></div>
</span></span></div>
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Content of second file session2.php
session_start();
?>
<!DOCTYPE html>
</span></span></div>
</span></span></div>
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".
";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
// To print all the information about the session variables use this.
print_r($_SESSION);
// To change the session variables use this.
$_SESSION["favcolor"] = "yellow";
?>
// For deleting session variables use this.
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
**Attaching MySQL database**
MySQL is perfect for our use and can be learned very easily. Also there are many DBMS’s out there that can be used but here we are only going to discuss about MySQL.
Install the MySQL on your computer and we are ready to send the queries to the server.
Now there are two ways of connecting to the MYSQL either we can use MYSQLi or we can use PDO. PDO can make the connection with other 12 databases but Mysqli is only for Mysql.
The syntax of PDO is little difficult so we will concentrate on MySQLi for now.
Install MySQLi into the system.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
// Inserting data
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}
// Selecting data
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
";
}
} else {
echo "0 results";
}
// if you want to close the connection before ending of script use this.
mysqli_close($conn);
?>
**PHP and AJAX together.**
</span></span></div>
</span></span></div>
</head>
</span></span></div>
Start typing a name in the input field below:

</span></span></div>
First name:
</form>
Suggestions:

// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
</body>
</html>
</div>
Please share your Feedback:

Did you enjoy reading or think it can be improved? Don’t forget to leave your thoughts in the comments section below! If you liked this article, please share it with your friends, and read a few more!

We don't share your details with others