Email download link of a file – PHP and MySQL

In this tutorial, we are going to show you, how you can email a download link of a file to a user when they request to download files from your website. We are going to create a system where you can upload files and the user will be able to download them. But before downloading, they must enter their email address. The link to download the file will be emailed to the user. In this way, you will get a large number of emails. This will help you with a very large email list.

Prevent direct access to files

First, we are going to prevent users from downloading the files directly from the URL. We will be storing all our uploaded files in the “uploads” folder. So, create a new folder named “uploads” at the root of your project. Create a “.htaccess” file in this folder. In this file, write the following single line:

deny from all

This will gives a “403 Forbidden” error whenever someone tries to access the file directly from the browser.

Upload files

Now we are going to create a form that will allow you to upload files. You can create this form in your admin panel because usually, the administrator of the website can upload files.

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

Create a database named “collect_emails_while_downloading_files” in your phpMyAdmin. Or you can use your own database if you already have one. In this database, you need to create a table where we will store the path and name of all uploaded files.

CREATE TABLE files (
	id INTEGER(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
	file_name TEXT NOT NULL,
    file_path TEXT NOT NULL
);

Then we need to save the selected file in the uploads folder and its path in the files table in the MySQL database. We will be using PHP PDO prepared statements that will help us from preventing the SQL injection.

<?php

    // connect with database
    $conn = new PDO("mysql:host=localhost:8889;dbname=collect_emails_while_downloading_files", "root", "root");

    // check if form is submitted, for admin panel only
    if (isset($_POST["upload"]))
    {
        // get the file
        $file = $_FILES["file"];
        
        // make sure it does not have any error
        if ($file["error"] == 0)
        {
            // save file in uploads folder
            $file_path = "uploads/" . $file["name"];
            move_uploaded_file($file["tmp_name"], $file_path);

            // save file path in database, prevent SQL injection too
            $sql = "INSERT INTO files(file_name, file_path) VALUES (:file_name, :file_path)";
            $result = $conn->prepare($sql);
            $result->execute([
                ":file_name" => $file["name"],
                ":file_path" => $file_path
            ]);
        }
        else
        {
            die("Error uploading file.");
        }
    }

    // get all files
    $sql = "SELECT * FROM files ORDER BY id DESC";
    $result = $conn->query($sql);
    $files = $result->fetchAll();

?>

Refresh the page and try uploading a file. You will see it will be saved in your uploads folder and its path and name will be stored in the files table. Also, try accessing that from the browser directly, it will give you a 403 Forbidden error.

Show all uploaded files

In the previous step, we ran a query to fetch all files sorting from latest to oldest. Now we need to show them on a table.

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Action</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach ($files as $file): ?>
            <tr>
                <td><?php echo $file["id"]; ?></td>
                <td><?php echo $file["file_name"]; ?></td>
                <td>
                    <!-- button to download file -->
                    <form method="POST" action="check-email.php" onsubmit="return onFormSubmit(this);">
                        <input type="hidden" name="id" value="<?php echo $file['id']; ?>" required />
                        <input type="hidden" name="email" />
                        <input type="submit" value="Download" />
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

This will show all files in a table with a button to download. When that button is clicked, we need to get the user’s email address so we can email him a download link for that file. That link will be valid for that file and for that email only.

<script>
    function onFormSubmit(form) {
        // get email address and submit
        var email = prompt("Enter your email:", "");
        if (email != null && email != "") {
            form.email.value = email;
            return true;
        }
        return false;
    }
</script>

Send download link in email

We will be using the PHPMailer library to send emails. Open CMD at the root folder of your project and run the following command. Make sure you have the composer downloaded and installed in your system.

composer require phpmailer/phpmailer

Create a table in your database that will store all the download requests of files sent by users. Run the following query in your database in phpMyAdmin:

CREATE TABLE download_requests (
	id INTEGER(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
	file_id INTEGER(11) NOT NULL,
	email TEXT NOT NULL,
	token TEXT NOT NULL,
	CONSTRAINT fk_file_id FOREIGN KEY (file_id) REFERENCES files (id) ON DELETE CASCADE ON UPDATE CASCADE
);

Create a file named “check-email.php” and write the following code in it. It will send the email to the user and also will store the data in the above created table.

<?php

    // composer require phpmailer/phpmailer

    // include PHPMailer library
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    
    require 'vendor/autoload.php';

    // connect with database
    $conn = new PDO("mysql:host=localhost:8889;dbname=collect_emails_while_downloading_files", "root", "root");

    // get all form values
    $id = $_POST["id"];
    $email = $_POST["email"];

    // generate a unique token for this email only
    $token = time() . md5($email);

    // get file from database
    $sql = "SELECT * FROM files WHERE id = :id";
    $result = $conn->prepare($sql);
    $result->execute([
        ":id" => $id
    ]);
    $file = $result->fetch();
    
    if ($file == null)
    {
        die("File not found");
    }

    // insert in download requests, prevent SQL injection too
    $sql = "INSERT INTO download_requests(file_id, email, token) VALUES (:id, :email, :token)";
    $result = $conn->prepare($sql);
    $result->execute([
        ":id" => $id,
        ":email" => $email,
        ":token" => $token
    ]);

    // send email to user
    $mail = new PHPMailer(true);

    try
    {
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'your_email@gmail.com';
        $mail->Password = 'your_password';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        $mail->setFrom('adnan@gmail.com', 'Adnan');
        $mail->addAddress($email); // Add a recipient
        $mail->addReplyTo('adnan@gmail.com', 'Adnan');

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Download your files';

        // mention download link in the email
        $email_content = "Kindly click the link below to download your files: <br />";
        $base_url = "http://localhost:8888/tutorials/collect-emails-while-downloading-files-php-mysql";
        $email_content .= "<a href='" . $base_url . "/download.php?email=" . $email . "&token=" . $token . "'>" . $file['file_name'] . "</a>";
        $mail->Body = $email_content;

        $mail->send();
        echo '<p>Link to download files has been sent to your email address: ' . $email . '</p>';
    }
    catch (Exception $e)
    {
        die("Message could not be sent. Mailer Error: " . $mail->ErrorInfo);
    }

Make sure to change the base URL at line 68. Also, change your email address and password on lines 53 and 54 respectively. This email will be used to send the emails. Goto this link and enable a less secure apps option for that email address.

Enable less secure apps – Gmail

Test the code now. You will be able to see a list of all uploaded files with a button to download. When clicked, it will show a prompt where you can enter your email address. When clicked “OK”, it will send an email with a download link and also it will store it in the “download_requests” table in the MySQL database.

In your email, you will see a link to download the file. But right now it will give a 404 Not found error because the file is not created yet.

Download the file from email download link

Create a file named “download.php” and write the following code in it. This will directly download the file into your system.

<?php

    // connect with database
    $conn = new PDO("mysql:host=localhost:8889;dbname=collect_emails_while_downloading_files", "root", "root");

    // get variables from email
    $email = $_GET["email"];
    $token = $_GET["token"];

    // check if the download request is valid
    $sql = "SELECT *, download_requests.id AS download_request_id FROM download_requests INNER JOIN files ON files.id = download_requests.file_id WHERE download_requests.email = :email AND download_requests.token = :token";
    $result = $conn->prepare($sql);
    $result->execute([
        ":email" => $email,
        ":token" => $token
    ]);
    $file = $result->fetch();

    if ($file == null)
    {
        die("File not found.");
    }

    // download the file
    $url_encoded_file_name = rawurlencode($file["file_name"]);
    $file_url = "http://localhost:8888/tutorials/collect-emails-while-downloading-files-php-mysql/uploads/" . $url_encoded_file_name;
    // die($file_url);

    // headers to download any type of file
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $file["file_name"] . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file["file_path"]));
    readfile($file["file_path"]);

