PHP – CodingNepal https://www.codingnepalweb.com CodingNepal is a blog dedicated to providing valuable and informative content about web development technologies such as HTML, CSS, JavaScript, and PHP. Thu, 18 May 2023 17:03:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 PHP vs Node.js – Which is best for Backend Development? https://www.codingnepalweb.com/php-vs-nodejs-which-is-best-for-backend/ https://www.codingnepalweb.com/php-vs-nodejs-which-is-best-for-backend/#comments Tue, 27 Dec 2022 11:48:18 +0000 https://www.codingnepalweb.com/?p=3736 PHP vs Node.js Which is best for Backend Development

There are numerous programming languages available for backend development, but two of the most commonly used are PHP and Node.js. These languages are popular choices for building backend web applications and websites, but they each have their own unique set of strengths and weaknesses.

To help you decide which technology is the best fit for your backend development project, this blog will provide an overview of PHP and Node.js. We’ll cover what these languages are, what they are used for, and the critical differences between them.

By understanding the capabilities and features of each technology, you can make an informed decision about which one is the best fit for your specific project needs and requirements.

But before continuing this blog, there is also a lot of confusion among frontend developers when choosing the best framework for frontend development, if you’re one of them, this blog might be helpful to you: React vs Angular – Which is best for Frontend Development?

What is PHP, and what does it do?

What is PHP, and what does it do

PHP, which stands for “Hypertext Preprocessor,” is a server-side scripting language that is widely used for creating dynamic web applications and websites. It is executed on the server and generates HTML (HyperText Markup Language), which is then sent to the client’s web browser.

PHP was developed by Rasmus Lerdorf in 1994 and has since become a popular choice for building dynamic web pages. It is well-known for its ease of use, and it has a large ecosystem of frameworks such as Laravel, CodeIgniter, Symfony, etc., which offer a range of tools and features to help developers build robust and scalable web applications easily.

PHP has numerous advantages, some of which are listed below:

  • It is easy to learn and use even if you’re a newbie in backend development.
  • It has a large ecosystem of powerful libraries and frameworks available.
  • It is compatible with a wide range of platforms including Linux, and Windows.
  • It has built-in support for popular databases that make data easy to read and store.
  • It has many built-in security features such as input validation and sanitization.
  • It has a huge and active community of developers.

What is Node.js, and what does it do?

What is Node.js, and what does it do

Node.js is a JavaScript runtime environment that enables the execution of JavaScript code on the server side, outside of a web browser. It was developed by Ryan Dahl in 2009 and built using the V8 JavaScript engine, which is also used by the Chrome web browser.

Node.js is designed to be lightweight, efficient, and well-known for its fast performance and scalability. As a result, it is ideal for creating real-time web applications such as chat applications and online games. Node.js is also a cross-platform technology, which means it can be used on various operating systems, including Windows, macOS, and Linux.

Node.js has numerous advantages, some of which are listed below:

  • It is easy to learn and use, especially if you’re familiar with JavaScript.
  • It is efficient and well-suited for building real-time applications and APIs.
  • It uses an event-driven, non-blocking I/O model that makes it asynchronous.
  • It is a cross-platform technology that works on a variety of platforms.
  • It can be used for both the front-end and back-end of web development.

Differences between PHP and Node.js

There are several differences between PHP and Nod.js. But some key differences between them are pointed out below.

PHP Node.js
It is a server-side scripting language. It is a JavaScript runtime environment.
It uses a traditional synchronous programming model. It uses an event-driven, non-blocking I/O model.
It has a large ecosystem of libraries and frameworks. It has a more limited set of tools and libraries.
It is slower and less efficient than Node.js. It is faster and more efficient than PHP.
It is used for server-side rendering of web pages. It is used for building server-side applications and APIs.
It is used in collaboration with relational databases like MySQL. It works perfectly with NoSQL (not only SQL) databases like MongoDB.

Which should you use, PHP or Node.js?

As you are now aware, what are PHP and Node.js, their pros and cons, and the differences between them? The decision of which technology you should use will depend on your specific project requirements and the resources and skills that are available to you.

PHP can be the best choice if you are a newbie and want to build a simple, traditional web application or website because it is easy to learn and has a large number of frameworks. But if you are familiar with JavaScript and want to build real-time, high-performance web applications or APIs, then Node.js might be a better choice for you.

Ultimately, each technology has its own advantages and disadvantages. So, before selecting any of these technologies for your backend development, it is important to consider your project requirements, objectives, and your personal interests and skills.

If you found this blog useful, please consider sharing it with others to help them benefit as well. Thank you for your support and keep visiting our site.

]]>
https://www.codingnepalweb.com/php-vs-nodejs-which-is-best-for-backend/feed/ 5
File Upload with Progress Bar HTML CSS & JavaScript https://www.codingnepalweb.com/file-upload-with-progress-bar-html-javascript/ https://www.codingnepalweb.com/file-upload-with-progress-bar-html-javascript/#comments Fri, 16 Jul 2021 10:46:40 +0000 https://www.codingnepalweb.com/?p=2172 File Upload with Progress Bar HTML CSS & JavaScript

Hey friends, today in this blog you’ll how to Upload File with Progress in HTML CSS & JavaScript. Earlier, I have shared a blog on how to create Drag & Drop or Browse File Upload Feature using JavaScript. So I’ll not add this feature to this File Uploader.

In this project (File Upload JavaScript with Progress Bar), as you can see in the preview image, there are two pictures of the file uploader. In the first one, there is a dashed border container with an icon and text to browse the file to upload.

When you click on this container an open file window will open and you can select any file to upload. Once you select the file then you can see in the second picture, there is shown your file uploading status with filename, uploaded percent, progress bar, etc. and there is the history of the uploaded files with filename, size, etc.

Video Tutorial of File Upload JavaScript with Progress Bar

 
In the video, you have seen the demo of the File Upload with Progress Bar and how I created it using HTML CSS, JavaScript & PHP. I’ve used PHP as a backend language to receive the user file and save or upload it. You can also use any other server-side language for it such as NodeJS.

I hope you liked this File Uploader and want to get source codes or files of this project but don’t worry I have given codes and source files download link to the bottom of the page. But before copy-paste the codes or download files, let’s talk about the important codes and concepts behind creating this file uploader.

In the JavaScript file, I used the change event to get the user selected filename and then called the uploadFile(filename) function with passing the filename as an argument. Inside uploadFile() function, using Ajax I sent the selected file to the PHP. As you can have seen on the codes, I used upload property and progress event to get file loaded value and file total size.

In the PHP file, I received the file and added the current time before the filename to make the filename dynamic and moved this file to the files folder using PHP inbuilt function move_uploaded_file.

You might like this:

File Upload JavaScript with Progress Bar [Source Codes]

To create this project (File Upload JavaScript). First, you need to create four Files: HTML, CSS, JavaScript & PHP files. After creating these files just paste the following codes into your file. Remember, you’ve to create a folder with php name and inside this folder, you’ve to create php file a name of upload.php and a files folder to saved all uploaded files.

If you didn’t understand then you can download the source code files of this File Upload JavaScript with Progress Bar from the given download button.

First, create an HTML file with the name of index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with .html extension.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Upload JavaScript with Progress Ba | CodingNepal</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
  <div class="wrapper">
    <header>File Uploader JavaScript</header>
    <form action="#">
      <input class="file-input" type="file" name="file" hidden>
      <i class="fas fa-cloud-upload-alt"></i>
      <p>Browse File to Upload</p>
    </form>
    <section class="progress-area"></section>
    <section class="uploaded-area"></section>
  </div>

  <script src="script.js"></script>

</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #6990F2;
}

::selection{
  color: #fff;
  background: #6990F2;
}
.wrapper{
  width: 430px;
  background: #fff;
  border-radius: 5px;
  padding: 30px;
  box-shadow: 7px 7px 12px rgba(0,0,0,0.05);
}
.wrapper header{
  color: #6990F2;
  font-size: 27px;
  font-weight: 600;
  text-align: center;
}
.wrapper form{
  height: 167px;
  display: flex;
  cursor: pointer;
  margin: 30px 0;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border-radius: 5px;
  border: 2px dashed #6990F2;
}
form :where(i, p){
  color: #6990F2;
}
form i{
  font-size: 50px;
}
form p{
  margin-top: 15px;
  font-size: 16px;
}

