Split video in multiple parts – PHP & FFmpeg

To split video files in 2 parts or extracting a specific part from a long video is usually done by some of the softwares available on the internet. Some operating systems provides basic editing softwares for free, for example Windows 10 has built-in video editor in their Windows Media Player. Macintosh has QuickTime player and iMovie which came along with operating system for free. If you do not have such editor you can always download from the internet and sometimes you have to pay some amount because some of them are not free. In this tutorial, we will be creating a simple PHP script that will help you to split a video and save the extracted part as a separate video.

Step 1 – Download FFmpeg

First you need to download and install FFmpeg encoder which you can download from here: Download FFmpeg. This encoder is used to edit video and audio files, you can edit MP4/FLV/MKV/3GP or MOV files. You can edit all types of audio files from this too including MP3, WAV or OGG. FFmpeg is basically a command line tool so after installation try to run the command in your terminal or command prompt:

> ffmpeg

This will make sure FFmpeg has been installed perfectly in your system. Now you can use it’s commands, you can find all documentation in it’s official website.

Step 2 – Creating layout

The design is quite simple, we will be using bootstrap darkly for designing the webpage. Bootstrap darkly will be included in the source files.

<link rel="stylesheet" href="bootstrap-darkly.min.css">

<div class="container" style="margin-top: 100px;">
    <div class="row">
	<div class="offset-md-4 col-md-4">
	    <form method="POST" enctype="multipart/form-data">
	        <div class="form-group">
	            <label>Video</label>
       	            <input type="file" name="video" class="form-control">
	        </div>

               <div class="form-group">
                   <label>Cut from</label>
                   <input type="text" name="cut_from" class="form-control" placeholder="00:00:00">
               </div>

               <div class="form-group">
                   <label>Duration</label>
                   <input type="text" name="duration" class="form-control" placeholder="00:00:00">
              </div>

              <input type="submit" name="submit" class="btn btn-primary" value="Split">

	    </form>
	</div>
    </div>
</div>

Step 3 – Split video in multiple parts

The next step is to split the file based on user input. Paste the following code on top of your file including the PHP starting and closing tags:

<?php

if (isset($_POST["submit"]))
{
    $file_name = $_FILES["video"]["tmp_name"];
    $cut_from = $_POST["cut_from"];
    $duration = $_POST["duration"];

    $command = "/usr/local/bin/ffmpeg -i " . $file_name . " -vcodec copy -ss " . $cut_from . " -t " . $duration . " output.mp4";
    system($command);
}

?>

Step 4 – Preview of selected video

At this point your script is working perfectly. One more thing you can add is to display the preview of video before performing the splitting action. So that the user can know which video he is about to split. To do this first you have to create a video tag just below input type file, so the preview of video will be displayed beneath the input field.

<video width="500" height="320" id="video" controls></video>

This will set the width and height of video. Make sure to give the unique “id” attribute and also the “controls” attribute. The id attribute will help in javascript to get the video tag and display the preview of selected video and controls attribute will display the controls in html5 video player.

Now you need to attach a javascript listener that will be called when the user selects the file. Go ahead and add an attribute on input type file tag.

onchange="onFileSelected(this);"

This will call the javascript function called “onFileSelected” and send the input type file as a parameter. Now we are going to create a function.

At the bottom of file paste the following code along with script tag at the start and end:

<script>

    function onFileSelected(self) {
        var file = self.files[0];
        var reader = new FileReader();

        reader.onload = function (event) {
            var src = event.target.result;
            var video = document.getElementById("video");
            video.setAttribute("src", src);
        };

        reader.readAsDataURL(file);
    }

</script>

Now that you have learned how to split the video file in multiple parts. You can also learn how to merge multiple videos into one. Follow this tutorial to do that.

[wpdm_package id=’150′]

Live CRUD with AJAX – PHP

By live CRUD with AJAX, we mean that you will be able to Create, Read, Update, Delete data without having to refresh the page. This tutorial does not have any dependency on jQuery, you can implement it without having to include jQuery in it. We will be using a sample database named classicmodels and it will be included in the source files below. It has multiple tables but we will be using a table named employees to perform all 4 operations.

Live CRUD with AJAX – PHP

Let’s get started:

Create

We will be creating a simple form to input all fields and a button to insert a new row in database. Be default, the browser redirects you to the action attribute of form but we will be using onsubmit event to prevent form from redirecting. And thus, we can call our javascript function to save data via AJAX.

