Email verification using one time url in php

If you want to sell digital goods on the website, then a temporary download link is a very convenient source. Because it offers you a secure way to share the download link of digital products. Also, the user permits downloading the file only for a single time; after the download, the link is expired or deleted. Therefore, the single time download link is perfect for giving a digital product (code, music, video, etc.) to an only person and remove the link once you download your product.

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

There is no need to manually monitor the download activity to change the download link with the single-use download link . In its place, the download link will expire immediately after the first download. In this tutorial, we will explain to you how to create a one-time download link in PHP and implement the temporary download URL feature on the web application using PHP.

Читайте также:  Python attributeerror nonetype object has no attribute text

The example code permits you to make a unique link to download the file from the server. This link will give access to the user to download one time. Also, the link contains a time limit, and it will expire automatically after the specified expiry date.

For instance, you want to sell an eBook on your website. You will sell the eBook on your site for $5 so, you could use our script to access that user to download the respective eBook only one-time. The download link will give them a limited number of seconds/minutes/hours/days/week/years to claim their download.

The following process will be followed to implement the temporary download link functionality in PHP .

  • Create a download link.
  • Make a protected directory to store keys.
  • Create a file and write a unique key to it.
  • On download request, token key, and expiration time is validated.
  • Force the browser to download the file.

Configurations (config.php)