section .row{
  margin-bottom: 10px;
  background: #E9F0FF;
  list-style: none;
  padding: 15px 20px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
section .row i{
  color: #6990F2;
  font-size: 30px;
}
section .details span{
  font-size: 14px;
}
.progress-area .row .content{
  width: 100%;
  margin-left: 15px;
}
.progress-area .details{
  display: flex;
  align-items: center;
  margin-bottom: 7px;
  justify-content: space-between;
}
.progress-area .content .progress-bar{
  height: 6px;
  width: 100%;
  margin-bottom: 4px;
  background: #fff;
  border-radius: 30px;
}
.content .progress-bar .progress{
  height: 100%;
  width: 0%;
  background: #6990F2;
  border-radius: inherit;
}
.uploaded-area{
  max-height: 232px;
  overflow-y: scroll;
}
.uploaded-area.onprogress{
  max-height: 150px;
}
.uploaded-area::-webkit-scrollbar{
  width: 0px;
}
.uploaded-area .row .content{
  display: flex;
  align-items: center;
}
.uploaded-area .row .details{
  display: flex;
  margin-left: 15px;
  flex-direction: column;
}
.uploaded-area .row .details .size{
  color: #404040;
  font-size: 11px;
}
.uploaded-area i.fa-check{
  font-size: 16px;
}

Third, create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with .js extension.

const form = document.querySelector("form"),
fileInput = document.querySelector(".file-input"),
progressArea = document.querySelector(".progress-area"),
uploadedArea = document.querySelector(".uploaded-area");

form.addEventListener("click", () =>{
  fileInput.click();
});

fileInput.onchange = ({target})=>{
  let file = target.files[0];
  if(file){
    let fileName = file.name;
    if(fileName.length >= 12){
      let splitName = fileName.split('.');
      fileName = splitName[0].substring(0, 13) + "... ." + splitName[1];
    }
    uploadFile(fileName);
  }
}

function uploadFile(name){
  let xhr = new XMLHttpRequest();
  xhr.open("POST", "php/upload.php");
  xhr.upload.addEventListener("progress", ({loaded, total}) =>{
    let fileLoaded = Math.floor((loaded / total) * 100);
    let fileTotal = Math.floor(total / 1000);
    let fileSize;
    (fileTotal < 1024) ? fileSize = fileTotal + " KB" : fileSize = (loaded / (1024*1024)).toFixed(2) + " MB";
    let progressHTML = `<li class="row">
                          <i class="fas fa-file-alt"></i>
                          <div class="content">
                            <div class="details">
                              <span class="name">${name} • Uploading</span>
                              <span class="percent">${fileLoaded}%</span>
                            </div>
                            <div class="progress-bar">
                              <div class="progress" style="width: ${fileLoaded}%"></div>
                            </div>
                          </div>
                        </li>`;
    uploadedArea.classList.add("onprogress");
    progressArea.innerHTML = progressHTML;
    if(loaded == total){
      progressArea.innerHTML = "";
      let uploadedHTML = `<li class="row">
                            <div class="content upload">
                              <i class="fas fa-file-alt"></i>
                              <div class="details">
                                <span class="name">${name} • Uploaded</span>
                                <span class="size">${fileSize}</span>
                              </div>
                            </div>
                            <i class="fas fa-check"></i>
                          </li>`;
      uploadedArea.classList.remove("onprogress");
      uploadedArea.insertAdjacentHTML("afterbegin", uploadedHTML);
    }
  });
  let data = new FormData(form);
  xhr.send(data);
}

Last, create a PHP file with the name of message.php and paste the given codes into your PHP file. Remember, you’ve to create a file with .php extension.

<?php
  $file_name =  $_FILES['file']['name'];
  $tmp_name = $_FILES['file']['tmp_name'];
  $file_up_name = time().$file_name;
  move_uploaded_file($tmp_name, "files/".$file_up_name);
?>

That’s all, now you’ve successfully created a File Upload JavaScript with Progress Bar. If your code doesn’t work or you’ve faced any error/problem, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it. Once you extracted it, move this project folder inside htdocs or www folder of your XAMPP or WAMP installation directory then start the apache server and run this file on your browser.

Note: In the video, I have manually slowed the Internet connection to upload files slowly and to show you the progress of uploading. So the small size file like images also taken time to upload but when you download this project and upload the image file then you might not see the progress bar because your file will be uploaded too fast.

 

]]>
https://www.codingnepalweb.com/file-upload-with-progress-bar-html-javascript/feed/ 60
How to Create a Working Contact Form in PHP https://www.codingnepalweb.com/create-working-contact-form-in-php/ https://www.codingnepalweb.com/create-working-contact-form-in-php/#comments Sat, 19 Jun 2021 14:13:25 +0000 https://www.codingnepalweb.com/?p=2127 Create a Working Contact Form in PHP

Hey friends, today in this blog you’ll learn how to create a Working Contact Form in PHP. I’ll use HTML CSS JavaScript & PHP to create this working contact form. In the earlier blog, I have shared how to send email using PHP from Localhost and it’s a time to create a contact form in PHP.

Contact Form is an important element on a page that allows users to communicate with the website owner. This contact form has some input fields for filling in name, email address, subject, message, etc. You can add or remove fields according to your site requirements.

In this project [Contact Form in PHP], as you can in the image preview, there is a contact form with a heading, input fields, button, and status text. This text is dynamic means this text change according to the form status and informs the user about their message is sending, sent, or failed. This contact form is fully validated means the user can’t send a message without entering a valid email address and message. You can watch a demo of this contact form or a tutorial of it.

Video Tutorial of Working Contact Form in PHP

 
In the video, you have seen the demo of this contact form and how I created it using HTML CSS JavaScript & PHP. I hope you like this contact form in PHP and want to get source codes but don’t worry I’ve provided the codes of this project at the bottom of this page and you can easily copy-paste or download the code files.

But first, read this blog till the end to understand the codes and concepts behind creating this contact form in php. Well, I used ajax in JavaScript so this contact form isn’t refreshed when your message is about sending, failed, or sent. Using ajax I sent all form data [name, email address, phone, website, and message] to the PHP file and in the PHP file, I received all.

After I got all user data, first I checked that user has entered a valid email and message or not because these two fields are mandatory. If the user has entered their valid email and message then using PHP inbuilt mail() function I sent these data to the provided email address that’s it.

If a message not sent due to an invalid email, empty message field, or network issue then I sent an error message with the reason, and using JavaScript I displayed this error on the contact form.

You might like this:

Create a Working Contact Form in PHP [Source Codes]

To create this project [Contact Form in PHP]. First, you need to create four Files: HTML, CSS, JavaScript & PHP files. After creating these files just paste the following codes into your file. You can also download the source code files of this Contact Form in PHP & JavaScript from the given download button.

First, create an HTML file with the name of index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with .html extension.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Contact Form in PHP | CodingNepal</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
  <div class="wrapper">
    <header>Send us a Message</header>
    <form action="#">
      <div class="dbl-field">
        <div class="field">
          <input type="text" name="name" placeholder="Enter your name">
          <i class='fas fa-user'></i>
        </div>
        <div class="field">
          <input type="text" name="email" placeholder="Enter your email">
          <i class='fas fa-envelope'></i>
        </div>
      </div>
      <div class="dbl-field">
        <div class="field">
          <input type="text" name="phone" placeholder="Enter your phone">
          <i class='fas fa-phone-alt'></i>
        </div>
        <div class="field">
          <input type="text" name="website" placeholder="Enter your website">
          <i class='fas fa-globe'></i>
        </div>
      </div>
      <div class="message">
        <textarea placeholder="Write your message" name="message"></textarea>
        <i class="material-icons">message</i>
      </div>
      <div class="button-area">
        <button type="submit">Send Message</button>
        <span></span>
      </div>
    </form>
  </div>

  <script src="script.js"></script>