<form method="POST" onsubmit="return doInsert(this);">
    <input name="first_name" placeholder="First name">
    <input name="last_name" placeholder="Last name">
		
    <input type="submit" value="Insert">
</form>

<script>
function doInsert(form) {
    var firstName = form.first_name.value;
    var lastName = form.last_name.value;
		
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "Http.php", true);
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200)
            alert(this.responseText);
    };

    ajax.send("first_name=" + firstName + "&last_name=" + lastName + "&do_insert=1");
    return false;
}
</script>

Http.php

This file will be responsible for serving all 4 operations. We will be creating a database connection and a separate block for each request. Simple !

<?php

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

if (isset($_POST["do_insert"]))
{
    $first_name = $_POST["first_name"];
    $last_name = $_POST["last_name"];
	
    $sql = "INSERT INTO `employees`(`lastName`, `firstName`) VALUES ('$last_name', '$first_name')";
    mysqli_query($connection, $sql);

    echo "Record has been inserted successfully.";
    exit();
}

Read

Display data in tabular form requires a table with unique ID to tbody tag.

<table>
    <thead>
        <tr>
	    <th>First Name</th>
	    <th>Last Name</th>
	</tr>
    </thead>

    <tbody id="data"></tbody>
</table>

<script>
    function getData() {
	var ajax = new XMLHttpRequest();
	ajax.open("GET", "Http.php?view_all=1", true);
	ajax.send();
		
	ajax.onreadystatechange = function () {
	    if (this.readyState == 4 && this.status == 200) {
		var data = JSON.parse(this.responseText);
		var html = "";

		for (var a = 0; a < data.length; a++) {
		    html += "<tr>";
			html += "<td>" + data[a].firstName + "</td>";
			html += "<td>" + data[a].lastName + "</td>";
		    html += "</tr>";
		}
				
	        document.getElementById("data").innerHTML = html;
	    }
	};
    }

    getData();
</script>

Http.php

There are no parameters in the AJAX request so for the sake of simplicity, in this file we will just be fetching all records from database. Paste the following code right below INSERT block done in previous step in Http.php:

if (isset($_GET["view_all"]))
{
    $sql = "SELECT * FROM employees";
    $result = mysqli_query($connection, $sql);

    $data = array();
    while ($row = mysqli_fetch_object($result))
	    array_push($data, $row);

    echo json_encode($data);
    exit();
}

Delete

Removing a row from database is the simplest part of this tutorial, just enter an ID, sends an AJAX request and execute the DELETE command.

<form method="POST" onsubmit="return doDelete(this);">
    <input name="employee_id" placeholder="Employee ID">
    <input type="submit" value="Delete">
</form>

<script>
    function doDelete(form) {
        var employeeID = form.employee_id.value;

        var ajax = new XMLHttpRequest();
        ajax.open("POST", "Http.php", true);
        ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

        ajax.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200)
                alert(this.responseText);
        };

        ajax.send("employee_id=" + employeeID + "&do_delete=1");
        return false;
    }
</script>

Http.php

We will be using simple DELETE query to remove a row from database. Paste the following code right below VIEW ALL block done in previous step in Http.php:

if (isset($_POST["do_delete"]))
{
    $employee_id = $_POST["employee_id"];

    $sql = "DELETE FROM employees WHERE employeeNumber = '" . $employee_id . "'";
    mysqli_query($connection, $sql);

    echo "Record has been deleted";
    exit();
}

Update (a)

Updating the data would require 2 forms, 1 to get data of record you want to update, and 2nd to actually update the data in database. First we are going to get the record which needs to be updated:

<form method="POST" onsubmit="return getData(this);">
    <input name="employee_id" placeholder="Employee ID">
    <input type="submit" value="Search">
</form>

<script>
function getData(form) {
    var employeeID = form.employee_id.value;

    var ajax = new XMLHttpRequest();
    ajax.open("POST", "Http.php", true);
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            var form = document.getElementById("form-update");

            /* Show data in 2nd form */
            form.first_name.value = data.firstName;
            form.last_name.value = data.lastName;
            form.employee_id.value = employeeID;

            form.style.display = "";
        }
    };

    ajax.send("employee_id=" + employeeID + "&get_data=1");
    return false;
}
</script>

Http.php

This query will be almost same as for VIEW ALL function. Paste the following code right below DELETE block done in previous step in Http.php:

if (isset($_POST["get_data"]))
{
    $employee_id = $_POST["employee_id"];

    $sql = "SELECT * FROM employees WHERE employeeNumber = '" . $employee_id . "'";
    $result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_object($result);

    echo json_encode($row);
    exit();
}

Update (b)

In this step, we will actually be updating the record in database. This step is almost similar to the INSERT section.

<form method="POST" onsubmit="return doUpdate(this);" id="form-update" style="display: none;">
    <input type="hidden" name="employee_id">
    <input name="first_name" placeholder="First name">
    <input name="last_name" placeholder="Last name">
    <input type="submit" value="Update">
</form>

<script>
function doUpdate(form) {
    var firstName = form.first_name.value;
    var lastName = form.last_name.value;
    var employeeID = form.employee_id.value;

    var ajax = new XMLHttpRequest();
    ajax.open("POST", "Http.php", true);
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200)
            alert(this.responseText);
    };

    ajax.send("first_name=" + firstName + "&last_name=" + lastName + "&employee_id=" + employeeID + "&do_update=1");

    return false;
}
</script>

Http.php

Paste the following code right below GET DATA block done in previous step in Http.php:

if (isset($_POST["do_update"]))
{
    $first_name = $_POST["first_name"];
    $last_name = $_POST["last_name"];
    $employee_id = $_POST["employee_id"];

    $sql = "UPDATE `employees` SET `lastName` = '$last_name', `firstName` = '$first_name' WHERE employeeNumber = '" . $employee_id . "'";
    mysqli_query($connection, $sql);

    echo "Record has been updated successfully.";
    exit();
}

That’s how you can implement a complete live CRUD operation with AJAX, PHP and MySQL. If you want to get more advanced. You can check our tutorial on doing a CRUD operation in Vue JS.

[wpdm_package id=’146′]

Run cron jobs on localhost

In this tutorial, you will be learning to create and run cron jobs on localhost. You will need XAMPP or WAMP and this tutorial is for Windows OS only. We will be creating a cron job that will insert a new row in database once a day. We will be using Windows Task Scheduler to tell which file to execute as a cron jobs.

Insert row in database

Create a simple file named index.php and write the PHP code to insert a new row every time that file executes. We have created a sample database called my_db and it has only 1 table called my_table and that table has only 1 column called current_date.

<?php

// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "my_db");

// Getting current date
$date_time = date("Y-m-d");

// Inserting in database
mysqli_query($connection, "INSERT INTO my_table(current_date) VALUES('$date_time')");

Creating script.bat file for windows Task Scehduler

Script.bat is the file that will tell the windows task scheduler which file to execute as a cron job. In this file, you have to tell the path to your php.exe file which is located in your XAMPP or WAMP “php” folder and the path to your index.php file. Create a simple file named script.bat and paste the following code in it:

"path_to_php.exe" -f "path_to_index.php"

Creating a VBS file

A VBS file should be created that will tell the path of script.bat file. Create a new file named shell.vbs and paste the following code in it:

'Starts a new windows shell process (command line).
Set WinScriptHost = CreateObject("WScript.Shell")

'Runs a command and sets the character set for the text string, "script.bat"
WinScriptHost.Run Chr(34) & "script.bat" & Chr(34), 0

'Tells the shell not to display the window.
Set WinScriptHost = Nothing

Setting up Task Scheduler

You can follow the video below to setup the task scheduler in your windows:

That’s how you can run cron jobs on your localhost in windows operating system. If you face any problem in following this, kindly do let us know.

Follow more PHP tutorials.

[wpdm_package id=’144′]

Crop and save image – PHP

You can crop the image before uploading and save it on your server using PHP. Cropping an image would require a jQuery library called cropper. You can download the cropper library from the link below:

Download cropper library

Go ahead and download this library. You will also need jQuery for this. All files have also been included in the source files below.

Including library files

After downloading and placing the files in your project, you will be need to include 3 files. jQuery, cropper.css and cropper.js. You can find those files in the source files below:

index.php

<script src="jquery-3.3.1.min.js"></script>
<script src="cropper.js"></script>
<link rel="stylesheet" type="text/css" href="cropper.css">

<!-- Image needs to be cropped, should be displayed in an <img> tag -->
<img src="adnan-afzal.jpg" style="width: 200px;" id="image">

<!-- Initiating the library and disabling the zoom from mouse wheel and from laptop mousepad -->
<script>
    $(function () {
        $("#image").cropper({
            zoomable: false
        });
    });