Let’s discuss the configuration variables with the given file.

  • $files – An array of the files with the unique ID.
    • You can specify the different name of the file being downloaded. It helps to protect the original data.
    • You can specify the local or remote file path.
     array( 'content_type' => 'application/zip', 'suggested_name' => 'codex-file.zip', 'file_path' => 'files/test.zip', 'type' => 'local_file' ), 'UID67890' => array( 'content_type' => 'audio/mpeg', 'suggested_name' => 'music-codex.mp3', 'file_path' => 'https://www.dropbox.com/XXXXXXX/song.mp3?dl=1', 'type' => 'remote_file' ), ); // Base URL of the application define('BASE_URL','http://'. $_SERVER['HTTP_HOST'].'/'); // Path of the download.php file define('DOWNLOAD_PATH', BASE_URL.'download.php'); // Path of the token directory to store keys define('TOKEN_DIR', 'tokens'); // Authentication password to generate download links define('OAUTH_PASSWORD','ALLSWEB'); // Expiration time of the link (examples: +1 year, +1 month, +5 days, +10 hours) define('EXPIRATION_TIME', '+5 minutes');

    index.php

    In this file, you will see a link to navigate to the download link creation file. You need to specify the authentication password in the query string of the link.

    Create Temporary Download Link (generate.php)

    This file will make a temporary download link and lists the links on the web page. The query string contains the authentication password. And there is a need to match with the specified in the config.php file. Otherwise, it will render a 404 error.

    • Get the authentication password from the query string.
    • Validate the authentication password.
    • Encode the file ID with base64_encode() in PHP.
    • Generate a new unique key with a timestamp using uniqid() in PHP.
    • Generate download link with file ID and key.
    • Create a protected directory to store keys.
    • Write the key in a file and put it in the token directory.
    • List all the download links on the web page.

    This file downloads the file by the temporary download link.

    • Acquire the file ID & key from the query string of the URL.
    • Acquire the time from the key and calculate link expiration time.
    • Recover the keys from the tokens file.
    • When you found a match through the key, delete it.
    • Put the remaining keys back into the tokens file.
    • If the match found and the link is not expired, force the browser to download the file.

    > // Put the remaining keys back into the tokens file file_put_contents(TOKEN_DIR.’/keys’,$keys); // If match found and the link is not expired if($match !== false && $currentTime \»»); fpassthru($file); >else< header("Content-Description: File Transfer"); header("Content-type: "); header("Content-Disposition: attachment; filename=\"\""); header("Content-Length: " . filesize($filePath)); header('Pragma: public'); header("Expires: 0"); readfile($filePath); > exit; >else < $response = 'Download link is not valid.'; >>else < // If the file has been downloaded already or time expired $response = 'Download link is expired.'; >?>

    Conclusion

    Firstly, with the help of our sample script, you can sell digital goods on the website with a temporary download link . Secondly, the single time download link is perfect for giving a digital product (code, music, video, etc.) to an only person and remove the link once he/she downloads the product. At last, our example code allows you to create a unique link to download the file from the server.

    Источник

    One time url in php for Email verification

    Generating One time url for email verification

    A one time url is a temporary link so designed that it can be used only once. It is used for variety of purposes like email verification link, one time download link, reset forgot password link etc.

    Here we will talk about email verification by generating one-time urls. We can also put an expiry time limit on the validity of url, setting it to expire after 24 hours or more as per our needs.

    How to generate one time url in php?

    We will use some php function to generate a secured token and embed that token into url and send it to email id as an email verification link. Next we push that token into the database for user verification later. On receiving the url if the user clicks on that sent link, we will retrieve the token from the url and match it with the stored token in the database. If a match is found user is verified and we delete that token from the database to escape misusing it again.

    We will use uniqid() function in php to generate a unique id based on the randomly generated username.

    This will generate a random unique id based on username and current time in microseconds. If security is not a issue for our website we can use this function to generate a token and send it with the url as one time email verification link.

    But if we are more concerned about security issue we can use an additional php function sha1() or md5() to generate cryptographically secured token. Sha1() is more secured than md5() but slower in comparison to md5(). So in high security applications use sha1() only.

    1. Get user Email id to send one time url as email verification link
    2. Check for valid email id and request server to generate one time url
    3. Server generates token, stores it in database and forwards the generated link to the email id.
    4. User when visits the link gets verified. Now delete the token from database.

    Get Email id to send one time url

    The user enters his email id to receive otp. A script has been written to check for invalid email id which returns an error on entering an invalid email id.

              
    Email Verification using one time url in php


    email verification in php using otp

    Makes an ajax request to the server for one time url generation

    function generateUrl() < $(".err").html("").hide(); var email = $("#email").val(); var name = $("#name").val(); if(name.length !== 0) < var input =< "name" : name, "email" : email, "action" : "generate_url" >$("#loading-image").show(); $.ajax(< url : 'controller.php', type : 'POST', dataType : 'json', data : input, success : function(response) < $(".container").html(response.message); >, complete : function() < $("#loading-image").hide(); >, error : function() < $(".container").html("Error"); >>); > else $("#message1").html("Enter your name").css('color','red'); >

    Server generates token, saves it in database, embeds it in url and forwards it to user email id

    The server generates a unique token using the email id of the user and stores the token in the database. After that, it creates a unique one-time link embedding the token in the url and forwards the link to the user email id calling php mail() function.

    processEmailVerification(); > function processEmailVerification() < switch ($_POST["action"]) < case "generate_url": $email = $_POST['email']; $token = sha1(uniqid($email,true)); // this will generate unique 40 character long secured token $db = mysqli_connect('localhost', 'username', '(password)', 'database name'); //here check for email id ia already registered or not $query = "INSERT INTO new_pending_users (email,token) VALUES ('$email','$token')"; $result = mysqli_query($db, $query); if ($result === FALSE) < die(mysqli_error()); exit(); >else< $url = "https://djtechblog.com/php/projects/one-time-url/user-verification.php?token=$token";// send this url to user via email $message = "Thankyou for registraion. kindly go to this " . $url . " to validate your email id."; $sub = "Activate your account"; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= 'From: Dj Techblog ' . "\r\n"; $retval = mail($email,$sub,$message,$headers); if($retval = true) echo json_encode(array( "type" =>"success", "message" => "Verification link sent to email id")); else echo json_encode(array( "type" =>"error", "message" => "Error")); > break; > > > $controller = new Controller(); ?>

    User verifies the email id visiting the email verification link

    Now we assume that the user receives the email verification link and uses that link to verify his email id. This time server retrieves the token from the url and matches it with the token stored in the database, if match found email id verified otherwise server discards the token as an invalid or expired token. If the user is verified successfully we also delete the token so that it cant be reused again.

    $/i', $_GET["token"])) < $token = $_GET["token"]; >else < throw new Exception("Valid token not provided."); >$db = mysqli_connect('localhost', 'usrname', '(password)', 'database'); $query = "SELECT * FROM new_pending_users WHERE token='$token' LIMIT 1"; $result = mysqli_query($db, $query); if ($result === FALSE) < die(mysqli_error($connect)); >$user = mysqli_fetch_assoc($result); if($user) < if ($user['token'] === $token) < // delete token so it can't be used again $db0 = mysqli_connect('localhost', 'username', '(password)', 'dtabase'); $query0 = "DELETE FROM new_pending_users WHERE token='$token' LIMIT 1"; $result0 = mysqli_query($db0, $query0); if($result0 === TRUE)< // do one-time action here, like activating a user account // or deleting the record from new_pending_users and creating a new record in registered_users. echo "Email verification successful"; >else exit; > > ?>

    If you like this article, share this knowledge with your friends. It will inspire me to write more.

    • Mobile number verification by otp sms in php using Textlocal
    • simple login form in ajax and php using mobile number
    • Instamojo payment gateway integration in php
    • PayUmoney payment gateway integration in php
    • Email verification in php using otp
    • Generating random numbers in php
    • Generating cryptographically secured numbers in php
    • Generating One time url for email verification
    • Create a php login form using Mysql Database
    • Everything about sessions in php
    • Reset forgot password by sending one time password reset link to Email id
    • Register user form | Update user details form in php | Update mysql database using php
    • Upload a image file in php and display as profile picture
    • Generate OTP and store it into session variable for futher use/ no use of database
    • How to make sms otp expire in php
    • Login-logout using php sessions
    • Regsiter user with admin approval in php
    • Admin panel with Category Subcategory setup for ecommerce website in php
    • File upload via ajax call in php
    • Admin panel to add update delete products for ecommerce webiste in php
    • Add a shopping cart to ecommerce website in php

    I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

    Reach to me in the contact us form below

    Источник

    How to Create One Time Temporary Download Link with Expiration in PHP

    Tutorials Website

    Temporary download link is extremely helpful to offer Digital products on the site. It gives a safe method to share the download link of the advanced items. The client permits downloading the record just a single time, after the download the link is terminated or evacuated. The one-time download link is perfect to give an advanced item (code, music, video, and so on) to a solitary individual and terminate the link once the item is downloaded.

    With the single-utilize download link, you don’t have to physically screen the download action keeping in mind the end goal to change the download link. Rather, the download link will be terminated quickly after the primary download. In this instructional exercise, we will demonstrate to you proper methodologies to produce one-time download link in PHP and execute the temporary download URL usefulness on the web application utilizing PHP.

    The illustration code enables you to create a one of a kind link to download the document from the server. This link will enable the client to download one time. Likewise, the link will have a termination time and it will be lapsed after the predefined expiry date.

    For instance, you need to offer an eBook on your site. The eBook is sold on your site for $5, you could utilize our content to enable that client to download the separate eBook just a single time. The download link will give them a predetermined number of seconds/minutes/hours/days/week/years to assert their download.

    Источник

Оцените статью