</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body{
  display: flex;
  padding: 0 10px;
  min-height: 100vh;
  background: #0D6EFD;
  align-items: center;
  justify-content: center;
}
::selection{
  color: #fff;
  background: #0D6EFD;
}
.wrapper{
  width: 715px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 10px 10px 10px rgba(0,0,0,0.05);
}
.wrapper header{
  font-size: 22px;
  font-weight: 600;
  padding: 20px 30px;
  border-bottom: 1px solid #ccc;
}
.wrapper form{
  margin: 35px 30px;
}
.wrapper form.disabled{
  pointer-events: none;
  opacity: 0.7;
}
form .dbl-field{
  display: flex;
  margin-bottom: 25px;
  justify-content: space-between;
}
.dbl-field .field{
  height: 50px;
  display: flex;
  position: relative;
  width: calc(100% / 2 - 13px);
}
.wrapper form i{
  position: absolute;
  top: 50%;
  left: 18px;
  color: #ccc;
  font-size: 17px;
  pointer-events: none;
  transform: translateY(-50%);
}
form .field input,
form .message textarea{
  width: 100%;
  height: 100%;
  outline: none;
  padding: 0 18px 0 48px;
  font-size: 16px;
  border-radius: 5px;
  border: 1px solid #ccc;
}
.field input::placeholder,
.message textarea::placeholder{
  color: #ccc;
}
.field input:focus,
.message textarea:focus{
  padding-left: 47px;
  border: 2px solid #0D6EFD;
}
.field input:focus ~ i,
.message textarea:focus ~ i{
  color: #0D6EFD;
}
form .message{
  position: relative;
}
form .message i{
  top: 30px;
  font-size: 20px;
}
form .message textarea{
  min-height: 130px;
  max-height: 230px;
  max-width: 100%;
  min-width: 100%;
  padding: 15px 20px 0 48px;
}
form .message textarea::-webkit-scrollbar{
  width: 0px;
}
.message textarea:focus{
  padding-top: 14px;
}
form .button-area{
  margin: 25px 0;
  display: flex;
  align-items: center;
}
.button-area button{
  color: #fff;
  border: none;
  outline: none;
  font-size: 18px;
  cursor: pointer;
  border-radius: 5px;
  padding: 13px 25px;
  background: #0D6EFD;
  transition: background 0.3s ease;
}
.button-area button:hover{
  background: #025ce3;
}
.button-area span{
  font-size: 17px;
  margin-left: 30px;
  display: none;
}
@media (max-width: 600px){
  .wrapper header{
    text-align: center;
  }
  .wrapper form{
    margin: 35px 20px;
  }
  form .dbl-field{
    flex-direction: column;
    margin-bottom: 0px;
  }
  form .dbl-field .field{
    width: 100%;
    height: 45px;
    margin-bottom: 20px;
  }
  form .message textarea{
    resize: none;
  }
  form .button-area{
    margin-top: 20px;
    flex-direction: column;
  }
  .button-area button{
    width: 100%;
    padding: 11px 0;
    font-size: 16px;
  }
  .button-area span{
    margin: 20px 0 0;
    text-align: center;
  }
}

Third, create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with .js extension.

//Contact Form in PHP
const form = document.querySelector("form"),
statusTxt = form.querySelector(".button-area span");
form.onsubmit = (e)=>{
  e.preventDefault();
  statusTxt.style.color = "#0D6EFD";
  statusTxt.style.display = "block";
  statusTxt.innerText = "Sending your message...";
  form.classList.add("disabled");

  let xhr = new XMLHttpRequest();
  xhr.open("POST", "message.php", true);
  xhr.onload = ()=>{
    if(xhr.readyState == 4 && xhr.status == 200){
      let response = xhr.response;
      if(response.indexOf("required") != -1 || response.indexOf("valid") != -1 || response.indexOf("failed") != -1){
        statusTxt.style.color = "red";
      }else{
        form.reset();
        setTimeout(()=>{
          statusTxt.style.display = "none";
        }, 3000);
      }
      statusTxt.innerText = response;
      form.classList.remove("disabled");
    }
  }
  let formData = new FormData(form);
  xhr.send(formData);
}

Last, create a PHP file with the name of message.php and paste the given codes into your PHP file. You’ve to create a file with .php extension. Remember, after copying and paste these PHP codes, you have to enter that email address in the $receiver variable where you want to receive all messages.

//Contact Form in PHP
<?php
  $name = htmlspecialchars($_POST['name']);
  $email = htmlspecialchars($_POST['email']);
  $phone = htmlspecialchars($_POST['phone']);
  $website = htmlspecialchars($_POST['website']);
  $message = htmlspecialchars($_POST['message']);

  if(!empty($email) && !empty($message)){
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
      $receiver = "receiver_email_address"; //enter that email address where you want to receive all messages
      $subject = "From: $name <$email>";
      $body = "Name: $name\nEmail: $email\nPhone: $phone\nWebsite: $website\n\nMessage:\n$message\n\nRegards,\n$name";
      $sender = "From: $email";
      if(mail($receiver, $subject, $body, $sender)){
         echo "Your message has been sent";
      }else{
         echo "Sorry, failed to send your message!";
      }
    }else{
      echo "Enter a valid email address!";
    }
  }else{
    echo "Email and message field is required!";
  }
?>

That’s all, now you’ve successfully created a Working Contact Form in PHP. If your code doesn’t work or you’ve faced any error/problem, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it. But it won’t work on your localhost and to make it work you’ve to upload it to an online server.

To upload it to an online server first, extract the downloaded zip file on your PC and open the message.php file. In this file, there is a $receiver variable and you’ve to enter that email address where you want to receive all messages. After entering the email, just save this file and make a zip file of this folder and then upload it to your hosting and extract it there. Now, you’re ready to receive your visitor’s messages using this Contact Form in PHP.

View Live Demo

 

]]>
https://www.codingnepalweb.com/create-working-contact-form-in-php/feed/ 105
Download YouTube Video Thumbnail in PHP & JavaScript https://www.codingnepalweb.com/download-youtube-video-thumbnail/ https://www.codingnepalweb.com/download-youtube-video-thumbnail/#comments Wed, 09 Jun 2021 14:15:38 +0000 https://www.codingnepalweb.com/?p=2068 Download YouTube Video Thumbnail in PHP & JavaScript

Hey friends, today in this blog you’ll learn how to Save or Download YouTube Video Thumbnail or other Image Files using PHP cURL & JavaScript. In the earlier blog, I have shared a blog on how to create a URL Shortner Website using PHP and now it’s time to create a project to download YouTube video thumbnail using JavaScript & PHP.

In this project [Download YouTube Video Thumbnail], you can see in the image preview a white box or form with an input field, image preview area, and a download button. Download button is disabled until you paste a valid YouTube video URL or other image file URL.

When you paste YouTube video URL immediately, there appears a preview of the thumbnail of that video and you can download it. This thumbnail downloader accepts all types of YouTube video URLs means long or short URLs of the videos. And it also accepts any other image file like .jpg, .jepg, .png, .gif, and .webp.

Video Tutorial of YouTube Thumbnail Downloader

 
In the video, you have seen how this downloader looks like and how you can download a thumbnail or other image files by pasting their link or URL. In the video, you have also seen how I created this thumbnail downloader using HTML CSS JavaScript & PHP.

As you already know, To create this project I used only 6-8 lines of PHP cURL codes and they are used to download an image only and all other things are done using JavaScript like preview thumbnail. So if you don’t know PHP then you can also watch this video to learn JavaScript. I tried to explain each JavaScript & PHP line with comments and I hope you’ve understood the codes.

Let’s understand how I got a thumbnail from the URL and downloaded it but before this, you’ve to know how YouTube video URL looks like.

  • Long URL of the video – https://www.youtube.com/watch?v=FucPPCPDd2Y
  • Short URL of the same video – https://youtu.be/FucPPCPDd2Y

As you can see in both URLs there is the same video ID FucPPCPDd2Y of 11 lengths long and this ID is unique to each video and we need only this ID to get the thumbnail of this video. Using JavaScript, first, I got the user entered video URL and split it from the v= if the URL is long or split it from /be if the URL is short to get only video ID.

After I got the video ID, https://img.youtube.com/vi/VID_ID/maxresdefault.jpg is the thumbnail URL of the YouTube video. If you open this URL by replacing VID_ID with some random video ID then you’ll get a thumbnail of that video. I just replaced this VID_ID with the user entered video ID and inserted this full URL inside <img src=”thumbnail_url”> to show an image preview and at the same time I passed this URL in value of a hidden input to download this thumbnail using PHP. That’s it after I got a thumbnail, I just download it using PHP cURL.



Remember, YouTube has four types of thumbnail URLs and in this project, I only used one of them.

  • Low-Quality – https://img.youtube.com/vi/VID_ID/sddefault.jpg
  • Medium-Quality – https://img.youtube.com/vi/VID_ID/mqdefault.jpg
  • Hight-Quality – https://img.youtube.com/vi/VID_ID/hqdefault.jpg
  • Max High-Quality – https://img.youtube.com/vi/VID_ID/maxresdefault.jpg