</script>

<!-- If you want to remove the background and make it transparent, you can apply the following styles -->
<style>
    .cropper-crop {
        display: none;
    }
    .cropper-bg {
        background: none;
    }
</style>

At this point, you will be able to crop the selected image in <img> tag. Next step is to save the cropped area from image.

Saving image cropped area

First you have to create a simple button, upon click will send an AJAX request with cropped area:

<!-- A button when clicked will save the cropped area -->
<button type="button" onclick="crop();">
    Crop
</button>

<script>
function crop() {
    // Blob is a textual form of an image which will be obtained from <img> tag
    $("#image").cropper("getCroppedCanvas").toBlob(function (blob) {

        // FormData is a built-in javascript object
        var formData = new FormData();
        formData.append("croppedImage", blob);

        $.ajax({
            url: "upload.php", // name of the file which we will be creating soon
            method: "POST",
            data: formData,
            processData: false, // necessary for sending image data
            contentType: false, // necessary for sending image data
            success: function (response) {
                alert(response);
            }, error: function (xhr, status, error) {
                console.log(status, error);
            }
        });
    });
}
</script>

Now, we just have to create a new file named upload.php and paste the following code in it. The code is pretty simple, we can storing the image sent from AJAX using the built-in PHP function called move_uploaded_file():

upload.php

<?php

move_uploaded_file($_FILES["croppedImage"]["tmp_name"], "Cropped image.jpg");
echo "Image has been uploaded";

That’s it, go on and try cropping an image and hit the “Crop” button. Your cropped area will be saved as “Cropped image.jpg”.

[wpdm_package id=’142′]

Dynamic Pagination – PHP

Dynamic pagination is one of the most amazing way to optimize your page load if you have a lot of record in your database. You can see it in a tech giant Google, when you search for something, you will see a list of page numbers at the bottom of page. We will be using a sample database called classicmodels and we are assuming to display 5 records in one page.

Creating a layout

Our layout should be super simple, a simple bootstrap table and an unordered list for page number list:

<table class="table">
    <tr>
        <th>Employee number</th>
        <th>First name</th>
        <th>Last name</th>
        <th>Email</th>
    </tr>
</table>

Displaying dynamic pagination links

To display pagination links, we have to divide total rows by the number of records we want to display in 1 page. For example, if you have 30 records in your database and you want to display 5 records in 1 page, the formula should be:

30 / 5 = 6

Thus, 6 links will be displayed in an unordered list:

// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "classicmodels");
// How many records will be displayed in one page
$record_per_page = 5;
// Getting total number of records
$sql = "SELECT COUNT(*) AS total FROM employees";
$result = mysqli_query($connection, $sql);
$total = mysqli_fetch_object($result)->total;
// Calculating number of pagination links required
$pages = ceil($total / $record_per_page);

Then we can simply loop till $pages variable and display the list items:

<ul class="pagination">
    <?php for ($a = 1; $a <= $pages; $a++): ?>
        <li class="<?php echo $a == $page_number ? 'active' : ''; ?>">
            <a href="?page=<?php echo $a; ?>">
                <?php echo $a; ?>
            </a>
        </li>
    <?php endfor; ?>
</ul>

At this point, if you run the file you will only see pagination links. On clicking you will see $page variable in the URL. We will be using this to display records as per that page.

Displaying records based on page number

Before the <table> tag, you need to check if there is $page variable in the URL. If not, then the variable should have value 1, by default. To append that variable in MySQL query, we need to subtract 1 from it as the index starts from 0. Then we will multiply it with 5 (number of records in 1 page). So your basic formula should be:

($page_number – 1) * 5

So if you are on page 3, then putting the values you will get:

(3 – 1) * 5 = 10

Thus, it will get records from 10 to 15. Below is the code for it:

$page_number = isset($_GET["page"]) ? $_GET["page"] : 1;
$start_from = ($page_number - 1) * $record_per_page;
$sql = "SELECT * FROM employees LIMIT " . $start_from . ", " . $record_per_page;
$result = mysqli_query($connection, $sql);

And to display it in <table> you can do:

<?php while ($row = mysqli_fetch_object($result)): ?>
    <tr>
        <td><?php echo $row->employeeNumber; ?></td>
        <td><?php echo $row->firstName; ?></td>
        <td><?php echo $row->lastName; ?></td>
        <td><?php echo $row->email; ?></td>
    </tr>
