Welcome to the mine useful documentation for daily work on web developer and computer programming. Thanks to PrettyDocs for theme template layout; download it at the page linked in the button below.
Download PrettyDocsPrismJS is used as the syntax highlighter here. You can build your own version via their website should you need to.
Return current Unix timestamp with microseconds. Useful for count execution time.
$start = microtime(true);
while (...){
}
$time_elapsed_sec = microtime(true) - $start;
Prepared Statement to prevent SQL injection.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
User login system tutorial using HTML, PHP, MySql, Session and CSS on which user can log in to the profile page and log out.
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php"); // Redirecting To Profile Page
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName:</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password:</label>
<input id="password" name="password" placeholder="**********" type="password"><br><br>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</body>
</html>
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else{
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "company");
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT username, password from login where username=? AND password=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->fetch()) //fetching the contents of the row {
$_SESSION['login_user'] = $username; // Initializing Session
header("location: profile.php"); // Redirecting To Profile Page
}
mysqli_close($conn); // Closing Connection
}
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "company");
session_start();// Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$query = "SELECT username from login where username = '$user_check'";
$ses_sql = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['username'];
<?php
include('session.php');
if(!isset($_SESSION['login_user'])){
header("location: index.php"); // Redirecting To Home Page
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome: <i><?php echo $login_session; ?></i></b>
<b id="logout"><a href="logout.php">Log Out</a></b>
</div>
</body>
</html>
session_start();
if(session_destroy()) // Destroying All Sessions {
header("Location: index.php"); // Redirecting To Home Page
}
CREATE DATABASE company;
CREATE TABLE login(
id int(10) NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
);
One very important feature of any good membership website is a password reset system because some users are bound to forget their password.
The whole process of implementing such a system can be broken down into 3 main steps. To ease the explanation, let's analyze these steps in terms of the forms that we will present for the user to fill:
In this section we will see how it works the $_FILES superglobal variable which is used as a vector for transferring files from the client to the server.
Before proceeding it is good to remember that inside the php.ini file there are several options that relate to the upload of files to which it is good to pay attention. If you do not have direct access to the php.ini file I remind you that you can view the various settings of your PHP installation using the phpinfo() function.
Below are the affected options:
In addition to these there are other parameters that affect file uploads, namely:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000">
Upload this file: <input name="userfile" type="file"></br>
<input type="submit" value="Send File">
</form>
// Verify that the file has actually been uploaded
if (!isset($_FILES['userfile']) || !is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo 'You have not sent any files...';
exit;
}
// Folder location where to put files uploaded by users
$uploaddir = '/var/www/myupload/';
// Retrieving the temporary path of the file
$userfile_tmp = $_FILES['userfile']['tmp_name'];
/* The $_FILE superglobal variable is an array containing all the information about the uploaded file:
$_FILES['userfile']['name']
$_FILES['userfile']['type']
$_FILES['userfile']['size'] */
// Retrieving the original name of the uploaded file
$userfile_name = $_FILES['userfile']['name'];
// Copy the file from its temporary location to my upload folder
if (move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name)) {
// If the operation was successful...
echo 'File sent successfully.';
}
else {
// If the operation failed...
echo 'Invalid Upload!';
}
Check if the file has been uploaded
if (!isset($_FILES['userfile']) || !is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo 'You have not sent any files...';
exit;
}
Check that the file is not too large
if ($_FILES['userfile']['size'] > 4194304) {
echo 'The file is too big!';
exit;
}
Verify that the upload does not overwrite another file
$target_file = '/var/www/myupload/' . $_FILES['userfile']['name'];
if (file_exists($target_file)) {
echo The file already exists';
exit;
}
Check the extension of the uploaded file
$ext_ok = array('doc', 'docx', 'pdf');
$temp = explode('.', $_FILES['userfile']['name']);
$ext = end($temp);
if (!in_array($ext, $ext_ok)) {
echo 'The file has an unacceptable extension!';
exit;
}
Check if the file is actually an image
$is_img = getimagesize($_FILES['userfile']['tmp_name']);
if (!$is_img) {
echo 'You can only send pictures';
exit;
}
FPDF is a PHP class that allows you to generate PDF files directly from PHP.
FPDF also has other advantages: high-level functions.
Here is a list of its main features:
The scripts section is available and provides some useful extensions.
A full-featured email creation and transfer class for PHP. Check on GitHub.
Many PHP developers need to send email from their code. The only PHP function that supports this directly is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.
The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the mail() function should be avoided when possible; it's both faster and safer to use SMTP to localhost.
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable implicit TLS encryption
$mail->Port = 465; // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
// Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen@example.com'); // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
// Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: {$mail->ErrorInfo}';
}
Simple one line PHP script to find the absolute path of the directory on web server.
<?php echo getcwd(); ?>
JSON is the string notation of JavaScript object. It takes up simple to complex forms and stores data as (key, value) pairs.
This is the example of a json file:
[
{
"Code": "1",
"Name": "June Zupers",
"Sports": "Base Ball"
},
{
"Code": "2",
"Name": "Fred Cortez",
"Sports": "Soccer"
},
{
"Code": "3",
"Name": "Kevin Burks",
"Sports": "Tennis"
}
]
To read json file with php, you must first get the json data stored in the file, decode json and finally parse through the array or object.
For that you'll need two php functions - one is file_get_contents() and the other is json_decode().
// load file
$data = file_get_contents('results.json');
// decode json to associative array
$json_arr = json_decode($data, true);
foreach ($json_arr as $key => $value) {
echo $json_arr[$key] . " - " . $json_arr[$value] . "<br/>";
}
If you know the specific key name, then you can simply access it like this:
echo $json_arr[0]['Code'];
Note: The function json_decode() decodes the given json string into an array or object. For example the statement json_decode($data, true); in above code will return associative array. You can ignore the second parameter 'true' to make it return as an object.
To add additional records to json file you have to simply append it to the end of file. Here let's see an example for adding new data. The following php snippet takes up a json file, decode it, add extra records and again encode to json and save it into a new file.
// read json file
$data = file_get_contents('results.json');
// decode json
$json_arr = json_decode($data, true);
// add data
$json_arr[] = array('Code'=>4, 'Name'=>'Jeff Darwin', 'Sports'=>'Cricket');
// encode json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
As for updating json file you can either modify single value or in bulk. Here's an example for modifying value for a specific json attribute.
// read file
$data = file_get_contents('results.json');
// decode json to array
$json_arr = json_decode($data, true);
foreach ($json_arr as $key => $value) {
if ($value['Code'] == '2') {
$json_arr[$key]['Sports'] = "Foot Ball";
}
}
// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
JSON deletion is little complex since it is easy to mess up doing the process. You must be clear what you need to delete first, a specific key pair from all rows or a complete row.
// read json file
$data = file_get_contents('results.json');
// decode json to associative array
$json_arr = json_decode($data, true);
// get array index to delete
$arr_index = array();
foreach ($json_arr as $key => $value) {
if ($value['Code'] == "2") {
$arr_index[] = $key;
}
}
// delete data
foreach ($arr_index as $i) {
unset($json_arr[$i]);
}
// rebase array
$json_arr = array_values($json_arr);
// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
The deletion script uses two foreach loops. The first one is for determining the array index we need to delete from json.
And the second is what actually deletes from array using unset() function.
Finally it rebases the array, encode it to json and store it in a new file.