You might like this:

Download YouTube Video Thumbnail [Source Codes]

To create this program [Download YouTube Video Thumbnail]. First, you need to create two Files one PHP File and another one is CSS File. After creating these files just paste the following codes into your file. First, create a PHP file with the name of index.php and paste the given codes into your PHP file. Remember, you’ve to create a file with .php extension.

<?php
  if(isset($_POST['button'])){
    $imgUrl = $_POST['imgurl'];
    $ch = curl_init($imgUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $downloadImg = curl_exec($ch);
    curl_close($ch);
    header('Content-type: image/jpg');
    header('Content-Disposition: attachment;filename="thumbnail.jpg"');
    echo $downloadImg;
  }
?>
<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Download YouTube Video Thumbnail | CodingNepal</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <header>Download Thumbnail</header>
    <div class="url-input">
      <span class="title">Paste video url:</span>
      <div class="field">
        <input type="text" placeholder="https://www.youtube.com/watch?v=lqwdD2ivIbM" required>
        <input class="hidden-input" type="hidden" name="imgurl">
        <span class="bottom-line"></span>
      </div>
    </div>
    <div class="preview-area">
      <img class="thumbnail" src="" alt="">
      <i class="icon fas fa-cloud-download-alt"></i>
      <span>Paste video url to see preview</span>
    </div>
    <button class="download-btn" type="submit" name="button">Download Thumbnail</button>
  </form>

  <script>
    const urlField = document.querySelector(".field input"),
    previewArea = document.querySelector(".preview-area"),
    imgTag = previewArea.querySelector(".thumbnail"),
    hiddenInput = document.querySelector(".hidden-input"),
    button = document.querySelector(".download-btn");

    urlField.onkeyup = ()=>{
      let imgUrl = urlField.value;
      previewArea.classList.add("active");
      button.style.pointerEvents = "auto";
      if(imgUrl.indexOf("https://www.youtube.com/watch?v=") != -1){
        let vidId = imgUrl.split('v=')[1].substring(0, 11);
        let ytImgUrl = `https://img.youtube.com/vi/${vidId}/maxresdefault.jpg`;
        imgTag.src = ytImgUrl;
      }else if(imgUrl.indexOf("https://youtu.be/") != -1){
        let vidId = imgUrl.split('be/')[1].substring(0, 11);
        let ytImgUrl = `https://img.youtube.com/vi/${vidId}/maxresdefault.jpg`;
        imgTag.src = ytImgUrl;
      }else if(imgUrl.match(/\.(jpe?g|png|gif|bmp|webp)$/i)){
        imgTag.src = imgUrl;
      }else{
        imgTag.src = "";
        button.style.pointerEvents = "none";
        previewArea.classList.remove("active");
      }
      hiddenInput.value = imgTag.src;
    }
  </script>

</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* Import Google font - Poppins & Noto */
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;500;600;700&family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #7D2AE8;
}
::selection{
  color: #fff;
  background: #7D2AE8;
}
form{
  width: 450px;
  background: #fff;
  padding: 30px ;
  border-radius: 5px;
  box-shadow: 10px 10px 13px rgba(0,0,0,0.1);
}
form header{
  text-align: center;
  font-size: 28px;
  font-weight: 500;
  margin-top: 10px;
  color: #7D2AE8;
}
form .url-input{
  margin: 30px 0;
}
.url-input .title{
  font-size: 18px;
  color: #373737;
}
.url-input .field{
  margin-top: 5px;
  height: 50px;
  width: 100%;
  position: relative;
}
.url-input .field input{
  height: 100%;
  width: 100%;
  border: none;
  outline: none;
  padding: 0 15px;
  font-size: 15px;
  background: #F1F1F7;
  border-bottom: 2px solid #ccc;
  font-family: 'Noto Sans', sans-serif;
}
.url-input .field input::placeholder{
  color: #b3b3b3;
}
.url-input .field .bottom-line{
  position: absolute;
  left: 0;
  bottom: 0;
  height: 2px;
  width: 100%;
  background: #7D2AE8;
  transform: scale(0);
  transition: transform 0.3s ease;
}
.url-input .field input:focus ~ .bottom-line,
.url-input .field input:valid ~ .bottom-line{
  transform: scale(1);
}
form .preview-area{
  border-radius: 5px;
  height: 220px;
  display: flex;
  overflow: hidden;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border: 2px dashed #8e46ec;
}
.preview-area.active{
  border: none;
}
.preview-area .thumbnail{
  width: 100%;
  display: none;
  border-radius: 5px;
}
.preview-area.active .thumbnail{
  display: block;
}
.preview-area.active .icon,
.preview-area.active span{
  display: none;
}
.preview-area .icon{
  color: #8e46ec;
  font-size: 80px;
}
.preview-area span{
  color: #8e46ec;
  margin-top: 25px;
}
form .download-btn{
  color: #fff;
  height: 53px;
  width: 100%;
  outline: none;
  border: none;
  font-size: 17px;
  font-weight: 500;
  cursor: pointer;
  margin: 30px 0 20px 0;
  border-radius: 5px;
  background: #7D2AE8;
  pointer-events: none;
  transition: background 0.3s ease;
}
.download-btn:hover{
  background: #6616d0;
}
@media screen and (max-width: 460px){
  body{
    padding: 0 20px;
  }
  form header{
    font-size: 24px;
  }
  .url-input .field,
  form .download-btn{
    height: 45px;
  }
  form .download-btn{
    font-size: 15px;
  }
  form .preview-area{
    height: 130px;
  }
  .preview-area .icon{
    font-size: 50px;
  }
  .preview-area span{
    margin-top: 10px;
    font-size: 12px;
  }
}

That’s all, now you’ve successfully created a project on Download YouTube Video Thumbnail using HTML CSS JavaScript & PHP. If your code does not work or you’ve faced any error/problem then please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

After extracting, move this folder inside htdocs of your XAMPP installation directory and start the apache server from xampp control panel and then open this url – localhost/thumbnail or localhost/thumbnail/index.php in your browser.

 

]]>
https://www.codingnepalweb.com/download-youtube-video-thumbnail/feed/ 46
Build URL Shortener using PHP with MySQL & JavaScript https://www.codingnepalweb.com/url-shortener-using-php-mysql/ https://www.codingnepalweb.com/url-shortener-using-php-mysql/#comments Thu, 18 Mar 2021 12:19:00 +0000

URL Shortener Website using PHP with MySQL & JavaScriptHey friends, today in this blog you’ll learn how to Build URL Shortener using PHP with MySQL & JavaScript. You may know, in the earlier blog, I have shared how to create a Chat Web Application using PHP with MySQL & JavaScript (Ajax), and now I’m going to create a URL Shortener in PHP and this is a requested blog/video of our many viewers so if you want a video on any related topic then you can comment in our YouTube videos or Blog posts.

A URL shortener is a service that helps take longer URLs (which can be more than a hundred characters) and transform/convert them into manageable or short links that rarely pass 20 characters. In this project [URL Shortener Website], there is only an input field on the website to enter or paste a long URL and a button to shorten the long URL. This input field has full validation that means the user can only type or enter a URL to shorten it.

When the user types a valid long URL and clicks on the shorten button then there is appears a popup box with a short url/link and a save button to edit or save the short URL. Users can only change or edit the short URL at that time, later it can’t be changed. Once the user clicks on the save button then the page will reload and there is shown the user’s created short URL, long URL, clicks, and a delete button to delete the particular row or link from the URLs area section.

If you’re feeling difficulty understanding what I’m saying or want to watch a full video tutorial of this project then you can watch a full video of this project [URL Shortener using PHP]

Video Tutorial of Build URL Shortener using PHP

 
In the video, you have seen the demo of the URL Shortener using PHP and how I created it. In this project, I didn’t add a login and signup form to show the particular URLs to particular users who have created these. I know a login form should be required in this project otherwise, any user can see anyone’s URLs but why I didn’t add it? Well, I already created a separate blog on Login & Signup Form using PHP with MySQL and I assume you can add it to this project by yourself so I didn’t add it.

If I add it then the video length will be doubled and I don’t want it. I created this project to show how you can create this type of simple url shortener website in PHP and now it depends on you and your skills, creativity how you can make this project more useful according to your requirements. I know if you’re a beginner then it’s too difficult to create by you but if many beginners will request me then definitely I’ll add a login and signup form on it for you.

You might like this:

URL Shortener using PHP with MySQL [Source Codes]

How to download source code files and what to do after downloading them?

If you want to run this project on your localhost then you don’t need to change anything in the coding files but if you want to upload it to an online server then you’ve to do some changes in the two/three project files and all required changes are mentioned in the coding files.

For localhost users – Download the zip file from the given download button and unzip it. You’ll get a folder name with url, just open this folder, there should be a url.sql file. Now open localhost/phpmyadmin on your browser and create a database name with url then import the url.sql file and all required tables, columns will be automatically created. That’s it for localhost users.

For online server users – Download the zip file from the given download button and unzip it. You’ll get a folder name with url, just open this folder, there should be a url.sql file and import it inside your MySQL database and all required tables, columns will be automatically created. After these steps, open the config.php file and do the changes which are mentioned in that file. If you want to upload this project to 000webhost which is free hosting, then watch this video because most steps are similar. That’s it for online server users.

 

]]>
https://www.codingnepalweb.com/url-shortener-using-php-mysql/feed/ 26
Chat Web Application using PHP with MySQL & JavaScript https://www.codingnepalweb.com/chat-web-application-using-php/ https://www.codingnepalweb.com/chat-web-application-using-php/#comments Wed, 17 Feb 2021 13:41:00 +0000 Realtime Chat Application using PHP with MySQL & JavaScript Ajax

Hey friends, today in this blog you’ll learn how to create a Chat Web Application using PHP with MySQL & JavaScript. Earlier I have shared a blog on how to create a Simple Chatbot using PHP with MySQL & jQuery Ajax. Our maximum viewers have requested me to create a Chat App so I decided to create one.

In this chat application, when you open it first on your browser, there is shown a signup form where you have to signup with your details like name, email, password, and image. Email and image field is fully validated which means you’ve to enter a valid email and an image file only. Once you signed up successfully, you’ll be redirected to the user’s page where you can see your full name, image, status, and logout button to the top, and users, like you, appear on the bottom if someone has signed up.

On this page, you can see their image, name, status, and the last message if they sent to you. You have to click on the particular user or you can also search any existing user with their name then you’ll be redirected to the chat page and there you can see the image, name, status of that user who is going to chat.

Once you send a message to another user then immediately that message appears in your chat box and another user chatbox too which you’ve sent the message. On the message receiver chatbox, this user received the message with the sender image. Remember chatbox will be automatically scrolled to the bottom once the chatbox starts scrolling. You can log out from the chat application at any time and once you log out, immediately all other users will know that you’ve been log out or offline.

Once you log out, you can again login and with your email and password that you used when signing up for the form. If you entered the correct credentials then you’ll be redirected to the user’s page and all other users will immediately know that you’ve logged on and now active.

Video Tutorial of Chat Application in PHP and MySQL

 
In the video, you’ve seen the demo of the chat application in PHP and MySQL and the codes or concepts behind creating a chat app. As I already told you I used PHP with MySQL and pure JavaScript Ajax to create this chat app so you don’t need to reload the page to see changes in the chat app. I know if you’re a beginner and you don’t have enough knowledge about PHP then definitely you’ve to difficult to understand the codes.

But I tried to explain each JavaScript and PHP line with comments, subtitles, etc. But don’t worry I have provided the source code files of this chat app so you can easily download from the given download button and try analyzing, practicing the codes to understand better. And I know, there are many other features that are missed on this chat app but for now, I think it is more than enough for practice.

You might like this:

Chat Web Application using PHP [Source Codes]

How to download source code files and what to do after downloading them?

Steps: – To download files, just click on the given download button then a 60 seconds timer will start, just wait for the timer. Once the timer completed then a zip file will be downloaded automatically. Once it downloaded, just extract the zip file then you’ll see the folder name with ChatApp. Copy this folder and paste it inside htdocs folder of your XAMPP then start your apache and MySQL from the XAMMP control panel.

After completing these steps, go to your browser and open this URL localhost/phpmyadmin then create a new database name with a chatapp. After creating the database, there you can see an import option, just click on that and import the SQL file which is in the ChatApp folder. Everything is done now, just open this URL localhost/chatapp that’s it. Your chat application is ready to chat.

If you want to upload this chat application to an online server for free and don’t know how? Then please watch this video How to upload Chat Application to an Online Server for Free?

 

]]>
https://www.codingnepalweb.com/chat-web-application-using-php/feed/ 270
Email Subscription Form using HTML CSS & PHP https://www.codingnepalweb.com/email-subscription-form-php/ https://www.codingnepalweb.com/email-subscription-form-php/#comments Wed, 25 Nov 2020 15:04:00 +0000 https://codingnepalweb.com/2020/11/25/email-subscription-form-using-html-css-php/ Subscription Form using HTML CSS & PHP Popup Email Subscription Box in PHP
Hello readers, Today in this blog you’ll learn how to create an Email Subscription Form using HTML CSS & PHP. Earlier I have also shared a blog on Email Subscription Box using only HTML & CSS but now in this form, I’m going to use PHP which helps to send an email immediately when new the user subscribed to the form or blog.

An email subscription is an option on a website that lets visitors receive the latest updates via email by defining their email addresses in a subscription form.

In this program [Popup Email Subscription Box in PHP], at first, on the webpage, there is a button labeled as “Show Modal” and when you clicked on this button then the Email Subscription Box appears with a sliding animation. After filling in your email address in the email field then you have to click on the Subscribe button. After clicked on this button, if your email address is not valid, then there is shown an error alert and if your email is valid then there is shown a success message labeled as “Thanks for subscribing us” and a short message will be sent to your email.

If you’re feeling difficult to understand what I am saying. You can watch a full video tutorial on this program [Email Subscription Form].

Video Tutorial of Email Subscription Form

 
In the video, you have seen the Email Subscription Form using HTML CSS & PHP. PHP used to validate the user entered email and send to mail to the user email. To show or hide subscription form on a button or cancel icon click is created using only HTML & CSS. I used HTML <innput type=”checkbox”> and <label> to show or hide form on click.

In this video, I have sent mail from Localhost using but your mail maybe won’t send because before sending mail from Localhost, you have to configure two XAMPP files. I have already shared a blog on How to configure XAMPP to send Mail from Localhost in PHP.

You might like this:

Popup Email Subscription Form in PHP [Source Codes]

To create this program [Popup Email Subscription Box in PHP]. First, you need to create two Files one PHP File and another one is CSS File. After creating these files just paste the following codes into your file. First, create a PHP file with the name of index.php and paste the given codes in your PHP file. Remember, you’ve to create a file with .php extension.

<!DOCTYPE html>
<!-- Created By CodingNepal - www.codingnepalweb.com -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscription Form | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
  <input type="checkbox" id="toggle">
  <label for="toggle" class="show-btn">Show Modal</label>
  <div class="wrapper">
    <label for="toggle">
    <i class="cancel-icon fas fa-times"></i>
    </label>
    <div class="icon"><i class="far fa-envelope"></i></div>
    <div class="content">
      <header>Become a Subscriber</header>
      <p>Subscribe to our blog and get the latest updates straight to your inbox.</p>
    </div>
    <form action="index.php" method="POST">
    <?php 
    $userEmail = ""; //first we leave email field blank
    if(isset($_POST['subscribe'])){ //if subscribe btn clicked
      $userEmail = $_POST['email']; //getting user entered email
      if(filter_var($userEmail, FILTER_VALIDATE_EMAIL)){ //validating user email
        $subject = "Thanks for Subscribing us - CodingNepal";
        $message = "Thanks for subscribing to our blog. You'll always receive updates from us. And we won't share and sell your information.";
        $sender = "From: shahiprem7890@gmail.com";
        //php function to send mail
        if(mail($userEmail, $subject, $message, $sender)){
          ?>
           <!-- show sucess message once email send successfully -->
          <div class="alert success-alert">
            <?php echo "Thanks for Subscribing us." ?>
          </div>
          <?php
          $userEmail = "";
        }else{
          ?>
          <!-- show error message if somehow mail can't be sent -->
          <div class="alert error-alert">
          <?php echo "Failed while sending your mail!" ?>
          </div>
          <?php
        }
      }else{
        ?>
        <!-- show error message if user entered email is not valid -->
        <div class="alert error-alert">
          <?php echo "$userEmail is not a valid email address!" ?>
        </div>
        <?php
      }
    }
    ?>
      <div class="field">
        <input type="text" class="email" name="email" placeholder="Email Address" required value="<?php echo $userEmail ?>">
      </div>
      <div class="field btn">
        <div class="layer"></div>
        <button type="submit" name="subscribe">Subscribe</button>
      </div>
    </form>
    <div class="text">We do not share your information.</div>
  </div>