<?php endwhile; ?>

That’s it. You can also learn dynamic pagination in Node JS and Mongo DB from here.

[wpdm_package id=’140′]

Load more data using AJAX – PHP

Learn how you can show a “Load more” button using AJAX, PHP and MySQL. No external library has been used in this tutorial.

What is “Load more” button ?

By “Load more” we mean creating a button that allows you to show only 10 or 20 records and on clicking that button will fetch next 10 records from database without having to refresh the page. This function is heavily used in tech giant Facebook where older posts are fetched by scrolling without refreshing the page.

We will be using a sample database called classicmodels, it is attached in the source files below.

Create layout

We will be using employees table and displaying employeeNumber, firstName, lastName and email fields. A unique ID should be provided to <tbody> which will be used to append data using Ajax.

<table>
    <thead>
        <tr>
            <th>Number</th>
            <th>First name</th>
            <th>Last name</th>
            <th>Email</th>
        </tr>
    </thead>

    <tbody id="data"></tbody>
</table>

<button type="button" onclick="getData();">
    Load More
</button>

Display initial records

We are displaying 10 records in each step and we will need just 1 variable for this. start to tell the starting position of fetching data and it will be incremented in each step.

<script>
    // Starting position to get new records
    var start = 0;

    // This function will be called every time a button pressed 
    function getData() {
        // Creating a built-in AJAX object
        var ajax = new XMLHttpRequest();

        // Sending starting position
        ajax.open("GET", "Http.php?start=" + start, true);

        // Actually sending the request
        ajax.send();

        // Detecting request state change
        ajax.onreadystatechange = function () {

            // Called when the response is successfully received
            if (this.readyState == 4 && this.status == 200) {

                // For debugging purpose only
                console.log(this.responseText);
            }
        };
    }

    // Calling the function on page load
    getData();
</script>

At this point if you run the program, you will see an empty table and a button, now you need to create Http.php file to handle each request.

Handling AJAX request – PHP

Create a new file and name it Http.php, in this file we will simply get the offset (start variable) and display the records based on that value.

<?php

// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "classicmodels");

// Getting offset to show next records
$start = $_GET["start"];

// Executing the query based on $start variable
$sql = "SELECT * FROM employees LIMIT $start, 10";
$result = mysqli_query($connection, $sql);

// Storing all returned records in an array
$data = array();
while ($row = mysqli_fetch_object($result))
    array_push($data, $row);

// Sending response back to AJAX
echo json_encode($data);

Now if you view your browser console, you will see some JSON string data when the page loads.

Appending records in table

Now you need to convert that JSON string into Javascript array and append in <tbody> tag. Paste the following code back in your index.php file:

ajax.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
        
        // Converting JSON string to Javasript array
        var data = JSON.parse(this.responseText);
        var html = "";

        // Appending all returned data in a variable called html
        for (var a = 0; a < data.length; a++) {
            html += "<tr>";
                html += "<td>" + data[a].employeeNumber + "</td>";
                html += "<td>" + data[a].firstName + "</td>";
                html += "<td>" + data[a].lastName + "</td>";
                html += "<td>" + data[a].email + "</td>";
            html += "</tr>";
        }

        // Appending the data below old data in <tbody> tag
        document.getElementById("data").innerHTML += html;

        // Incrementing the offset so you can get next records when that button is clicked
        start = start + 10;
    }
};

So for example, first time you will get employees from 1 to 10 and next time you hit load more button you will get employees from 11 to 20 and so on.

That’s how you can show a “Load more” button using AJAX, PHP and MySQL. You can also create a load more button in Node JS and Mongo DB. Learn from here how you can do that.

[wpdm_package id=’138′]

Reset password – PHP & MySQL

We will be using 4 files to implement reset password option.

  • index.php (to get email address)
  • send-recovery-mail.php (to send email)
  • reset-password.php (to enter new password)
  • new-password.php (to update the password)

Your table structure should be like this:

You need to create a table in database called users and the most important columns are email and reset_token. Sending email via localhost requires an Gmail account and you need to enable less secure apps for your account. You can enable it from the link below:

Enable less secure apps

Enter email address

Create a simple form to get user’s email address, where recovery mail should be sent.

<form method="POST" action="send-recovery-mail.php">
    <input type="email" name="email">
    <input type="submit" value="Send recovery email">
</form>

Send recovery email

We will be using PHPMailer library, you can download it from the link below:

Download PHPMailer

Next you need to include the library and make a connection with database:

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

First you need to check if a user of that email exists in your database:

$email = $_POST["email"];

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    //
}
else
{
    echo "Email does not exists";
}

Inside the if statement, you need to generate a unique token which will be sent in email:

if (mysqli_num_rows($result) > 0)
{
    $reset_token = time() . md5($email);
}
else
{
    echo "Email does not exists";
}

After that, you need to save this token against that user’s database record:

$sql = "UPDATE users SET reset_token='$reset_token' WHERE email='$email'";
mysqli_query($connection, $sql);

Then you create a variable called $message and write all the text that you want to send in recovery email:

$message = "<p>Please click the link below to reset your password</p>";
$message .= "<a href='http://localhost/tutorials/add-a-reset-password-option/reset-password.php?email=$email&reset_token=$reset_token'>";
	$message .= "Reset password";
$message .= "</a>";
  • Replace your web URL with the highlighted text.

Now, simply send the email via PHPMailer. We have created a separate function to do that:

function send_mail($to, $subject, $message)
{
    $mail = new PHPMailer(true);

    try {
        //Server settings
	$mail->SMTPDebug = 0;                                       // Enable verbose debug output
	$mail->isSMTP();                                            // Set mailer to use SMTP
	$mail->Host       = 'smtp.gmail.com;';  // Specify main and backup SMTP servers
	$mail->SMTPAuth   = true;                                   // Enable SMTP authentication
	$mail->Username   = 'your_gmail_address';                     // SMTP username
	$mail->Password   = 'your_gmail_password';                               // SMTP password
	$mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
	$mail->Port       = 587;                                    // TCP port to connect to

	$mail->setFrom('your_gmail_address', 'your_name');
	//Recipients
	$mail->addAddress($to);

	// Content
	$mail->isHTML(true);                                  // Set email format to HTML
	$mail->Subject = $subject;
	$mail->Body    = $message;

	$mail->send();
	echo 'Message has been sent';
    } catch (Exception $e) {
	echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}

And you can call this function right after$message variable:

send_mail($email, "Reset password", $message);

At this point, when you enter email and hit submit you will receive an email with a receovery link. On clicking you will be redirected to your site on page reset-password.php.

Enter new password

Now you need to create a file named reset-password.php. In this file, first you need to check if it comes from email link:

<?php

$email = $_GET["email"];
$reset_token = $_GET["reset_token"];

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    //
}
else
{
    echo "Email does not exists";
}

Second, you need to check if the token is not tempered, so that you cannot change someone else’s password:

$user = mysqli_fetch_object($result);
if ($user->reset_token == $reset_token)
{
    //
}
else
{
    echo "Recovery email has been expired";
}

Third, display a simple form to enter new password. The email and reset_token needs to be hidden in this file so that you can update password for only that specific user:

if ($user->reset_token == $reset_token)
{
    ?>
    <form method="POST" action="new-password.php">
        <input type="hidden" name="email" value="<?php echo $email; ?>">
    	<input type="hidden" name="reset_token" value="<?php echo $reset_token; ?>">
		
    	<input type="password" name="new_password" placeholder="Enter new password">
    	<input type="submit" value="Change password">
    </form>
    <?php
}
else
{
    echo "Recovery email has been expired";
}

Reset the password

Now you only needs to create a new file named new-password.php and paste the following code in it:

<?php

$email = $_POST["email"];
$reset_token = $_POST["reset_token"];
$new_password = $_POST["new_password"];

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    $user = mysqli_fetch_object($result);
    if ($user->reset_token == $reset_token)
    {
    	$sql = "UPDATE users SET password='$new_password' WHERE email='$email' AND reset_token='$reset_token'";
    	mysqli_query($connection, $sql);

    	echo "Password has been changed";
    }
    else
    {
    	echo "Recovery email has been expired";
    }
}
else
{
    echo "Email does not exists";
}

That’s how you can reset password using PHP and MySQL. Learn also how you can do email verification in your website.

[wpdm_package id=’136′]

Attach files in email – PHP

In this tutorial, we will teach you how you can attach files in an email using PHP. We will be using PHPMailer library to send an email.

Attach files in email – PHP

We will be creating a simple form to enter email address of receiver, subject, message and ability to select a file. That file will be attached in a email and sent to the receiver. If you are testing via XAMPP/WAMP/MAMP you may need to download PHPMailer library from the link below:

Download PHPMailer

You can install the library from composer, all details are provided in the link above. We will be using 2 files, 1 to display a form for input and 2nd to send the mail.

Getting user input

Below is the code for index.php file

<form method="POST" enctype="multipart/form-data" action="send-mail.php">
    <p>
	Send to:
	<input type="text" name="receiver">
    </p>

    <p>
	Subject:
	<input type="text" name="subject">
    </p>

    <p>
	Message:
	<textarea name="message"></textarea>
    </p>

    <p>
	Select file:
	<input type="file" name="file">
    </p>

    <input type="submit">
</form>

Attaching file with email

Sending email via localhost requires an Gmail account and you need to enable less secure apps for your account. You can enable it from the link below:

Enable less secure apps

Now paste the following code in your send-mail.php file:

<?php

// 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\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 0;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com;';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'your_gmail_ID';                     // Your gmail address
    $mail->Password   = 'your_gmail_password';                               // Your gmail password
    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('your_gmail_ID', 'your_name');
    $mail->addAddress($_POST["receiver"]);

    $file_name = $_FILES["file"]["name"];
    move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
    $mail->addAttachment($file_name);

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $_POST["subject"];
    $mail->Body    = $_POST["message"];

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

If you are using Mac, you may need to enable folder permission. You can enable folder permission by following steps below:

Folder permission for Mac users
Folder permission for Mac users

Now go ahead and try to submit the form and attaching any file to it. You will have attached file in your inbox (or in your spam if using localhost).

Instead of attaching the file in email, you can also upload the file on your server. And share its download link via an email. Learn here how you can do that.

[wpdm_package id=’133′]

Upload, Download and Delete files – PHP

We will teach you how you can upload, download and delete files in PHP. We will be implementing 3 functions and will be creating 3 files for each function:

  1. upload.php for uploading the file
  2. index.php for downloading the file
  3. delete.php for deleting the file

Upload file

Start off, by creating 2 files index.php and upload.php, also create a folder named uploads all uploaded files will be stored in this folder. If you are using Mac, you may need to enable permission by following the below steps:

Folder permission for Mac users

Folder permission for Mac users

Now you need to create a simple form that allows a user to select file from his computer to upload in your server:

<form method="POST" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

Next create a file named upload.php and paste the following code in it:

<?php

// Getting uploaded file
$file = $_FILES["file"];

// Uploading in "uplaods" folder
move_uploaded_file($file["tmp_name"], "uploads/" . $file["name"]);

// Redirecting back
header("Location: " . $_SERVER["HTTP_REFERER"]);

At this point, if you execute the index.php file you will be able to select file and when you click Upload button, the selected file should be saved in uploads folder.

Download file

In order to download the file, we are going to display a list of all files and a Download button. Paste the following code in index.php file:

<?php

// This will return all files in that folder
$files = scandir("uploads");

// If you are using windows, first 2 indexes are "." and "..",
// if you are using Mac, you may need to start the loop from 3,
// because the 3rd index in Mac is ".DS_Store" (auto-generated file by Mac)
for ($a = 2; $a < count($files); $a++)
{
    ?>
    <p>
    	<!-- Displaying file name !-->
        <?php echo $files[$a]; ?>

        <!-- href should be complete file path !-->
        <!-- download attribute should be the name after it downloads !-->
        <a href="uploads/<?php echo $files[$a]; ?>" download="<?php echo $files[$a]; ?>">
            Download
        </a>
    </p>
    <?php
}

At this point, if you refresh index.php you will see a list of all your uploaded files along with a Download button. Clicking on the Download button, will open a Download dialog based on your browser.

Delete file

In order to delete the file, first display a button to be clicked to delete. Href should be the full path of the file. The following code should be inserted inside the loop, after the Download button:

<a href="delete.php?name=uploads/<?php echo $files[$a]; ?>" style="color: red;">
    Delete
</a>

Create a new file named delete.php and paste the following code in it:

<?php

// Built-in PHP function to delete file
unlink($_GET["name"]);

// Redirecting back
header("Location: " . $_SERVER["HTTP_REFERER"]);

Now you will see a red button with a text Delete, on click it will delete the file and refresh the index.php page so you will see the remaining files. That’s how you can upload, download and delete the files in PHP.

You can also learn to:

  1. Upload file in Node JS
  2. Download files in BLOB
  3. Upload, download, and delete from Firebase storage from here