Search

PHP's Articles

PHP is a popular general-purpose scripting language that is especially suited to web development. It was originally created by Rasmus Lerdorf in 1994; the PHP reference implementation is now produced by The PHP Group.

Integrating Laravel and WordPress: A Powerful Combination for Content and Functionality
Integrating frameworks with content management systems is far from new in web development. Doing so empowers developers to leverage the strengths of both platforms effectively and unlock new possibilities. In this vein, integrating Laravel and WordPress offers a powerful combination. Indeed, combining Laravel and WordPress offers significant advantages, not just for managing content but also for enhancing website functionality. By marrying Laravel's robust framework capabilities with WordPress's user-friendly content management, developers can achieve a dynamic and feature-rich web solution. Understanding Laravel First things first, if you’re unfamiliar with Laravel, let us take a moment to introduce it. Laravel stands as a PHP framework renowned for its efficiency and flexibility in web development. At its core, Laravel simplifies the intricate process of building web applications by providing a structured and expressive syntax. This framework incorporates several key features that elevate its appeal among developers: Eloquent ORM: Enables smooth interaction with databases using an expressive and intuitive syntax. Blade Templating Engine: Offers a dynamic and efficient templating system for creating layouts with reusable components. Routing: Streamlines the definition of application routes, making navigation seamless and organized. Middleware: Facilitates filtering HTTP requests entering your application, ensuring a secure and controlled environment. Artisan Console: A command-line tool that automates repetitive tasks, enhancing productivity during development. Laravel's robust ecosystem, extensive documentation, and supportive community make it a preferred choice for developers seeking speed, scalability, and maintainability in their web projects. Its user-friendly nature and emphasis on modern PHP principles contribute to its standing as a leading PHP framework.   What Laravel Offers to WordPress With introductions in order, it may already seem obvious that integrating Laravel and WordPress can yield tremendous results. Still, let us be thorough and explore this synergy in some depth. Laravel is a powerful ally to WordPress, complementing its functionalities and addressing some limitations. While WordPress excels in content management, it can face complex web functionalities and scalability constraints. Indeed, WP Full Care finds that such constraints may not often concern average users, but they limit advanced users. With this in mind, Laravel steps in to augment WordPress by offering: Advanced Functionality: Laravel's robust backend capabilities enrich WordPress with complex functionalities. These include advanced user authentication, intricate data handling, and customized routing systems. Scalability and Performance: Laravel's performance optimization tools and scalable architecture help overcome WordPress's limitations when dealing with large-scale applications. They help ensure smoother handling of high traffic and complex operations. Enhanced Security: Laravel's security features, including its robust authentication system and middleware, fortify WordPress against potential vulnerabilities. This synergy empowers developers to create sophisticated, secure, high-performance web applications. At the same time, it allows them to benefit from the familiarity and ease of WordPress for content management.   Benefits for Content Having covered the fundamentals, let’s now delve into specifics. First, in terms of content, this synergy enhances content management in significant ways. Famously, WordPress stands out for its user-friendly content management system, offering intuitive tools for creating, editing, and publishing content. Whether in Ubuntu or user-friendlier systems, these perks remain. Still, by integrating Laravel's MVC (Model-View-Controller) architecture, content structuring and management become more efficient and organized. This collaboration enables developers to leverage Laravel's structured approach to handling data and business logic, making content management more streamlined and adaptable. In addition, the integration facilitates seamless content creation, editing, and publication workflows. It allows for incorporating Laravel's functionalities to enhance content presentation, enrich user experiences, and efficiently manage content-related tasks. Ultimately, it empowers content creators and developers with a powerful blend of WordPress's ease of use and Laravel's structured approach.   Benefits for Functionality And second, this synergy opens doors to a realm of enhanced capabilities. By harnessing Laravel's robust backend functionalities alongside WordPress, developers can infuse their projects with a potent blend of features. Laravel's user authentication, authorization, and security prowess bolsters WordPress's foundation, elevating the overall system's safety and reliability. This integration allows for advanced security measures and finely tailored user access controls, ensuring a fortified environment for users and data. Additionally, leveraging Laravel's routing and middleware functionalities within WordPress enables seamless integration of intricate functionalities. Developers can use Laravel's powerful routing mechanisms and middleware to create sophisticated web applications within WordPress, unlocking a new level of customization, efficiency, and complexity. Ultimately, this collaboration empowers developers to build highly functional and secure web solutions. Best Practices for Integrating Laravel and WordPress Finally, effective integration relies on several best practices contributing to a seamless and secure amalgamation. In no particular order, consider the following: Code Organization and Structure: Establish a well-defined architecture that separates and categorizes functionalities between Laravel and WordPress. This ensures clarity in development and maintenance while enabling smooth interaction. Documentation: Maintain comprehensive documentation outlining integration processes, code structure, and any customizations made. This facilitates future troubleshooting and streamlines the onboarding process for new developers. Testing and Quality Assurance: Implement robust testing methodologies to validate the integrated system's functionalities. This includes unit, integration, and user acceptance testing to ensure reliability and functionality. Scalability Considerations: Design the integration with scalability in mind, allowing for future expansions or modifications without major disruptions to the system. Backup and Recovery Mechanisms: Implement reliable backup and recovery solutions to safeguard against data loss or system failures. Training and Support: Train the team managing the integrated system. As you do, offer ongoing support to address any issues or queries that may arise. In addition, remain mindful of updates and maintenance best practices: Version Control: Keep Laravel and WordPress updated with the latest versions and security patches. Plugin Compatibility: Monitor and update plugins to ensure platform compatibility. Data Consistency: Perform routine checks to maintain data integrity and consistency within the integrated system. Security Checks: Conduct regular security audits to identify and address vulnerabilities promptly. Adhering to these practices fosters a robust integration and ensures the combined system's longevity, reliability, and security. Moreover, this approach contributes to an optimal experience for developers and users, guaranteeing a stable and efficient integrated platform. Conclusion In conclusion, integrating Laravel and WordPress presents a formidable synergy for developers seeking to harness the strengths of both platforms. By merging Laravel's robust backend functionalities with WordPress's user-friendly content management, the integration offers a comprehensive solution that caters to complex web development needs while ensuring a seamless content creation experience. The amalgamation of these platforms empowers developers to build highly functional, secure, and scalable web applications. It bridges the gap between content management and advanced functionalities, enhancing efficiency and flexibility in web development.
Getting Started with Laravel in CodeLobster IDE
Laravel is probably one of the most promoted PHP frameworks at the moment. It has a huge team and an excellent knowledge base - many articles, video tutorials and detailed documentation. Professional programmers use it widely in their projects, so beginners also need to learn Laravel as soon as possible. Codelobster helps you to make a local Laravel installation quickly and effortlessly. There is no need to use the command line or download and run VirtualBox and Homestead virtual machine, which is larger than 2 GB. For the work we need our IDE and the latest version of XAMPP, which in all respects is suitable for the correct operation of the newest version of the framework. This article uses XAMPP 7.2.12, and we recommend that you install it too. Launch CodeLobster and go to the main menu "Tools" -> "Preferences" -> "PHP". Specify the path to the executable file "php.exe", in our system, for example, it looks like this - "D:/xampp-7.2.12/php/php.exe". Check "php.ini" file and make sure you have enabled all the necessary PHP-extensions such as php_bz2, php_curl, php_fileinfo, php_gd2, php_gettext, php_mbstring, php_exif, php_mysqli, php_pdo_mysql, php_pdo_sqlite, php_openssl and php_ftp. Now everything is ready, let's run MySQL and Apache servers and start the main work. Installing Laravel in CodeLobster IDE Go to the main menu "Project" -> "Create Project". In the dialog box that appears, select the type of the created project "Create Empty Laravel Project". Specify the project name, which we will place in the "htdocs" folder in the directory with the installed XAMPP. Enable the option "Create project in a new folder" and click "OK" to start the wizard to install the framework. We have to complete a few steps and enter the elementary settings. To connect the system to an existing database, select the "Use Database" checkbox and enter DB name, username and password. In the next dialog box, enter the server name and port. If MySQL is running on the local computer, then nothing needs to be changed at this stage. All data entered by us will be automatically saved in the "config/database.php" file, and later it can be changed manually simply by opening this file in the editor. At the next dialog, we have got an ability to choose additional official packages for the installation: Cashier - it provides an interface for working with Stripe and Braintree services for organizing an online payment system on the site. Envoy - a package for organizing the execution of various tasks on a remote server, this may be the execution of PHP code or the launch of macros with several sequential commands.  Horizon - it provides a control panel and an API for accessing the Redis queue service, this ensures faster operation of WEB applications. Passport - it provides advanced features for user authentication using the API, fully implements the OAuth2 authorization system. Scout - it implements the synchronization of your search index with the records in the model for working with the database and provides the ability to perform full-text search. Socialite - it allows OAuth authentication, so you can use the login with Google, Facebook, Twitter, LinkedIn, GitHub, GitLab and Bitbucket. Such tools will help in the work on large-scale projects, if you are just starting to learn the framework, you can skip this step for now. Click "Finish" and wait a little while CodeLobster downloads the current version of the framework and unpacks it into the designated directory. When the wizard has finished its work, we will check the correctness of the installation - open the address "http://localhost/laravel/public/" in your browser, it is in this folder the public files are stored. As you can see, the Laravel logo appeared, there are no error messages, which means everything is well. We can study the structure of the new project on the "Project" tab, and also edit the main settings of our WEB-application. If you are using a database connection, go to the file explorer in the left pane of the IDE and open the ".env" file in the editor, this file stores the environment variables. Find the line "DB_CONNECTION=mysql" and enter the parameters for connecting to MySQL. In our example, this fragment looks like this: DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=rootpassword Testing the Work of the Framework Laravel includes an object-relational mapping (ORM) system, it is called Eloquent and is an implementation of the Active Record design pattern (AR). The rules for naming classes, tables and their fields are used in order to unify ways of connecting objects and their corresponding tables and rows in the DB. In the database that we have connected to the current installation, there is a ready-made table on which we can practice. The name of the table is "countries", it contains the names of countries and phone codes - these are the "name" and "phonecode" fields. To use Eloquent, you need to create your own class that extends the "Model" class. Create a file "Country.php" in the "app" folder and add the following lines to it: <?php namespace App; use Illuminate\Database\Eloquent\Model; class Country extends Model {} According to the naming rules, a class called "Country" (in the singular) will represent entries in the table "countries". This is quite enough for now, the rest of the work for us will be done by the framework. To take advantage of the model for the data access, let's create a router - we will link the URL "http://localhost/laravel/public/countries" to the function of extracting records from the table. Routers for your WEB applications are stored in the "routes" folder, open the "web.php" file in the editor and add a few lines of your own code to it:    Route::get('/countries', function () {     $countries = App\Country::all();     $html = '<ul>'; foreach ($countries as $country) {   $html .= '<li>' . $country->name . '</li>'; } return $html .= '</ul>'; }); The IDE understands the structure of the Laravel project very well and provides hints and dynamic help on all the functions and classes included in the framework. It will be much easier for you to use all its advantages if you use autocomplete while typing by pressing the Ctrl + Space key combination to get the list of methods that are allowed in this context. When we execute our code, an array with information about countries will be extracted, it can now be passed to the view for formatting and display. In our educational example, we simply select the names of the countries and create an HTML list, and it will be displayed using the default view. Open the address "http://localhost/laravel/public/countries" in the browser and see an accurate list with the names of all countries from our database. Let's summarize In this article, we have learned how to quickly create a new project and install Laravel using the wizard in CodeLobster IDE. This is a universal approach - it is suitable for any operating system and does not require the use of the command line or the installation of additional software. The principle of operation of all MVC and ORM frameworks is the same. After reading this article, you have learned the basic steps to get started with Laravel, with this knowledge you will be able to easily and simply master other PHP libraries.
How to create a PHP package for Composer
PHP has become more popular programing language in website development. Composer is the one of the major key factor. Sometimes you need some functionality work that you already worked one project. Or when you search in the web, most of the time, you will already find that in github repository. In that case, you just have to download that library with git and put into your project, sometimes need to add your configurations and you can use that library in your poroject with composer. Composer is the PHP package manager by which you can use packages developed by community. You can also create your own package and share it with the other developers. In this tutorial article, we will create simple package and use it. I will create simple project which will provide IP address of the user. composer.json file To create package, first you need to initialize your package with composer.json file. composer.json is the file where your packge information is stored. To create composer.json file, run the bellow command: composer init When you run this command, it will ask for package information, like package name, description, author, type, licence etc.. It will also ask if your package requires other packages. After that, you can see bellow composer.json file. Here is the file that I have create. {     "name": "jiteshmeniya/ipgetter",     "description": "Get IP address of the user",     "type": "library",     "license": "MIT",     "authors": [         {             "name": "jiteshmeniya99",             "email": "jiteshmeniya99@gmail.com"         }     ],     "require": {} } Other than composer.json, there are also some files in the root of package. README.md file is the basic documentation that will describe about package and how to use it. LICENSE file is terms how other developers are allowed to use and modify package code. src is the main directory where all of your code are reside Now let's talk about code. Create file in the src directory. Remember your file name should be match with class defined in the file. You should create one class in one file. If you need another class, create a new file. Also you can not create multiple class with same name. It is recommend you use new classname for every file. I have created bellow class in src/getip/IPGetter.php file. <?php namespace IPGetter; class IPGetter {     /**      * get IP address of the user      *      * @return void      */     public static function getIPAddress()     {         return $_SERVER['REMOTE_ADDR'];     } } Now we have to modify composer.json file as we need to autoload all of src classes. {     "name": "jiteshmeniya/ipgetter",     "description": "Get IP address of the user",     "type": "library",     "license": "MIT",     "authors": [         {             "name": "jiteshmeniya99",             "email": "jiteshmeniya99@gmail.com"         }     ],     "require": {         "php": ">=5.6"     },     "autoload": {         "psr-4": {             "IPGetter\\": "src/getip"         }     } } In the require, we have added minimum php version reuired. So if your package has code that can only works in specific PHP version, you can specify here. So after that someone will try to install this will get error without install. Also in the autoload, we have added the class namespace, so all the files inside src/getip directory will be loaded namespace "IPGetter". Send package to Packagist. After package has been created, you can share it other developers with github and send it to packagist. By doing this, other developers can use your package with just one command. To upload your package to github, check this article[How to upload project to git?] Now go to Packagist and submit your Github package link. Now you will get command for install package. In my case I get command like this: composer require jiteshmeniya/ipgetter Use package in your Project Whenever you need to use package in your project, run that command in project. It will create vendor directory with with your package folder along with composer folder. composer folder loads all of vendor folders classes. There is also autoload.php file in vendor folder which includes composer folders all class. So all you have to do is include vendor/autoload.php file in your index.php file. I have created bellow index.php file and used package class. <?php require_once __DIR__ . '/vendor/autoload.php'; use IPGetter\IPGetter; $ip_address = IPGetter::getIPAddress(); echo($ip_address);exit; Conclusion In this way, you can also create dynamic and complex packages according to your requirement and use in your all projects. This way it also helps other developers to use your package and contribute to community. If you have any query or suggestion, please comment bellow.
Twitter API OAuth 2.0 Authorization Example
Twitter is one of the most powerful social network platform to promote your application. With Twitter API, you can make users follow, tweet, DM and much more directly from your website without opening twitter. In this article, we will learn about how to integrate Twitter API in your web application. To start with Twitter API, first create your Twitter developer account. Then create a new Application. Now you can get Consumer API keys from the generated Application in Keys and tokens tab. Don't forget to set appropriate permissions also from the permission tab. Here is the Twitter API request flow. Get bearer token Now from your code side, to create any Twitter API curl request, first create a new curl request to get bearer token and pass it in request header. To get bearer token, first encode consumer key and consumer secret in RFC 1738 method. Then from consumers credential now encode them in base64 format. RFC-1738-encoded-consumer-key:RFC-1738-encoded-consumer-secret And you will get string like this: eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw== Now you all you need to do is get bearer token with post CURL request with https://api.twitter.com/oauth2/token?grant_type=client_credentials this URL. Be sure to set header with Authorization: Basic bearer-token-credentials Content-Type: application/x-www-form-urlencoded Content-Length: 29 and you will get Bearer Token in bellow json format {     "token_type": "bearer",     "access_token": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" } Here is my request code in PHP language: <?php $consumer_api_key = rawurldecode('xvz1evFS4wEEPTGEFPHBog'); $consumer_api_secret = rawurldecode('L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg'); $base64_key = base64_encode($consumer_api_key.':'.$consumer_api_secret); $url = 'https://api.twitter.com/oauth2/token?grant_type=client_credentials'; $curl = curl_init(); curl_setopt_array($curl, array(     CURLOPT_URL => $url,     CURLOPT_RETURNTRANSFER => true,     CURLOPT_CUSTOMREQUEST => "POST",     CURLOPT_HTTPHEADER => array(         "authorization: Basic ".$base64_key,         "cache-control: no-cache",         "content-type: application/x-www-form-urlencoded"     ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) {   echo "cURL Error #:" . $err; } else {   echo $response; } ?> Create Twitter API request Now you have get access_teken which you can pass in header request in any Twitter API. Here is all lists of Twitter API. For example, if you want to get User data by screen name or id, just send GET request in https://api.twitter.com/1.1/users/show.json?screen_name=here-comes-twitter-screen-name URL. Here  is my request code in PHP: <?php $url = 'https://api.twitter.com/1.1/users/show.json?screen_name=twitterdev'; $access_token = 'AAAAAAAAAAAAAAAAAAAAAJEvBgEAAAAALuTinPbWuLuDuWA0NRr7ZE%3DCNtMfu1gXJYW8MQzAOBnlIqUz73oIWuRFjUSetGNFN3cYCANj8'; $curl = curl_init(); curl_setopt_array($curl, array(   CURLOPT_URL => $url,   CURLOPT_RETURNTRANSFER => true,   CURLOPT_CUSTOMREQUEST => "GET",   CURLOPT_HTTPHEADER => array(     "authorization: Bearer ".$access_token,   ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) {   echo "cURL Error #:" . $err; } else {   echo $response; } ?> Invalidate access_token You can also invalidate the generated token by the following request. <?php $consumer_api_key = rawurldecode('xvz1evFS4wEEPTGEFPHBog'); $consumer_api_secret = rawurldecode('L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg'); $base64_key = base64_encode($consumer_api_key.':'.$consumer_api_secret); $access_token = '$access_token'; $url = 'https://api.twitter.com/oauth2/invalidate_token?access_token='.$access_token; $curl = curl_init(); curl_setopt_array($curl, array(     CURLOPT_URL => $url,     CURLOPT_RETURNTRANSFER => true,     CURLOPT_CUSTOMREQUEST => "POST",     CURLOPT_HTTPHEADER => array(         "authorization: Basic ".$base64_key,         'Accept: */*',         'Content-Length: 119',         'Content-Type: application/x-www-form-urlencoded'     ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) {   echo "cURL Error #:" . $err; } else {   echo $response; } ?> Conclusion This way, you can create all Twitter API request from the access_token. I hope this article will help new developers to use Twitter API. Thank you all and have a happy twitting.
How to get Minimum Value Key in Associative Array in PHP
Today we will share with you one simple but very helpful tutorials of PHP. how to find the minimum values' key in an associative array in PHP. for example, you have the following array and you want to find the minimum value's key from the array. $pets = array( "cats" => 1, "dogs" => 2, "fish" => 3 ); you can get the minimum value's key from this array some following ways. Example : 1 $pets = array( "cats" => 1, "dogs" => 2, "fish" => 3 ); array_keys($pets, min($pets)); # array('cats') Example : 2 $pets = array( "cats" => 1, "dogs" => 2, "fish" => 3 ); array_search(min($pets), $pets); We hope it can be helped a lot.  
Use PHP Code into Laravel Blade
in this article, I will share with you how to write PHP code in laravel blade files. there is two ways you should be written PHP code in laravel's blade files. one if laravel provides one his framework method and the second one is the traditional  method of write PHP code in laravel blade file. I will share with you both of example here. Example : 1 @php $Categories = explode(',', $value->category_name); $CategoriesSlug = explode(',', $value->category_slug); @endphp Example : 2 category_name); $CategoriesSlug = explode(',', $value->category_slug); ?> i hope it will help you.
How to Send Email in PHP using PHPMailer
Sending main in PHP application is very basic functionality in any PHP web application. if you work on a live web application then you should need many times to send mail notification or send a simple mail to the application's end-use. you can send whatever in your mail. like send simple text content or you can also send some files in the mail by attachment. So, we will share with you in this article how to send mail in PHP using SMTP and in this example, we will also see how to send a file as an attachment in your mail. You can send mail in PHP my SMTP library it provides us much helpful mail function for sending mail and works with mail functionality in web application. you will see send mail using SMTP in PHP application is very easy. PHPMailer is one of the most popular open-source PHP libraries to send emails with. It was first released way back in 2001 and since then it has become a PHP developer’s favorite way of sending emails programmatically, aside from a few other fan favorites like Swiftmailer. If you don't want to install this library by composer then download manually from this GitHub link PHPMailer/PHPMailer Installing PHPMailer You can install PHPMailer using Composer: composer require phpmailer/phpmailer Example - 1 In the first example, we will see how to send mail in PHP without a file attachment. require_once "vendor/autoload.php"; //PHPMailer Object $mail = new PHPMailer; //From email address and name $mail->From = "from@yourdomain.com"; $mail->FromName = "Full Name"; //To address and name $mail->addAddress("recepient1@example.com", "Recepient Name"); $mail->addAddress("recepient1@example.com"); //Recipient name is optional //Address to which recipient will reply $mail->addReplyTo("reply@yourdomain.com", "Reply"); //CC and BCC $mail->addCC("cc@example.com"); $mail->addBCC("bcc@example.com"); //Send HTML or Plain Text email $mail->isHTML(true); $mail->Subject = "Subject Text"; $mail->Body = "<i>Mail body in HTML</i>"; $mail->AltBody = "This is the plain text version of the email content"; if(!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message has been sent successfully"; } Example - 2 In this example, we will see how to send mail in PHP with a file attachment. require_once "vendor/autoload.php"; $mail = new PHPMailer; $mail->From = "from@yourdomain.com"; $mail->FromName = "Full Name"; $mail->addAddress("recipient1@example.com", "Recipient Name"); //Provide file path and name of the attachments $mail->addAttachment("file.txt", "File.txt"); $mail->addAttachment("images/profile.png"); //Filename is optional $mail->isHTML(true); $mail->Subject = "Subject Text"; $mail->Body = "<i>Mail body in HTML</i>"; $mail->AltBody = "This is the plain text version of the email content"; if(!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message has been sent successfully"; } Here we are attaching two files i.e., file.txt which resides in the same directory as the script and images/profile.png which resides in images directory of the script directory. Using Gmail SMTP Example You can utilize the mail server of another host to send an email, but for this, you first need to have authentication. For example: to send an electronic mail from Gmail’s mail server you require to have a Gmail account. SMTP is a protocol utilized by mail clients to send an electronic mail to send a request to a mail server. Once the mail server verifies the electronic mail it sends it to the destination mail server. Here is an example of sending an electronic mail from Gmail’s mail server from your domain. You don’t need a local mail server to run the code. We will be utilizing the SMTP protocol: require_once "vendor/autoload.php"; $mail = new PHPMailer; //Enable SMTP debugging. $mail->SMTPDebug = 3; //Set PHPMailer to use SMTP. $mail->isSMTP(); //Set SMTP host name $mail->Host = "smtp.gmail.com"; //Set this to true if SMTP host requires authentication to send email $mail->SMTPAuth = true; //Provide username and password $mail->Username = "name@gmail.com"; $mail->Password = "super_secret_password"; //If SMTP requires TLS encryption then set it $mail->SMTPSecure = "tls"; //Set TCP port to connect to $mail->Port = 587; $mail->From = "name@gmail.com"; $mail->FromName = "Full Name"; $mail->addAddress("name@example.com", "Recepient Name"); $mail->isHTML(true); $mail->Subject = "Subject Text"; $mail->Body = "<i>Mail body in HTML</i>"; $mail->AltBody = "This is the plain text version of the email content"; if(!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message has been sent successfully"; } i hope you like this useful article.
How to Make Async Requests in PHP
While creating HTTP request to other websites,  sometimes we don't need to get response from the server. In this case we have to just send the HTTP request and should drop the connection, so we don't wait until request complete and complete the next process. This can be done from using sockets if we don't need to check about the response from the request. This is because socket connection can be terminated straight after sending the request without waiting. This is like fire and forget the request. To use the socket connection, there is fsockopen() function in PHP. I have used this function to send the HTTP request. Here is my full code to send HTTP request. /**  * Send a HTTP request, but do not wait for the response  *  * @param string $method The HTTP method  * @param string $url The url (including query string)  * @param array $params Added to the URL or request body depending on method  */ public function sendRequest(string $method, string $url, array $params = []): void {     // url check     $parts = parse_url($url);     if ($parts === false)         throw new Exception('Unable to parse URL');     $host = $parts['host'] ?? null;     $port = $parts['port'] ?? 80;     $path = $parts['path'] ?? '/';     $query = $parts['query'] ?? '';     parse_str($query, $queryParts);     if ($host === null)         throw new Exception('Unknown host');     $connection = fsockopen($host, $port, $errno, $errstr, 30);     if ($connection === false)         throw new Exception('Unable to connect to ' . $host);     $method = strtoupper($method);     if (!in_array($method, ['POST', 'PUT', 'PATCH'], true)) {         $queryParts = $params + $queryParts;         $params = [];     }     // Build request     $request  = $method . ' ' . $path;     if ($queryParts) {         $request .= '?' . http_build_query($queryParts);     }     $request .= ' HTTP/1.1' . "\r\n";     $request .= 'Host: ' . $host . "\r\n";     $body = http_build_query($params);     if ($body) {         $request .= 'Content-Type: application/x-www-form-urlencoded' . "\r\n";         $request .= 'Content-Length: ' . strlen($body) . "\r\n";     }     $request .= 'Connection: Close' . "\r\n\r\n";     $request .= $body;     // Send request to server     fwrite($connection, $request);     fclose($connection); } With this function, you can simply send asynchronous HTTP request. I hope it will help you.