Make sure to change your base URL at line 26. Now you can run a complete test cycle again. Upload a file, click the download button, and enter your email. Check your email and then click the download link from the email and the file will be downloaded. Verify the file that is downloaded correctly.

So that’s how you can collect a large number of emails by allowing people to simply download files. You can create a very large email list from it.

Learn how to send attachment with an email using PHP.

Attach files in email – PHP

[wpdm_package id=’1281′]

Watermark image after upload – PHP, No Library

In this tutorial, we will teach you how you can put a watermark on an image uploaded by a user. You might have seen websites that allow you to upload images, but when you try to download them, they put their watermark on your image and ask you to pay to remove it. So let’s learn how they do this.

First I am going to create a form where we will show the input type file to select the image. Its method will be POST and the action will be “index.php”. The encoding (enctype) type must be multipart/form-data. This is necessary for uploading files. Then we are going to show a label that says “select file” and an input type file. The name attribute on the input type file will be used on the PHP side. It will also have an attribute accept=”image/*”, which means this input field will accept only image type, for example, PNG or JPEG, etc, but no PDF or DOCX type of files will be selected in this field. Finally, the form will have a submit button. Submit button will have a name attribute so we can know when this form is submitted.

Select a file

<form method="POST" action="index.php" enctype="multipart/form-data">

	<p>
		<label>Select file</label>
		<input type="file" name="image" accept="image/*" />
	</p>

	<input type="submit" name="submit" value="Upload" />
</form>

If you run the code now, you will see a form with an input type file and a submit button. Now we need to write the PHP code to handle this form.

Apply the watermark

First, we will check if the form is submitted.

<?php

if (isset($_POST["submit"]))

Then we will save the user uploaded image in a file named “image.png” because, in order to put a watermark on it, the file must be stored in our server.

move_uploaded_file($_FILES["image"]["tmp_name"], "image.png");

Then we need to get this image as an object. So call imagecreatefromjpeg function if your image was a JPEG image, imagecreatefrompng if it is a PNG. Parameter will be the path of saved image file.

$image_obj = imagecreatefromjpeg("image.png");

Similarly, we will create an object of our watermark image, which is a PNG image.

$watermark = imagecreatefrompng("watermark.png");

Then we will define the margin from the right and from the bottom, since we do not want the watermark to stick to the corners, we want a little margin.

$margin_right = 10;
$margin_bottom = 10;

Then we are going to get the watermark image width and height in a separate variable.

$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);

Now comes the tricky part. We need to tell the X and Y coordinates of original image where we will place the watermark. The X position from left will be width of uploaded image, minus width of watermark image, minus margin from right.

$destination_x = imagesx($image_obj) - $watermark_width - $margin_right;

Similarly, the Y position from top will be height of uploaded image, minus height of watermark image, minus margin from bottom.

$destination_y = imagesy($image_obj) - $watermark_height - $margin_bottom;

Now we need to copy the watermark image in user uploaded image. The syntax of this function is:

// imagecopy(dst_im, src_im, dst_x, dst_y, src_x, src_y, src_w, src_h)

Our destination image is the image uploaded by user. Source image is the watermark image. Destination x and y are just we calculated, I will explain this as well. And source x and y will be zero, because we do not want any margin in our watermark image. And finally the width and height of our source image which is watermark image.

imagecopy($image_obj, $watermark, $destination_x, $destination_y, 0, 0, $watermark_width, $watermark_height);

Now let me explain the calculation we did above.

Explaining X, Y co-ordinates

width of user image = 2560
width of watermark image = 640
margin from right = 10

2560 - 640 - 10 = 1910 = x

height of user image = 1600
height of watermark image = 345
margin from bottom = 10

1600 - 345 - 10 = 1245 = y

First is destination_x variable. The width of image object is 2560px, minus the width of watermark is 640px, minus the margin right which is 10. That equals 1910, so our watermark will be placed at 1910 on X axis from left. Now come to destination_y variable, height of user uploaded image is 1600px, it will be different for each image because user can upload image of any resolution. I am writing these values as sample. So the 1600px is the height of user uploaded image. Minus the height of watermark, which is 345px. Minus margin from bottom that is 10. That equals 1245. So our watermark image will be placed at 1245 on Y axis from top.

1910 + 640 = 2550
1245 + 345 = 1590

Now when the watermark is placed at 1910 from left and it has a width of 640px, then that equals 2550 which is 10px less than the width of user image, which is 2560px. So there is a difference of 10px, which means there will be a margin of 10px from right. Similarly, when the watermark is placed at 1245 from the top and it has a height of 345px, then that equals 1590 which is again 10px less than the height of the user image, which is 1600px. So it will have a margin of 10px from the bottom.

Generating watermarked image

Now the watermark image object has been copied to the user uploaded image object using imagecopy function above. Now we need to generate that image.

imagepng($image_obj, "output.png");

The first parameter will be an image object, which is a user object along with a watermark object because the watermark image has been copied to it. And second, will be the path of the output file.

Finally, we are going to destroy the image objects we just created for user-uploaded images and watermark image to free up the memory.

imagedestroy($image_obj);
imagedestroy($watermark);

Also, we saved the user image using the move uploaded file function because we need the image to be stored before putting a watermark on it. Now the watermark is placed, so we have no need for the original user-selected picture, so we are going to delete it using the unlink function.

unlink("image.png");

If you run the code now, select an image, and upload it, you will see that the original image was saved as image.png and the output.png is being rendered for a few seconds. When the output.png is completely rendered then the original image.png was automatically deleted because we have used the unlink function.

Complete code

<?php

if (isset($_POST["submit"]))
{
	move_uploaded_file($_FILES["image"]["tmp_name"], "image.png");
	$image_obj = imagecreatefromjpeg("image.png");

	$watermark = imagecreatefrompng("watermark.png");

	$margin_right = 10;
	$margin_bottom = 10;

	$watermark_width = imagesx($watermark);
	$watermark_height = imagesy($watermark);

	$destination_x = imagesx($image_obj) - $watermark_width - $margin_right;
	$destination_y = imagesy($image_obj) - $watermark_height - $margin_bottom;

	// imagecopy(dst_im, src_im, dst_x, dst_y, src_x, src_y, src_w, src_h)
	imagecopy($image_obj, $watermark, $destination_x, $destination_y, 0, 0, $watermark_width, $watermark_height);

	// 2560 - 640 - 10 = 1910
	// 1600 - 345 - 10 = 1245

	// x = 1910 + 640 = 2550
	// y = 1245 + 345 = 1590

	imagepng($image_obj, "output.png");

	imagedestroy($image_obj);
	imagedestroy($watermark);

	unlink("image.png");
}

?>

The final image will be of the same quality as of original image. If you face any problems in following this, kindly mention them in the comments section below.

How you can also resize the image without stretching in PHP by following this tutorial.

[wpdm_package id=’1262′]

PHP object as argument to Javascript function

Suppose you have a PHP variable or an object which you want to pass as an argument to a Javascript function whenever a button is clicked. Following this tutorial, you will be able to do so.

We will not be directly sending the PHP variable, but instead, we will attach the PHP variable to the HTML tag attribute and then send that tag to the Javascript function.

<?php
    $variable = "Adnan";

    $object = new \stdClass();
    $object->my_value = 2021;
?>

<button type="button"
    data-variable="<?php echo $variable; ?>"
    data-object="<?php echo htmlentities(json_encode($object)); ?>"
    onclick="buttonClicked(this);">Button</button>

<script>
    function buttonClicked(self) {
        var variable = self.getAttribute("data-variable");
        console.log(variable);

        var object = self.getAttribute("data-object");
        object = JSON.parse(object);
        console.log(object.my_value);
    }
</script>

When the button is clicked, we are sending a PHP object to the Javascript function as an argument. We are also sending a complete PHP object too. PHP objects can be sent by first converting them into JSON string format. You can learn more about the htmlentities function from PHP official documentation. Then we will convert the JSON string characters into HTML entities.

And on the Javascript side, we simply have to parse the JSON string back into a Javascript array or object. If you face any problems implementing this in your project, please let us know in the comments section.

You can also check our more tutorials on PHP.

[wpdm_package id=’1217′]

Convert date format to another – PHP, HTML

In this tutorial, we are going to teach you how to convert the date format from one to another using Javascript. We will also be adding, subtracting date by days.

Video tutorial

First, we will create a form to get the source and destination format from the user.

<form method="POST" onsubmit="return generateCode(this);">
    
    <div>
        <select name="source_format">
            <option value="">Enter source format</option>
            <option value="timestamp">Timestamp (123456789)</option>
            <option value="Y-m-d">Y-m-d (2020-08-30)</option>
            <option value="Y-m-d H:i:s">Y-m-d H:i:s (2020-08-30 14:30:18)</option>
            <option value="Y-m-d h:i:s A">Y-m-d h:i:s A (2020-08-30 02:30:18 PM)</option>
            <option value="Y-m-d h:i:s a">Y-m-d h:i:s a (2020-08-30 02:30:18 pm)</option>
            <option value="d M, Y">d M, Y (30 August, 2020)</option>
            <option value="D">D (Mon, Tue)</option>
        </select>
    </div>

    <div style="margin-top: 10px;">
        <select name="destination_format">
            <option value="">Enter destination format</option>
            <option value="timestamp">Timestamp (123456789)</option>
            <option value="Y-m-d">Y-m-d (2020-08-30)</option>
            <option value="Y-m-d H:i:s">Y-m-d H:i:s (2020-08-30 14:30:18)</option>
            <option value="Y-m-d h:i:s A">Y-m-d h:i:s A (2020-08-30 02:30:18 PM)</option>
            <option value="Y-m-d h:i:s a">Y-m-d h:i:s a (2020-08-30 02:30:18 pm)</option>
            <option value="d M, Y">d M, Y (30 August, 2020)</option>
            <option value="D">D (Mon, Tue)</option>
        </select>
    </div>

    <input type="submit" value="Generate Code" />

    <p id="output" style="display: none;"></p>
</form>

Then we will create a Javascript function that will write the PHP code to echo the date by converting it from source format to destination format.

<script>
    function generateCode(form) {

        var sourceFormat = form.source_format.value;
        var destinationFormat = form.destination_format.value;

        var html = "";
        var dateHtml = "";
        if (sourceFormat == "timestamp" && destinationFormat == "timestamp") {
            dateHtml = `echo $timestamp_value;`;
        } else if (sourceFormat == "timestamp") {
            dateHtml = `echo date('` + destinationFormat + `', $timestamp_value);`;
        } else if (destinationFormat == "timestamp") {
            dateHtml = `echo strtotime($date_value);`;
        } else {
            dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value));`;
        }
        html += `&lt;?php<br />
            <span style='margin-left: 1em;'>&emsp;` + dateHtml + `</span><br />
        ?>`;
        
        document.getElementById("output").innerHTML = html;
        document.getElementById("output").style.display = '';

        return false;
    }
</script>

The resulting output will be displayed in a paragraph. Right now we are displaying a dropdown to select a date format. But what if the user wants to write a custom format ? So we will create 2 more fields for writing custom format for source and destination.

<input type="text" style="margin-left: 10px;" name="source_format_custom" placeholder="Custom source format" />

<input type="text" style="margin-left: 10px;" name="destination_format_custom" placeholder="Custom destination format" />

Then we need to update our custom date format variables if these fields have some value.

var sourceFormat_custom = form.source_format_custom.value;
if (sourceFormat_custom != "") {
    sourceFormat = sourceFormat_custom;
}

var destinationFormat_custom = form.destination_format_custom.value;
if (destinationFormat_custom != "") {
    destinationFormat = destinationFormat_custom;
}

Add/subtract from the date

Now we need to add or subtract months, years, or days from the new date format. For this, we will create 2 dropdowns to check if the user wants to add or subtract. And second to check if he wants to add/subtract days, months, or years.

<p style="text-align: center;">Add / subtract date (optional)</p>

<div>
    <select name="addsubtract_date">
        <option value="">None</option>
        <option value="add">Add</option>
        <option value="subtract">Subtract</option>
    </select>

    <select name="addsubtract_datetype">
        <option value="years">Years</option>
        <option value="months">Months</option>
        <option value="days">Days</option>
        <option value="hours">Hours</option>
        <option value="minutes">Minutes</option>
        <option value="seconds">Seconds</option>
    </select>
</div>

<input type="number" placeholder="Enter value" name="addsubtract_datevalue" />

Now when the form is submitted, we need to get the values of both these dropdowns.

var addsubtractdate = "";
if (form.addsubtract_date.value == "add") {
    addsubtractdate = "'+ " + form.addsubtract_datevalue.value + " " + form.addsubtract_datetype.value + "'";
} else if (form.addsubtract_date.value == "subtract") {
    addsubtractdate = "'- " + form.addsubtract_datevalue.value + " " + form.addsubtract_datetype.value + "'";
}

After that, we need to make changes in every echo statement in our Javascript code to handle this add/subtract feature.

if (sourceFormat == "timestamp" && destinationFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo $timestamp_value;`;
    } else {
        dateHtml = `echo strtotime(` + addsubtractdate + `, $timestamp_value);`;
    }
} else if (sourceFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo date('` + destinationFormat + `', $timestamp_value);`;
    } else {
        dateHtml = `echo date('` + destinationFormat + `', strtotime(` + addsubtractdate + `, $timestamp_value));`;
    }
} else if (destinationFormat == "timestamp") {
    if (addsubtractdate == "") {
        dateHtml = `echo strtotime($date_value);`;
    } else {
        dateHtml = `echo strtotime(` + addsubtractdate + `, strtotime($date_value));`;
    }
} else {
    if (addsubtractdate == "") {
        dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value));`;
    } else {
        dateHtml = `echo date('` + destinationFormat + `', strtotime($date_value . ` + addsubtractdate + `));`;
    }
}

You can run the script now, and you will be able to generate the code for converting the date from one format to another. Moreover, you can also get the code for adding/subtracting days, months, or years from the resultant date. That’s how you can convert date format from one to another.

Learn how to calculate the time passed since the date in PHP and Javascript.

Calculate time passed since date – Javascript, PHP

Feel free to download the source code below.

[wpdm_package id=’1183′]

Prevent file access from URL – PHP htaccess

When developing a web application, it is very important for you to prevent file access from URL for the users. Because someone might try to download all your images and videos by directly accessing them from the URL. You must allow users to view the images and videos directly from your website instead of just letting the automated scripts download all uploaded data.

.htaccess

First, you need to create a file named “.htaccess” along with the dot “.” without the double quotes at the root folder of your project. Some operating systems hide the files that start with a dot extension.

  • In Windows, go to “view” from the top menu and check the “show hidden items” checkbox.
  • In Mac, press (command + shift + dot) (⌘ + ⇧ + .) at the same time.
  • In Ubuntu, press Ctrl + H.

Following should be the content of your .htaccess file:

# enable mod_rewrite
RewriteEngine On

# RewriteCond = define rule condition
# HTTP_REFERER = check from where the request originated
# ! = exclude
# ^ = start of string
# [NC] = case insensitive search
RewriteCond %{HTTP_REFERER} !^http://localhost:8888/tutorials/video-streaming-php [NC]

# \ = match any
# . = any character
# () = pattern, group
# $ = end of string

# [F] = forbidden, 403
# [L] = stop processing further rules
RewriteRule \.(gif|jpg|jpeg|png|mp4|mov|mkv|flv)$ - [F,L]

At line #9, you must place your website base URL without forwarding the slash “/” at the end. Using htaccess, you can also prevent “.env” files from accessing in your Laravel application. Follow this for more.

Access from code only

Now if you try to access the file directly from the URL, you will get a 403 Forbidden error. But you can easily access it from your code like this:

<video src="video.mp4" controls></video>

This prevent file access from the URL but you can still see it in the browser. However, the user can still manually download the video file. But it prevents the automated scripts to download all the files from your server directory.

Preview Laravel email before sending – PHP, AJAX

Either you are sending an email in Laravel via normal form POST request or via AJAX. This tutorial will help you add functionality where you can preview Laravel email before sending it. If you are adding functionality to your Laravel project where you need to send an email, it is very important during the development to check the preview of mail before sending.

Normally, when you receive the email in your inbox, you can see how it will look to users. But if you haven’t set up your SMTP server for sending emails, then following this tutorial will save you a lot of time during development.

Create a new Laravel project

To create a new Laravel project, open your command prompt or Terminal and run the following command in it:

composer create-project laravel/laravel example-app

This will create a folder named “example-app”. Now, you need to enter this folder using the following command:

cd example-app

When your Terminal is inside this folder, run the following command to start the server:

php artisan serve

Typically, this starts your project at host 127.0.0.1 and port 8000. So you can access it from the URL:

http://127.0.0.1:8000

Create controller and mailer

Create a new controller using the following command, you can also use your own controller if you want:

php artisan make:controller UserController

Now, open your “routes/web.php” file and create a new route:

// include controller
use App\Http\Controllers\UserController;

// create route
Route::get("/send-mail", [UserController::class, "send_mail"]);

Create a mailer to send mails by running the following command in your Terminal:

php artisan make:mail SendMail

Now, we need to create the following function in “App\Http\Controllers\UserController”:

use Mail;
use App\Mail\SendMail;

class UserController extends Controller
{
    // create method
    public function send_mail()
    {
        // send email
        // preview with dynamic variable data

        $data = "This is a variable.";

        // pass as a parameter
        $mailable = new SendMail($data);
        // Mail::to("recipient@gmail.com")->send($mailable);

        // preview email
        return $mailable->render();
    }
}

Following will be the content of your “App\Mail\SendMail”. You can add all the variables you want to pass in this mailer:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendMail extends Mailable
{
    use Queueable, SerializesModels;

    // class data member
    public $data;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    // parametrized constructor
    public function __construct($data)
    {
        // assign value
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // create this folder mails
        // and file test.blade.php

        // pass value in view
        return $this->view('mails/test', [
            "data" => $this->data
        ]);
    }
}

At line #40, we need to create a new file in views folder, “resources/views/mails/test.blade.php” and in this file you can write the content of your email. For the sake of understanding, I am writing simple text with variables:

<h1>This is mail:</h1>

<!-- display in mail view -->
Data = {{ $data }}

If you access your browser at “http://127.0.0.1:8000/send-mail”, you will see the content of email with all variables rendered on it.

Preview email from AJAX

If you are sending an email via an AJAX request, then it might be difficult for you during the development to check how the email will look like. You might be sending an email on each test and viewing it from your Gmail inbox to preview the email. But there is a shorter method to do that, and it will surely save your time.

First, create a new route that will render a view file.

// routes/web.php
Route::get("/send-mail-ajax", function () {
    // render view
    return view("send_mail_ajax");
});

Create a file named “send_mail_ajax.blade.php” inside the “resources/views” folder and paste the following code into it:

<!-- meta tag for CSRF token -->
<meta name="_token" content="{{ csrf_token() }}">

<!-- hidden input field for base url -->
<input type="hidden" id="base_url" value="{{ url('/') }}" />

<!-- send ajax -->
<script>
    var ajax = new XMLHttpRequest();
    ajax.open("POST", document.getElementById("base_url").value + "/send-mail-ajax", true);

    // when the response is received
    ajax.onreadystatechange = function () {
        if (this.readyState == 4) {
            if (this.status == 200) {
                // display in browser
                document.write(this.responseText);
            }

            // handler error
            if (this.status == 500) {
                console.log(this.responseText);
            }
        }
    };

    var formData = new FormData();
    formData.append("_token", document.querySelector("meta[name=_token]").content);
    ajax.send(formData);
</script>

We have created a meta tag for saving CSRF token which is required for each POST request in Laravel, and a hidden input field that will save the website’s base URL. Then we are sending an AJAX request, and when the response is successfully received then we are displaying that in current web page.

Don’t worry, it will be used just during the development process. Once it is reviewed, then you can comment out that code at line #17.

Create a POST route in “routes/web.php” and it will use the same method in UserController, only the method is set to POST:

// create route
Route::post("/send-mail-ajax", [UserController::class, "send_mail"]);

Try to access the URL at “http://127.0.0.1:8000/send-mail-ajax”, you will first view an empty page then after few seconds, you will see the content of email in your web page.

Let me know if you need any help in following this tutorial.

[wpdm_package id=’1171′]

Hide HTML from inspect element – PHP

In this article, we are going to discuss, how you can hide HTML tags from inspect element. It prevents the HTML tags from rendering in the browser so they won’t be visible in “View page source” or “inspect element”.

When developing a web application, sometimes you write a code to do something. But after some time, you find a better algorithm for that solution, and your comment on the previous code, and apply the new algorithm.

We comment on the code because we feared that we might need that code somewhere else in the project and we do not want to waste our time and effort we put into writing that code.

The only problem with commenting on the code is that the HTML tags created with that code are still visible from inspect element. They might not be sensitive but sometimes you just do not want it to show to the user. Someone with good coding knowledge can see your commented HTML codes.

Demonstration

I am going to create a loop from 1 to 10 and create a paragraph in each iteration. You might be displaying data from the database using foreach or while loop and might be displaying in tables, cards, or any other layout. After that, I am going to comment on the paragraph inside the loop.

<?php for ($a = 1; $a <= 10; $a++) { ?>
    <!-- <p>I am commented <?php echo $a; ?></p> -->
<?php } ?>
 
<p>I am normal.</p>

Right now, you will only see the “I am normal” text, but if you right-click on the empty area of your screen and click “View page source”, you will see the commented paragraphs.

Commented code – PHP

To prevent those commented paragraphs to appear in “page source” or “inspect element”, simply wrap the code you don’t want to display in the if condition. And set the condition to never be true.

<?php for ($a = 1; $a <= 10; $a++) { ?>
    
    <?php if (false) { ?>
        <p>I am commented <?php echo $a; ?></p>
    <?php } ?>

<?php } ?>

<p>I am normal.</p>

If you open the page source now, you will no longer see the commented paragraphs. That is how you can hide HTML from inspect element.

Code not executed – PHP

Prevent browser cache from CSS, JS, and image files

In this article, I am going to teach you, how you can prevent the browser cache from keep displaying the old content. We will ask the browser to update your cached files and fetch the fresh content. Suppose, you have written a Javascript file named “script.js”. Now, you added some functionality code in that file, or change the algorithm of some function. You have updated the file on a live server. But your changes will not affect your user’s side if their browser has cached that JS file.

How browser cache works

In that case, you have to forcefully tell the browser to fetch the updated file instead of serving the cached file. The browser cache works in such a manner that, whenever a CSS, JS, or image file is rendered in the client’s browser, the browser stores the URL of that file in its cache along with its content. When the user refreshes the page, all <style>, <script> and <img /> tags request the resources using the “href” and “src” attribute. The browser checks if the requested URL already exists in its cache database. If “yes” then it (browser) fetches its content from the cache database and serves it.

That’s why most of the time your website users are not able to view the updated content. As you now know the problem, you now have a solution. The browser searches the URL in its cache database. So, whenever you update your file, simply change the URL by appending a query parameter at the end of the URL. For example, if you have an image tag which is displaying an image named “1.jpg”, like this:

<img src="1.jpg" />

Skip cache and fetch fresh content

Now, you have replaced the “1.jpg” image with a new image and you want the user’s to view the new image, then simply change the URL like this:

<img src="1.jpg?v=1" />

Here, “v” stands for “version” but you can use any parameter you want. Make sure to append it with “?” so it will be treated as a parameter. Its sole purpose is to tell the browser that the URL has now changed. So, it must fetch the updated resource instead of from the cache database. Now, every time you change the image file, simply increment this version value like “?v=2” and the image will be updated for all users next time they refresh the page.

If you want the browser to never cache a specific resource, for example, you want the web browser to always serve the updated “1.jpg” file. In that case, append the PHP timestamp in the query parameter. A PHP timestamp is the number of seconds passed from the 1st of January 1970 till the current time.

<img src="1.jpg?v=<?php echo time(); ?>" />

This will prevent the browser to never cache this image. Because every time user sends a request for this resource, the URL will change each time.

See this in action

PayPal and Stripe – Javascript

Whether you are creating an E-commerce website or simply wanted to receive payments from your website using PayPal and Stripe, this script already contains all the source code you need to show Stripe and PayPal payment buttons and receive payments directly in your Stripe and PayPal accounts.

It also has a full shopping cart implementation, where you can add products to the cart, update quantities, remove products from the cart and move to checkout.

Demo

Home page

Here you can add products to the shopping cart and also you can remove products from the shopping cart.

When you add or remove a product from the shopping cart, you will see the shopping cart badge on top updating its values in real-time.

Shopping cart

On clicking the above “Cart” button you will be redirected to the shopping cart page where you can change the number of products and can also remove the product from the shopping cart.

You can also see the grand total at the bottom right that changes in real-time as you change the quantity of product or when you remove a product from the shopping cart.

Checkout

Here you can make the payment using Stripe or Paypal.

Fully documented code

Comments have been added with each line of code for explanation.

Separate file for each function

To manage the code, each payment method is separated in its own file. So you can easily change and modify the code as per your needs.