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.

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.
PHP Curl Request with Headers Example
Setting custom HTTP Headers with cURL is a subsidiary when transmuting Utilizer Agent or Cookies. Headers can be transmuted two ways, both utilizing the curl_setopt function. Controlling the cURL headers is done utilizing the CURLOPT_HTTPHEADER option. This can be utilizable if you optate to set custom request headers when performing a HTTP request through cURL in PHP. The CURLOPT_HTTPHEADER option is used with the curl_setopt function. For example, to add headers to a request, we simply place them in an Array, which can then be passed to the cul_setopt function. To change the User-Agent and Accept headers, we can simply do like shown below: $User_Agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31'; $request_headers = array(); $request_headers[] = 'User-Agent: '. $User_Agent; $request_headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; After having included all the request headers that you want, you need to pass on the Array to the curl_setopt function. Your request can then be carried out by calling curl_exec(). curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers); A complete version of the above can look like this: $url = "https://laravelcode.com/"; // Setting the HTTP Request Headers $User_Agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31'; $request_headers = array(); $request_headers[] = 'User-Agent: '. $User_Agent; $request_headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; // Performing the HTTP request $ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers); $response_body = curl_exec($ch); // Performs the Request, with specified curl_setopt() options (if any). The $response_body variable contains the response body, you can try to output it directly to the browser with echo, just be sure to match the mime-type of the resource (I.e. text/html). Delivering cookies in HTTP headers When Cookies are used by a website, a client will include them in the headers of its requests. So, to make cookies available to a website when visiting the site with cURL, we add them to a "Cookie" field. The cookie field contains all cookies for a site, so if there is more than one cookie, they should be separated by a semicolon (;). $cookies = 'CookieName1=Value;CookieName2=Value'; $request_headers[] = 'Cookie: '. $cookies; Note. Cookie Names must be unique.  Using cURL header options Alternatively, some headers can also be set with dedicated options in the curl_setopt function. Both the User-agent and Cookie headers can be set using the CURLOPT_USERAGENT and CURLOPT_COOKIE options respectively. This may be easier than adding the each header field manually. If we have both a cookie and a user-agent string stored in variables, as shown below: $User_Agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31'; $cookies = 'CookieName1=Value;CookieName2=Value'; We can simply feed them directly via curl_setopt: curl_setopt($ch, CURLOPT_USERAGENT, $User_Agent); curl_setopt($ch, CURLOPT_COOKIE, $cookies); Compared to using an Array, this may be easier. However, which method you choose to use, is mostly down to your own personal preferences.