</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  height: 100vh;
  background: linear-gradient(136deg, rgb(224,195,252) 0%, rgb(142,197,252) 100%);
}
::selection{
  color: #fff;
  background: rgb(142,197,252);
}
.show-btn, .wrapper{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
  border-radius: 5px;
  box-shadow: 0px 10px 15px rgba(0,0,0,0.1);
}
.show-btn{
  color: rgb(142,197,252);
  padding: 13px 18px;
  font-size: 20px;
  font-weight: 500;
  text-transform: uppercase;
  cursor: pointer;
}
.wrapper{
  z-index: 5;
  background: #fff;
  padding: 30px;
  text-align: center;
  max-width: 400px;
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
  top: 50%;
  opacity: 1;
  pointer-events: auto;
  transition: all 0.3s ease;
}
#toggle{
  display: none;
}
#toggle:checked ~ .wrapper{
  opacity: 0;
  pointer-events: none;
  top: 40%;
}
.wrapper .cancel-icon{
  position: absolute;
  right: 20px;
  top: 20px;
  color: rgb(142,197,252);
  cursor: pointer;
}
.cancel-icon:hover{
  color: rgb(224,195,252);
}
.wrapper .icon{
  height: 110px;
  width: 110px;
  background: linear-gradient(136deg, rgb(224,195,252) 0%, rgb(142,197,252) 100%);
  line-height: 110px;
  border-radius: 50%;
  color: #fff;
  font-size: 55px;
}
.wrapper .content{
  margin: 20px 0;
}
.content header{
  font-size: 30px;
  font-weight: 600;
}
.content p{
  color: #333;
  font-size: 16px;
  font-weight: 400;
  margin-left: -3px;
}
form{
  width: 98%;
}
form .field{
  height: 45px;
  width: 100%;
  margin-bottom: 12px;
}
form .field input{
  width: 100%;
  height: 100%;
  border-radius: 5px;
  border: 1px solid #ccc;
  padding: 0 15px;
  outline: none;
  font-size: 17px;
  transition: all 0.3s ease;
}
form .field input:focus{
  border-color: rgb(142,197,252);
}
form .btn{
  height: 47px;
  width: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 5px;
}
form .btn .layer{
  height: 100%;
  width: 300%;
  position: absolute;
  left: -100%;
  background: linear-gradient(136deg, rgb(224,195,252) 0%, rgb(142,197,252) 100%);
  transition: all 0.4s ease;
}
form .btn:hover .layer{
  left: 0;
}
form .btn button{
  z-index: 1;
  position: relative;
  background: none;
  padding: 0px!important;
  color: #fff;
  border: 0px;
  outline: none;
  font-size: 20px;
  font-weight: 500;
  cursor: pointer;
  height: 100%;
  width: 100%;
}
.wrapper .text{
  margin-top: 5px;
}
.alert{
  margin: -9px 0 12px 0;
  padding: 10px;
  border-radius: 5px;
}
.success-alert{
  color: #155724;
  background: #d4edda;
  border: 1px solid #c3e6cb;
}
.error-alert{
  color: #721c24;
  background: #f8d7da;
  border: 1px solid #f5c6cb;
}

That’s all, now you’ve successfully created an Email Subscription Form using HTML CSS & PHP. If your code does not work or you’ve faced any error/problem then please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/email-subscription-form-php/feed/ 16
How to Upload, Preview & Download Image using JavaScript & PHP https://www.codingnepalweb.com/upload-preview-download-image-php/ https://www.codingnepalweb.com/upload-preview-download-image-php/#comments Wed, 30 Sep 2020 12:14:00 +0000 https://codingnepalweb.com/2020/09/30/how-to-upload-preview-download-image-using-javascript-php/ How to Upload, Preview & Download Image using JavaScript & PHP

Hello reader, Today in this blog, you’ll learn how to Upload, Preview & Download Images using JavaScript & PHP. Earlier, I’ve shared many blogs related to PHP [Custom Simple PHP Chatbot, Send Email from Localhost, Login & Signup Form with Email Verification] and many more. Now time to create another program (Easily Download Image through URL) using PHP.

In this program [Image Download using PHP], on the webpage, there is an image preview box with an image gallery icon, one input field to paste the image URL, and a button to download the image. This input field is fully validation that means the user can’t upload any other URL except images.

When you paste a valid image URL that has like .png or .jpeg extension then there is shown a preview of that image, and the download button also active to download the image, by default the download button is disabled at first. When you click on the download button, it immediately downloads the image.

If you’re feeling difficult to understand what I am saying. You can watch a full video tutorial on this program [Download Image using JavaScript & PHP].

Video Tutorial of Download Image in JavaScript & PHP

 
In the video, you have seen how we can download any images on one click using PHP. I hope you’ve understood the basic codes behind creating this program. In this video, I’ve only created the design part of the Image Download Program. In the second part of this video, I have completed the JavaScript and PHP codes of this program. If you haven’t still watched this video, please watch because I’ve explained each line of JavaScript and PHP code with the comments.
 
This design is fully based on HTML & CSS but to validate image extension and show preview of the image I used JavaScript and to download images I used cUrl in PHP. cURL is a tool for transferring files and data with URL syntax, supporting multiple protocols – HTTP, FTP, TELNET, and more.

You might like this:

Download Image in JavaScript & PHP [Source Codes]

To create this program [Image Download using PHP]. First, you need to create two Files one PHP File and another one is CSS File. After creating these files just paste the following codes in your file. First, create a PHP file with the name of index.php and paste the given codes in your PHP file. Remember, you’ve to create a file with .php extension.

<!-- Created By CodingNepal -->
<?php
//if download button clicked
if(isset($_POST['downloadBtn'])){
    //getting the user img url from input field
    $imgURL = $_POST['file']; //storing in variable
    $regPattern = '/\.(jpe?g|png|gif|bmp)$/i'; //pattern to validataing img extension
    if(preg_match($regPattern, $imgURL)){ //if pattern matched to user img url
        $initCURL = curl_init($imgURL); //intializing curl
        curl_setopt($initCURL, CURLOPT_RETURNTRANSFER, true);
        $downloadImgLink = curl_exec($initCURL); //executing curl
        curl_close($initCURL); //closing curl
        // now we convert the base 64 format to jpg to download
        header('Content-type: image/jpg'); //in which extension you want to save img
        header('Content-Disposition: attachment;filename="image.jpg"'); //in which name you want to save img
        echo $downloadImgLink;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Download in PHP | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <div class="wrapper">
        <div class="preview-box">
            <div class="cancel-icon"><i class="fas fa-times"></i></div>
            <div class="img-preview"></div>
            <div class="content">
                <div class="img-icon"><i class="far fa-image"></i></div>
                <div class="text">Paste the image url below, <br/>to see a preview or download!</div>
            </div>
        </div>
        <form action="index.php" method="POST" class="input-data">
            <input id="field" type="text" name="file" placeholder="Paste the image url to download..." autocomplete="off">
            <input id="button" name="downloadBtn" type="submit" value="Download">
        </form>
    </div>

    <script>
        $(document).ready(function(){
            //if user focus out from the input field
            $("#field").on("focusout", function(){
                //getting user entered img URL
                var imgURL = $("#field").val();
                if(imgURL != ""){ //if input field isn't blank
                    var regPattern = /\.(jpe?g|png|gif|bmp)$/i; //pattern to validataing img extension
                    if(regPattern.test(imgURL)){ //if pattern matched to image url
                        var imgTag = '<img src="'+ imgURL +'" alt="">'; //creating a new img tag to show img
                        $(".img-preview").append(imgTag); //appending img tag with user entered img url
                        // adding new class which i've created in css
                        $(".preview-box").addClass("imgActive");
                        $("#button").addClass("active");
                        $("#field").addClass("disabled");
                        $(".cancel-icon").on("click", function(){
                            //we'll remove all new added class on cancel icon click
                            $(".preview-box").removeClass("imgActive");
                            $("#button").removeClass("active");
                            $("#field").removeClass("disabled");
                            $(".img-preview img").remove();
                            // that's all in javascript/jquery now the main part is PHP
                        });
                    }else{
                        alert("Invalid img URL - " + imgURL);
                        $("#field").val('');//if pattern not matched we'll leave the input field blank
                    }
                }
            });
        });
    </script>
    
</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
html,body{
    display: grid;
    height: 100%;
    place-items: center;
}
::selection{
   color: #fff;
   background: #4158d0;	
}
.wrapper{
    height: 450px;
    width: 500px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-direction: column;
}
.wrapper .preview-box{
    position: relative;
    width: 100%;
    height: 320px;
    display: flex;
    text-align: center;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    border: 2px dashed #c2cdda;
}
.preview-box.imgActive{
    border: 2px solid transparent;
}
.preview-box .cancel-icon{
    position: absolute;
    right: 20px;
    top: 10px;
    z-index: 999;
    color: #4158d0;
    font-size: 20px;
    cursor: pointer;
    display: none;
}
.preview-box.imgActive:hover .cancel-icon{
    display: block;
}
.preview-box .cancel-icon:hover{
    color: #ff0000;
}
.preview-box .img-preview{
    height: 100%;
    width: 100%;
    position: absolute;
}
.preview-box .img-preview img{
    height: 100%;
    width: 100%;
    border-radius: 5px;
}
.wrapper .preview-box .img-icon{
    font-size: 100px;
    background: linear-gradient(-135deg, #c850c0, #4158d0);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
.wrapper .preview-box .text{
    font-size: 18px;
    font-weight: 500;
    color: #5B5B7B;
}
.wrapper .input-data{
    height: 130px;
    width: 100%;;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    flex-direction: column;
}
.wrapper .input-data #field{
    width: 100%;
    height: 50px;
    outline: none;
    font-size: 17px;
    padding: 0 15px;
    user-select: auto;
    border-radius: 5px;
    border: 2px solid lightgrey;
    transition: all 0.3s ease;
}
.input-data #field.disabled{
    color: #b3b3b3;
    pointer-events: none;
}
.wrapper .input-data #field:focus{
    border-color: #4158d0;
}
.input-data #field::placeholder{
    color: #b3b3b3;
}
.wrapper .input-data #button{
    height: 50px;
    width: 100%;
    border: none;
    outline: none;
    color: #fff;
    font-weight: 500;
    font-size: 18px;
    cursor: pointer;
    border-radius: 5px;
    opacity: 0.5;
    pointer-events: none;
    background: linear-gradient(-135deg, #c850c0, #4158d0);
    transition: all 0.3s ease;
}
.input-data #button.active{
    opacity: 1;
    pointer-events: auto;
}
.input-data #button:active{
    transform: scale(0.99);
}

