PHP- Introduction
- PHP -> acronym for "PHP: Hypertext Preprocessor"
- Server Side Scripting Language (Difference Between Scripting and Programming Language https://www.geeksforgeeks.org/whats-the-difference-between-scripting-and-programming-languages/)
- PHP files(.php) can contain text, HTML, CSS, JavaScript, and PHP code. PHP code is executed on the server, and the result is returned to the browser as plain HTML
- Main applications of PHP
- It is used for creating dynamic web pages
- Modify content in database
- handle files on server(Open, read, write, delete)
- Encrypt data
- Syntax- PHP code is enclosed in <?php ?> tag
- Variables are defined by $
$x = 'abc';
- HTML inside PHP
<?php
$name = "abc";
echo "<div>Name is $name</div>";
?>
- Datatypes
- String
- Integer
- Float (floating point numbers - also called double)
- Boolean
- Array
- Object
- NULL
- Resource
- var_dump($x); is used to find datatype of the variable
- echo, concatenation, Die, header function
- echo, print-> These is used to print the output
$abc = 'xyz';
echo $abc;
echo($abc);
print $abc;
print($abc);
- To print associative arrays print_r() is used
$abc = ['name'=>'abc', 'age'=>25];
print_r($abc);
- Concatenation -> Join strings using .
$name = 'Abc'
$age = 25;
echo 'Name is '.$name.' and age is'.$age;
- Die -> Print a message and terminate the current script
if(error){
die('Error occured');
echo "abc"; // Not called
}
- Header -> It is used to redirect from one web page to another in PHP.
header('Location:www.google.com');
- Superglobals
- Predefined variables which can be accessed from anywhere i.e there is no scope defined for these variables
- $GLOBALS -> Access global variables
- $_SERVER -> Holds information about headers, paths, and script locations
- $_REQUEST -> Collects data after submitting a form
- $_POST -> Collect data after submitting a form by method = "POST"
- $_GET -> Collect data after submitting a form by method = "GET"
- $_COOKIE
- $_SESSION
- Forms
- Action in the forms refers to the page where the request will be directed after we hit the submit button
<form action='profile.php' method='POST'>
- Request data send to profile.php is associated with the name attribute in input element
<input name='firstname' type='text'> will be send as $_POST['firstname']
- Validation
- 1) Required to check the validation rules for the form fields.
Input email is required and must contain a valid email address(abc@abc.abc)
Input name is required and must contain letters and white spaces only
- preg_match(pattern, string) returns true if pattern matches with the string
preg_match("/^[a-zA-Z ]*$/", $name)
- filter_var validates or sanitize the data
filter_var($email, FILTER_VALIDATE_EMAIL) returns true if email is valid else false
filter_var($email, FILTER_SANITIZE_EMAIL) returns the sanitized data
- empty($_POST['firstname']) and isset() functions can be used to check if variable is empty or not set
- Example->
if(!empty($_POST['email'])){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
- Refer to https://www.sitepoint.com/form-validation-with-php/ , https://www.w3schools.com/PHP/php_form_url_email.asp
- 2) Required to stop any type of Cross-site Scripting attacks. It is a client-side code injection attack. The attacker aims to execute malicious scripts in a web browser by including scripts in the request.
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"> .
An attacker can pass a URL like "http://www.example.com/profile.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E" to create a code like
<form method="post" action="profile.php/"><script>alert('hacked')</script>
- htmlspecialchars convert the predefined characters like "<" (less than) and ">" (greater than) to HTML entities
& (ampersand) becomes &
" (double quote) becomes "
' (single quote) becomes '
< (less than) becomes <
> (greater than) becomes >
- <form method="post" action="profile.php/"><script>alert('hacked')</script>">
- Cookies
- A cookie is a small piece of data sent from a website and stored on the user's computer by the user's web browser while browsing
- setcookie(name, value, expire, path, domain, secure, httponly);
- $_COOKIE[$cookie_name] is used to retrieve Cookies by cookie name
- It can be modified by using setcookie again
- It can be deleted by using expiration date in the past
- Can be used to store user information like user_id, username etc
- Sessions
- A session is a way to store information to be used across multiple pages. It is not stored on user's computer
- A session can be started with <?php session_start(); ?> at the beginning of the page. Before any HTML tag
- It can be created, retrieved and modified by using super global variable $_SESSION
set cookie - > $_SESSION['user_id'] = 1;
Retrive cookie -> echo $_SESSION['user_id'];
Modify cookie -> $_SESSION['user_id'] = 2;
- It can be deleted by session_unset() and session_destroy()
- Database
- Connecting to a database
- connect.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$db = 'mydb'
// Create connection
$conn = new mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
die();
}
?>
- Execute SQL commands using PHP
- profile.php
<?php
include 'connect.php';
$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 DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === FALSE) {
echo "Error creating table: " . $conn->error;
} else {
$query = "SELECT firstname, secondname, email FROM MyGuests";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo 'First Name -> '.$row['firstname'];
echo '<br/>';
echo 'Second Name -> '.$row['secondname'];
echo '<br/>';
echo 'Email -> '.$row['email'];
}
}
_____________________________________________________________
mysqli_fetch_assoc ->
['firstname'=> 'Abc', 'lastname'=>'PQR', 'email'=>'abc@abc.abc']
- AJAX(Asynchronous JavaScript And XML)
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest(); //Used to send request within
// same webserver
xmlhttp.onreadystatechange = function() { // Detects change in state of request
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
// state
// 0 UNSENT, open() has not been called yet.
// 1 OPENED, send() has been called.
// 2 HEADERS_RECEIVED, send() has been called, and headers and
status are available.
// 3 LOADING Downloading; responseText holds partial data.
// 4 DONE, The operation is complete.
xmlhttp.open("GET", "profile.php?q=" + str, true);
xmlhttp.send();
// For POST, request method is POST and data is send through params
// var params = 'name=abc&pass=pqr';
// xmlhttp.open("GET", "profile.php", true);
// xmlhttp.send(params);
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
- Update a web page without reloading the page
- Request data from a server - after the page has loaded
- Receive data from a server - after the page has loaded
- Send data to a server - in the background
- Hashing
- Hashing is the transformation of a string of characters into a usually shorter fixed-length value.
- Salt -> additional input to a one-way function that hashes data.
- Ex-> sha1
- pass = abc
- s = abc."salt";
- sha1(s)