That’s all, now you’ve successfully created a How to Upload, Preview & Download Image using JavaScript & PHP. If your code doesn’t work or you’ve faced any error/problem then please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/upload-preview-download-image-php/feed/ 7
Simple Chatbot using PHP with MySQL & jQuery (Ajax) https://www.codingnepalweb.com/chatbot-using-php-with-mysql/ https://www.codingnepalweb.com/chatbot-using-php-with-mysql/#comments Sun, 20 Sep 2020 08:48:00 +0000 https://codingnepalweb.com/2020/09/20/simple-chatbot-using-php-with-mysql-jquery-ajax/  

Simple Chatbot using PHP with MySQL & jQuery (Ajax)

Hello readers, Today in this blog you’ll learn how to create a Simple Chatbot using PHP with MySQL & jQuery (Ajax). Earlier I shared a blog on how to Send Emails with PHP from Localhost using the XAMPP server and now it’s time to create a working chatbot in PHP.

A chatbot is a computer program designed to simulate human conversation. These chatbots reply to you instantly according to your queries because programmers have inserted thousands of inputs, replies, and queries into the database that can be asked by the user.

To make an advanced chatbot we’ve to code more and more but I tried to make a simple chatbot with a few lines of code and queries which help you to get an idea about how a chatbot actually works.

On the webpage for this chatbot, there is a chat form with an input field and a button labeled “send” for typing a message and sending it to the bot. If you ask the bot a question, and if the query exists in the database, the bot instantly replies with a message based on your query; if the query does not match any database queries, the bot replies with a message labeled “Sorry, we can’t understand you!”

In this chatting process, the webpage isn’t reloaded because I used jQuery (Ajax) for that. If you’re feeling difficult to understand what I am saying. You can watch a full video tutorial on this program [Simple Chatbot using PHP].

Video Tutorial of Simple Chatbot using PHP

 
In the video, you have seen how this chatbot looks and how it gives a reply according to the user query. If you know basic HTML, CSS, PHP & jQuery then you can easily understand the codes behind creating this chatbot. In this video, I have just made a chatbot form where chats are static but in part -2 of this video, I have done the PHP and jQuery codes of this program and made it dynamic.

In that part -2 video, to make this chatbot dynamic, I just created a database and a table in MySQL and inserted some queries and replies into it and with the help of PHP and Ajax, I retrieved the data (replies) in the chat form according to the user query.

You might like this:

Simple Chatbot using PHP with MySQL [Source Codes]

To create this program [Simple Chatbot using PHP]. First, you need to create three Files two PHP Files and another one CSS Files. After creating these files just paste the following codes in your file.

Remember that, if you’re going to download code files, you’ve to create a database name “bot”, and table name “chatbot”, and inside this table, you’ve to create three rows (id, queries, replies). Otherwise, you can replace the name of the database, table, and table rows with your database table details in my given files.

  • id type int(11) auto_increment
  • queries type varchar(300)
  • replies type varchar(300)

First, create a PHP file with the name bot.php and paste the given codes into your PHP file. Remember, you’ve to create a file with .php extension.

<!-- Created By CodingNepal -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Chatbot in PHP | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <div class="wrapper">
        <div class="title">Simple Online Chatbot</div>
        <div class="form">
            <div class="bot-inbox inbox">
                <div class="icon">
                    <i class="fas fa-user"></i>
                </div>
                <div class="msg-header">
                    <p>Hello there, how can I help you?</p>
                </div>
            </div>
        </div>
        <div class="typing-field">
            <div class="input-data">
                <input id="data" type="text" placeholder="Type something here.." required>
                <button id="send-btn">Send</button>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function(){
            $("#send-btn").on("click", function(){
                $value = $("#data").val();
                $msg = '<div class="user-inbox inbox"><div class="msg-header"><p>'+ $value +'</p></div></div>';
                $(".form").append($msg);
                $("#data").val('');
                
                // start ajax code
                $.ajax({
                    url: 'message.php',
                    type: 'POST',
                    data: 'text='+$value,
                    success: function(result){
                        $replay = '<div class="bot-inbox inbox"><div class="icon"><i class="fas fa-user"></i></div><div class="msg-header"><p>'+ result +'</p></div></div>';
                        $(".form").append($replay);
                        // when chat goes down the scroll bar automatically comes to the bottom
                        $(".form").scrollTop($(".form")[0].scrollHeight);
                    }
                });
            });
        });
    </script>
    
</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
html,body{
    display: grid;
    height: 100%;
    place-items: center;
}

::selection{
    color: #fff;
    background: #007bff;
}

::-webkit-scrollbar{
    width: 3px;
    border-radius: 25px;
}
::-webkit-scrollbar-track{
    background: #f1f1f1;
}
::-webkit-scrollbar-thumb{
    background: #ddd;
}
::-webkit-scrollbar-thumb:hover{
    background: #ccc;
}

.wrapper{
    width: 370px;
    background: #fff;
    border-radius: 5px;
    border: 1px solid lightgrey;
    border-top: 0px;
}
.wrapper .title{
    background: #007bff;
    color: #fff;
    font-size: 20px;
    font-weight: 500;
    line-height: 60px;
    text-align: center;
    border-bottom: 1px solid #006fe6;
    border-radius: 5px 5px 0 0;
}
.wrapper .form{
    padding: 20px 15px;
    min-height: 400px;
    max-height: 400px;
    overflow-y: auto;
}
.wrapper .form .inbox{
    width: 100%;
    display: flex;
    align-items: baseline;
}
.wrapper .form .user-inbox{
    justify-content: flex-end;
    margin: 13px 0;
}
.wrapper .form .inbox .icon{
    height: 40px;
    width: 40px;
    color: #fff;
    text-align: center;
    line-height: 40px;
    border-radius: 50%;
    font-size: 18px;
    background: #007bff;
}
.wrapper .form .inbox .msg-header{
    max-width: 53%;
    margin-left: 10px;
}
.form .inbox .msg-header p{
    color: #fff;
    background: #007bff;
    border-radius: 10px;
    padding: 8px 10px;
    font-size: 14px;
    word-break: break-all;
}
.form .user-inbox .msg-header p{
    color: #333;
    background: #efefef;
}
.wrapper .typing-field{
    display: flex;
    height: 60px;
    width: 100%;
    align-items: center;
    justify-content: space-evenly;
    background: #efefef;
    border-top: 1px solid #d9d9d9;
    border-radius: 0 0 5px 5px;
}
.wrapper .typing-field .input-data{
    height: 40px;
    width: 335px;
    position: relative;
}
.wrapper .typing-field .input-data input{
    height: 100%;
    width: 100%;
    outline: none;
    border: 1px solid transparent;
    padding: 0 80px 0 15px;
    border-radius: 3px;
    font-size: 15px;
    background: #fff;
    transition: all 0.3s ease;
}
.typing-field .input-data input:focus{
    border-color: rgba(0,123,255,0.8);
}
.input-data input::placeholder{
    color: #999999;
    transition: all 0.3s ease;
}
.input-data input:focus::placeholder{
    color: #bfbfbf;
}
.wrapper .typing-field .input-data button{
    position: absolute;
    right: 5px;
    top: 50%;
    height: 30px;
    width: 65px;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
    outline: none;
    opacity: 0;
    pointer-events: none;
    border-radius: 3px;
    background: #007bff;
    border: 1px solid #007bff;
    transform: translateY(-50%);
    transition: all 0.3s ease;
}
.wrapper .typing-field .input-data input:valid ~ button{
    opacity: 1;
    pointer-events: auto;
}
.typing-field .input-data button:hover{
    background: #006fef;
}

Last, create a PHP file with the name message.php and paste the given codes into your PHP file. Remember, you’ve to create a file with .php extension.

<!-- Created By CodingNepal -->
<?php
// connecting to database
$conn = mysqli_connect("localhost", "root", "", "bot") or die("Database Error");

// getting user message through ajax
$getMesg = mysqli_real_escape_string($conn, $_POST['text']);

//checking user query to database query
$check_data = "SELECT replies FROM chatbot WHERE queries LIKE '%$getMesg%'";
$run_query = mysqli_query($conn, $check_data) or die("Error");

// if user query matched to database query we'll show the reply otherwise it go to else statement
if(mysqli_num_rows($run_query) > 0){
    //fetching replay from the database according to the user query
    $fetch_data = mysqli_fetch_assoc($run_query);
    //storing replay to a varible which we'll send to ajax
    $replay = $fetch_data['replies'];
    echo $replay;
}else{
    echo "Sorry can't be able to understand you!";
}

?>

That’s all, now you’ve successfully created a Simple Chatbot using PHP with MySQL & jQuery (Ajax). If your code doesn’t work or you’ve faced any error/problem then please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/chatbot-using-php-with-mysql/feed/ 60
How to Send Mail using XAMPP Server with PHP https://www.codingnepalweb.com/send-mail-using-xampp-server-with-php/ https://www.codingnepalweb.com/send-mail-using-xampp-server-with-php/#comments Wed, 09 Sep 2020 09:32:00 +0000 https://codingnepalweb.com/2020/09/09/how-to-send-mail-using-xampp-server-with-php/
How to Send Email with PHP & Gmail | Send Mail from Localhost using XAMPP Server

Hello readers, Today in this blog you’ll learn how to Send Mail using XAMPP Server. Earlier I have shared a blog on How to configure XAMPP to send Mail from Localhost in PHP? If you haven’t still read that blog, I want to suggest you read that blog first.

Generally, in this program, on the webpage, there is a mail send the form with three inputs – email address, subject, and message. When you click on the send button without filling the form completely, there is a display of an alert labeled as  “All input fields are required!”. And when you filled up all inputs and click on the send button, your mail will be sent to a particular email address that you’ve provided in the recipient field and there is also display a success message labeled as “Your mail sent successfully to someone email”.

If somehow mail can’t be sent, there is a display of an alert labeled as “Sorry, failed while sending mail!”. If you’re feeling difficult to understand what I am saying. You can watch a full video tutorial on this program [How to Send Email with PHP & Gmail].

Video Tutorial of Send Mail using XAMPP Server

 
In the video, you have seen How to Send Email with PHP & Gmail and I hope you’ve understood the basic codes behind creating this form and sending mail. I used SMTP Server to send Mail/Email from Localhost using XAMPP. An SMTP (Simple Mail Transfer Protocol) server is an application that’s main purpose is to send and receive mail/email between email senders and receivers.

You might like this:

How to Send Email with PHP & Gmail [Source Codes]

To create this program [How to Send Email with PHP & Gmail]. First, you need to create two Files one PHP File and another one is CSS File. After creating these files just paste the following codes in your file.

First, create a PHP file with the name of mail.html and paste the given codes in your PHP file. Remember, you’ve to create a file with .php extension.

<!DOCTYPE html>
<!-- Created By CodingNepal -->
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Send Mail From Localhost | CodingNepal</title>
      <link rel="stylesheet" href="style.css">
      <!-- bootstrap cdn link -->
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
   </head>
   <body>
      <div class="container">
         <div class="row">
            <div class="col-md-4 offset-md-4 mail-form">
               <h2 class="text-center">
                  Send Message
               </h2>
               <p class="text-center">
                  Send mail to anyone from localhost.
               </p>
               <!-- starting php code -->
               <?php
                  //first we leave this input field blank
                  $recipient = "";
                  //if user click the send button
                  if(isset($_POST['send'])){
                      //access user entered data
                     $recipient = $_POST['email'];
                     $subject = $_POST['subject'];
                     $message = $_POST['message'];
                     $sender = "From: shahiprem7890@gmail.com";
                     //if user leave empty field among one of them
                     if(empty($recipient) || empty($subject) || empty($message)){
                         ?>
               <!-- display an alert message if one of them field is empty -->
               <div class="alert alert-danger text-center">
                  <?php echo "All inputs are required!" ?>
               </div>
               <?php
                  }else{
                      // PHP function to send mail
                     if(mail($recipient, $subject, $message, $sender)){
                      ?>
               <!-- display a success message if once mail sent sucessfully -->
               <div class="alert alert-success text-center">
                  <?php echo "Your mail successfully sent to $recipient"?>
               </div>
               <?php
                  $recipient = "";
                  }else{
                   ?>
               <!-- display an alert message if somehow mail can't be sent -->
               <div class="alert alert-danger text-center">
                  <?php echo "Failed while sending your mail!" ?>
               </div>
               <?php
                  }
                  }
                  }
                  ?> <!-- end of php code -->
               <form action="mail.php" method="POST">
                  <div class="form-group">
                     <input class="form-control" name="email" type="email" placeholder="Recipients" value="<?php echo $recipient ?>">
                  </div>
                  <div class="form-group">
                     <input class="form-control" name="subject" type="text" placeholder="Subject">
                  </div>
                  <div class="form-group">
                     <!-- change this tag name into textarea to show textarea field. Due to more textarea I got an error, so I change the name of this field -->
                     <!-- <changeit cols="30" rows="5" class="form-control textarea" name="message" placeholder="Compose your message.."></changeit> -->
                  </div>
                  <div class="form-group">
                     <input class="form-control button btn-primary" type="submit" name="send" value="Send" placeholder="Subject">
                  </div>
               </form>
            </div>
         </div>
      </div>
   </body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* custom css styling */
@import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');
html,body{
    background: #007bff;
}
::selection{
    color: #fff;
    background: #007bff;
}
.container{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-family: 'Poppins', sans-serif;
}
.container .mail-form{
    background: #fff;
    padding: 25px 35px;
    border-radius: 5px;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 
                0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.container form .form-control{
    height: 43px;
    font-size: 15px;
}
.container .mail-form form .form-group .button{
    font-size: 17px!important;
}
.container form .textarea{
    height: 100px;
    resize: none;
}
.container .mail-form h2{
    font-size: 30px;
    font-weight: 600;
}
.container .mail-form p{
    font-size: 14px;
}

That’s all, now you’ve successfully created a How to Send Mail using XAMPP Server with PHP. If your code doesn’t work or you’ve faced any errors/problems then please download the source code files from the given download button. It’s free and a .zip file will be downloaded and you’ve extracted it.

 

]]>
https://www.codingnepalweb.com/send-mail-using-xampp-server-with-php/feed/ 16