Blog

  • Correct file permissions for WordPress on Apache

    File permission is a simple yet complex issue. If you manage a website, you need to ensure that the file permissions are adequate so as to allow users to perform operations on the file and at the same time, you need to ensure that file permissions are strict enough to prevent security and hacking incidents.

    Wrong permissions will break your automatic updates. Also, if you run composer, you may struggle as composer should not be run as root or sudo user, and non-root user would need read/write permissions to run composer.

    This situation usually arises when you run a website on a self-managed server like the one provided by DigitalOcean or Amazon AWS Lightsail. However, the permissions are equally valid for managed or shared hosting where the host has provided you the SSH access to your files.

    In this article, I have provided simple file permissions for your WordPress website hosted on Apache server. These permissions should be sufficient for most of your websites, including those which are not built on WordPress.

    Giving the correct file permissions to your WordPress website

    To begin with, Apache server runs all the processes requires to read/write the website files & directories. So, we need to provide the ownership of the website files & directories to Apache. As Apache runs as www-data, following command is appropriate to give ownership of your entire website folder to www-data user and group.

    In your SSH terminal, run the following command.

    sudo chown -R www-data:www-data /var/www/wordpress

    Here, I am assuming that your wordpress website root is /var/www/wordpress. You can change it to the directory in which your website is hosted.

    Now, we need to give all file permissions (read, write, execute) to owner (Apache server) because server needs to perform read/write operations on files & directories. It will ensure that our website runs smoothly without error.

    Giving read/write permissions to www-data is fine for your website to run and auto-update without any errors. But, if you try to SSH into your server as a non-root user, you will not be able to read/write your files inside the wordpress directory.

    Also, if you use composer, you need read/write access to website files. As per composer’s official documentation, it is recommended that you should NOT run composer as root or sudo user. You should run composer as non-root user. Same is true for other utilities as well which require read/write permissions in your wordpress directory. This means we need more permissions.

    For this, I am assuming you have already created a new user with sudo privileges and have logged in through that sudo user (not root use).

    First, add you to the www-data group using the following simple command in your SSH terminal. Remember, you must be logged in as a non-root user, with sudo privileges, as whom you want to run composer.

    sudo adduser $USER www-data

    Above command adds you to www-data group.

    Now give read/write/execute permissions to all the files and folders to both owner and group.

    sudo find /var/www/wordpress -type d -exec chmod 770 {} ;
    sudo find /var/www/wordpress -type f -exec chmod 660 {} ;

    Update: Recently I was facing following error while running these commands-

    `find: missing argument to -exec'

    I fixed that by adding a slash before the terminating semicolon.

    So, the update commands are-

    sudo find /var/www/wordpress -type d -exec chmod 770 {} \;
    sudo find /var/www/wordpress -type f -exec chmod 660 {} \;

    You need to log out and log in again for the new permissions to take effect.

    That’s it. You now have the correct permissions.

    How to check if your WordPress website has correct file permissions

    After setting up file permissions, you must validate the new file permissions. To check this, try the following two things-

    • Run composer and check if there is any permission error.
    • Try uploading a file in the WordPress media library.

    If you are able to execute the above two operations successfully without error, your WordPress website has the correct file permissions.

  • Customize your link preview on Facebook

    When you share a link to your post on Facebook or Twitter, it automatically generates a preview card with a title, description, and optional image. This preview helps your post visibility by presenting it in an attractive manner to other users.

    This preview can be customized for all our pages using Open Graph Protocol (OGP) created by Facebook. Twitter supports this protocol adding a few tags of its own as well. In this post, I will discuss the required meta tags to customize your link preview.

    In this article, based on the Open Graph Protocol, I will tell you the exact tags to be added in the head section of your blog. This will transform your posts into rich social objects on Facebook, Twitter etc.

    What is Open Graph Protocol

    Open Graph Protocol is a schema to assign properties to a web page which can be easily understood by the compliant applications. Open Graph Protocol is implemented through meta tags in the head section of HTML web page and is loosely based on other existing schema technologies.

    Open Graph Protocol provides different meta tags to be added to your page to customize the different elements of a web page as well as to define a lot of other properties for that page.

    Though we can add all the tags defined in the Open Graph Protocol for a webpage or blog post, it will be redundant and will add to extra code. So, in this post, we will look at the basic required meta tags which will be sufficient for your customized link previews on Facebook & Twitter.

    Customizing a link preview

    If you look at your link preview of a post you shared on Facebook or Twitter, you will observe that there are three important elements-

    • Title
    • Short Description
    • Image

    These are the visible elements which are needed in a link preview. Apart from these, there are two more properties, which are type and url.

    Type defines the type of web page. For blog posts and news articles, it is ‘article’. Url is the canonical url of the object. This acts as a unique id for the object in the entire graph. In case of multiple pages sharing same data like comment pages on a blog post, this url remains same.

    Apart from this, Facebook requires you to add their FB App ID in another meta tag. As described in my previous post on the topic Social Sharing Buttons, you can easily get your Facebook app id from your Facebook for Developers dashboard.

    In case of Twitter, though it defines it’s own tags, it officially supports the Open Graph Protocol as well. So, if you add separate Twitter meta tags along with Open Graph tags, Twitter tags will be redundant. So, in the interest of keeping our code concise, we will only add those Twitter tags, which are not covered by Open Graph Protocol.

    Twitter only requires one extra meta tag, ‘twitter:card’, which we will add in our code.

    Let’s take a look at the final code.

    <meta property="og:type" content="article" />
    <meta property="og:title" content="Title of your page">
    <meta property="og:description" content="Description of your page">
    <meta property="og:image" content="Image/url/of/your/post's/featured/image">
    <meta property="og:url" content="Canonical/url/to/your/page">
    <meta property="fb:app_id" content="Your_FB_App_ID" />
    <meta property="twitter:card" content="summary_large_image">

    You can see that "og:type" and "twitter:card" tags are static and will remain the same for all blog posts. "fb:app_id" will also remain the same if you are using same app id for entire website.

    You will have to modify four tags as per your post data- "og:title", "og:description", "og:image", "og:url".

    Paste these tags in the head section of your HTML page. Your page is now rich social object.

    Sometimes Facebook or Twitter fetches wrong values for these tags, or sometime they may not even able to fetch any data. Also, you may have changed the post title, description or image after the page has been fetched by Facebook/Twitter. As Facebook & Twitter cache their data for many days, you may not be able to see the updated data when you share that link.

    In such cases, you may use the Facebook Sharing Debugger which shows how Facebook looks at the Open Graph Meta of your page and shows you the open graph data currently saved by Facebook for your post. It also allows you to force Facebook to fetch the data again, in case, there is a discrepancy.

    What happens when there are no Open Graph meta tags on your page

    If there are no Open Graph meta tags on a page, Facebook tries to get that data automatically based on page content. Usually, the title of the page is taken as title. Description is taken from the description meta tag, if available. Otherwise, it takes first few lines from the content. Similarly, the first image found on the page which is larger than 200×200 pixels id taken as image.

    There is no confirmation that in the absence of Open Graph meta tags, Facebook will take only these values. It can take any value as defined by their fetching algorithms. So, to avoid this uncertainty, it is always advised to add the above seven meta tags to all your web pages.

    Conclusion

    So, you can see that Facebook’s Open Graph Protocol is currently kind of a universal protocol to define social properties of a web page. It is supported by Twitter and many other social networks.

    It is very easy to implement as it requires adding only seven basic tags. You can add many more tags by referring to the Open Graph Protocol Documentation.

    So, don’t wait anymore. If you have not yet implemented the Open Graph meta tags in your blog or website, it is important that you do it now.

  • JSON-LD: Add Structured Data to improve SEO

    JSON-LD: Add Structured Data to improve SEO

    Adding structured data like JSON-LD to your blog or website is a very important search engine optimization (SEO) technique. It helps Google to understand your content better and helps your website to get a better search ranking.

    What is Structured Data

    Structured data is a standard format to add information to a page which can be easily understood by search engines to identify the content of the page. For example, if you have a cooking blog, Google needs to understand if a particular page is for recipe and if yes, it needs to extract key information from that page to match with the user query. Structured data helps Google by directly providing this information.

    Structured data is comprised of predefined properties which are based on schema.org.

    There are multiple formats to add structured data to your website. The three most popular formats which are supported by Google are-

    • JSON-LD
      This is a subset of JSON where all the properties are defined in the head section of an HTML page.

    • Microdata
      In the Microdata format, structured data properties are nested within HTML content by using HTML tag attributes.

    • RDFa
      Similar to Microdata, RDFa uses HTML tag attributes which are officially HTML5 extension.

    Out of these three, Google recommends using JSON-LD for structured data whenever possible.

    So, our focus in this post will be only on JSON-LD. There is no use to add multiple structured data formats. One structured data format implemented efficiently is enough for Google to understand the key information provided by our content.

    JSON-LD is the easiest to implement among all other structured data formats as it is consolidated at a single place in the head section. Also, the JSON structure is easy to create either manually or through programming making it very fast to implement. The cluttered approach of Microdata & RDFa is something which actually results in errors in implementing structured data. JSON-LD is free from all that mess.

    The content on internet is mainly written in the form of blogs containing a lot of blog posts. So, in this article, I will tell you how to implement JSON-LD for a blog post.

    Though, schema.org provides a large number of properties for each page type, it is not necessary for you to implement all those properties. A few important ones are enough.

    Implementation of JSON-LD in a Blog Post

    First of all, let’s take a look at the complete JSON-LD snippet to be added to the head section of a blog post. Then, I will explain each property. Most of the properties are self explanatory.

    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "BlogPosting",
      "headline": "Enable browser caching on Apache server using htaccess",
      "description": "Browser caching for all types of files can be easily done using Apache's .htaccess file. This simple configuration results in a faster website, less consumption of bandwidth and better user experience.",
      "mainEntityOfPage": "https://abhineet.in/enable-browser-caching-apache-server-htaccess",
      "image": "https://abhineet.in/assets/images/logo.jpg",
      "datePublished": "2019-08-06",
      "dateModified": "2019-08-06",
      "author": {
        "@type": "Person",
        "name": "Abhineet Mittal",
        "description": "Abhineet is IIM Alumnus and Founder of popular Digital Publishing Platform, Sahityapedia. He is a technology enthusiast by hobby &amp; an avid reader.",
        "image": "https://abhineet.in/assets/images/logo.jpg",
        "url": "https://abhineet.in/about"
      },
      "publisher": {
        "@type": "Organization",
        "name": "abhineet.in/",
        "logo": {
          "@type": "ImageObject",
          "url": "https://abhineet.in/assets/images/logo.jpg"
        }
      }
    }
    <script>

    In this code, I have taken JSON-LD from one of the blog posts of this blog. Let’s discuss each element used in this code.

    • The entire JSON-LD snippet has to be wrapped inside <script type="application/ld+json"> and </script> tags.
    • @context is standard and should be used as-is.
    • The most relevant type for a blog post in schema.org is BlogPosting. So, we will use that for @type.
    • Headline is the page title. This title will be visible on the Google search results page.
    • Description is a short summary of the page, and like Heading, it will be visible on the Google search results page.
    • mainEntityOfPage defines that the topic discussed is the primary topic for this page. That means it has to have canonical URL.
    • Image is URL to featured post or thumbnail of this post.
    • datePublished & dateModified are self-explanatory.
    • Author adds nested properties to define a Person. Add your name, description (biography), image and URL.
    • Finally, Publisher is similar to Author, but it indicates an organization and must have name and logo properties.

    Interestingly, according to schema.org, Publisher can be either Person or Organization. But Google only accepts Organization as a Publisher. So, do not use Person there.

    Finally, you can validate your schema using Google Structured Data Testing Tool. If you see any error, try to fix it based on the comments provided by Google.

    And that’s it. Your blog posts are now SEO ready which can be easily understood by Google.

    Make sure you do not stuff structured data with unrelated content. Structured data should clearly describe the actual content in the blog post. Doing otherwise, will hurt your search ranking as Google’s algorithm’s are smart enough to notice any discrepancies.

    When all this is done, wait for a few days and observe the change in your search rankings. Properly implemented structured data will definitely boost the search ranking of your blog bringing in more traffic.

  • Social Sharing Buttons without Javascript

    If you are developing a website, it is imperative to have social sharing buttons to increase social engagement which in turn will result in higher traffic. A lot of widgets are available for this purpose.

    The Pros

    Adding a single line of Javascript adds all the popular sharing buttons to your website. Some services allow you to customize them through remote dashboards. They also add share count and other metrics to your buttons.

    From button styling to icons, everything is handled by these widgets. All you have to do is select which buttons to show and style of those buttons.

    These services also provide cloud-hosted analytics data where you can easily monitor the visitor and their sharing pattern of different posts.

    The Cons

    When you add these widgets, they simply add the Javascript SDKs of these social websites which load the sharing button and other metrics like the number of shares, likes, etc. along with the buttons.

    This may seem good, but it adds a lot of processing to the webpage. This results in higher load time and thus, lower ranking in search engine result pages (SERP).

    A major portion of your added analytics becomes redundant if you already have Google Analytics code installed on your website. Social analytics can also be implemented through events in Google Analytics, thus making additional tracking redundant. In most cases, social analytics added by these sharing buttons adds little value.

    Also, many of these services, track your visitors and you have no option to opt-out of it. They get all the traffic data of your website, slowing down your website with their trackers, and you have no control of that. For a webmaster, this is an uneasy situation.

    The Simple Solution: No Javascript

    The simple solution is to eliminate all the Javascript and add simple HTML buttons with sharing links provided by almost all social networks. This entire code will be purely HTML and CSS without Javascript.

    I have created sharing buttons for some popular social networks and included the required CSS for the buttons. You can add your styles as well. In case you need an even better look, you can also add icons to your buttons.

    The CSS

    First, let’s create CSS for these buttons.

    .button {
      text-decoration: none;
      display: inline-block;
      text-align: center;
      padding: .25rem .5rem;
      font-size: 1rem;
      font-weight: 300;
      border-radius: .2rem;
      color: black;
      background-color: white;
    }
    
    .button-facebook {
      background-color: #4267b2;
      color: white;
    }
    
    .button-twitter {
      background-color: #1DA1F2;
      color: white;
    }
    
    .button-whatsapp {
      background-color: #25D366;
      color: white;
    }

    Facebook

    In the case of Facebook, you will also need a Facebook App ID which is very easy to get. Don’t worry, you do not have to create an app. Just go to Facebook for Developers dashboard, and fill the form with new app details. A Facebook app will be created and added to your Facebook developers account. Once you get the app id, use it in the following code to add simple Facebook sharing buttons.

    <a href="https://www.facebook.com/dialog/share?app_id=your-app-id&href=https://example.com/link-to-your-post" target="_blank" title="Share on Facebook" class="button button-facebook" rel="noopener noreferrer">Facebook</a>

    Twitter

    <a href="https://twitter.com/intent/tweet?url=https://example.com/link-to-your-post&text=Post-Title&via=your-twitter-username" target="_blank" title="Share on Twitter" class="button button-twitter" rel="noopener noreferrer">Twitter</a>

    WhatsApp

    <a href="//example.com/link-to-your-post" target="_blank" title="Share on WhatsApp" class="button button-whatsapp" rel="noopener noreferrer">WhatsApp</a>

    These are just three, but you can add any number of buttons of different social networks based on the sharing link provided in their documentation.

    These links are simple HTML and CSS with NO Javascript. They do not add extra load on your page and give you the required functionality. You may miss the share count displayed on your sharing buttons, but it is not needed and the downsides of adding it to your website are simply not worth it.

    So, just add these buttons to your website posts and pages to replace the heavy sharing widgets, and move towards a faster, cleaner code and a fast loading website.

  • Add url rewriting router to PHP built-in server

    While developing a project, PHP built-in server is much more flexible and easy to use compared to desktop setups like LAMP, XAMP, WAMP, etc.

    However, without Apache, you also lose access to the magical and powerful .htaccess feature where you can create simple rewrite rules.

    What if our application needs such rewrites like loading .html files for permalinks without extension?

    Don’t worry. PHP provides an excellent and simple solution for this as well. You can create your router.php and call it while starting the server. Now, you are free to add any rewrite rule or any other condition to run your code.

    To do this, create a file named router.php in your project root. You can choose any name for this file, but router.php provides the right context.

    In this use case, I have a static website with all the static content like HTML, CSS, etc. But my permalinks are without HTML extension, though the file name is the same. I want to write a router that can rewrite my permalinks to .html version and at the same time, not mess us my style (.css) and script (.js) files.

    Here is the code which I wrote for my particular use case. You can modify it to suit your requirements.

    // router.php
    
    // Get the url path and trim leading slash
    $url_path = trim( $_SERVER[ 'REQUEST_URI' ], '/' );
    
    // If url_path is empty, it is root, so call index.html
    if ( ! $url_path ) {
        include( 'index.html' );
        return;
    }
    
    // If url_path has no dot, it is a post permalink, so add .html extension
    if( ! preg_match( '/[.]/', $url_path ) ) {
        include( $url_path . '.html' );
        return;
    }
    
    // In case of css files, add the appropriate header
    if( preg_match( '/[.css]/', $url_path ) ) {
        header("Content-type: text/css");
        include( $url_path );
        // You can do the same for other file types as well
    }

    Your router.php is ready. Now, open your terminal, go to the project root and start the PHP server with the following command.

    pathtophp.exe -S localhost:8000 router.php

    Finally, open your website by going to localhost:8000 on your browser. It works. Great.

    Please note that this method is good for small applications so that you can quickly do a test run and check the code without deploying it on a proper server. In the case of bigger applications, this setup may become complicated as it is difficult to scale.

  • Enable browser caching in WordPress using htaccess

    Browser caching is very important for any website as it helps in speeding up the website as well as reduces bandwidth costs.

    To enable browser caching on Apache, you must have the required modules enabled.

    If you are on a shared host like GoDaddy or HostGator, these modules are already enabled in most cases. So, you can skip the following steps and directly go to the htaccess code given at the end of this post.

    In case, you are on a cloud server like DigitalOcean, you may need to enable these modules which can be done in following easy steps.

    Open your terminal and run following two commands.

    sudo a2enmod headers
    sudo a2enmod expires

    Now restart the Apache server by running following command.

    systemctl restart apache2

    It will ask for authentication. Enter your password and Apache will restart.

    You have successfully enabled Headers and Expires modules on your Apache server.

    Now, open the root folder of your website and create a .htaccess file with the following content.

    # BEGIN Webroris.com cache-control
    <IfModule mod_expires.c>;
        ExpiresActive on
        ExpiresDefault "access plus 2 days"
        ExpiresByType image/gif "access plus 1 month"
        ExpiresByType image/png "access plus 1 month"
        ExpiresByType image/jpg "access plus 1 month"
        ExpiresByType image/jpeg "access plus 1 month"
        ExpiresByType image/x-ico "access plus 1 month"
        ExpiresByType image/x-icon "access plus 1 month"
        ExpiresByType text/html "access plus 1 seconds"
        ExpiresByType text/xml "access plus 1 seconds"
        ExpiresByType text/plain "access plus 1 seconds"
        ExpiresByType text/css "access plus 1 month"
        ExpiresByType text/javascript "access plus 1 month"
        ExpiresByType application/xml "access plus 1 seconds"
        ExpiresByType application/rss+xml "access plus 1 seconds"
        ExpiresByType application/json "access plus 1 seconds"
        ExpiresByType application/javascript "access plus 1 month"
        ExpiresByType application/x-javascript "access plus 1 month"
        ExpiresByType application/pdf "access plus 1 month"
      <IfModule mod_headers.c>;
           Header unset ETag
           Header unset Pragma
           Header unset Last-Modified
           Header append Cache-Control "public, no-transform, must-revalidate"
           Header set Last-modified "Tue, 1 Oct 2014 10:10:10 GMT"
      </IfModule>;
    </IfModule>;
    # END Webroris.com cache-control

    And that’s it. You do not have to restart your server now as .htaccess file works in real-time. All the files served from your server will now be cached in the user’s browser as per the expires directive mentioned in the .htaccess file. You may also change these to any value of your liking.

  • Should you quit your job for CAT Preparation?

    Should you quit your job for CAT Preparation?

    Common Admission Test (CAT) is the gateway to IIMs and other prestigious business schools in India. But at the same time, it is regarded as one of the toughest exams to crack due to very high competition.

    A lot of aspirants prepare for CAT after their graduation while on a job. And if you are in a hectic job, you may find it very difficult to concentrate on your studies.

    So what should one do in such a scenario? Is it a wise choice to quit the job and start CAT preparation with full dedication? Or, is it possible to prepare for CAT while working full time? Let’s find out.

    As a business manager, in life, you will have to make difficult decisions. Consider this decision as one of them. And to take any important decision, you need to sit calmly and think about what options do you have and what would be the outcome of each option.

    CAT is not a knowledge-intensive exam. It is a conceptual exam which needs a lot of practice. The syllabus of CAT is very limited. One can easily cover the basic concepts in a couple of months. The time taking part is to practice as many questions as you can. And practice needs discipline and sincerity.

    It does not matter how many hours a day you study. What matters is that you do it every day, even though it is only for one hour each day. This kind of regularity is needed to master the concepts. Another aspect is mock tests, which you should take very sincerely.

    If you are preparing for CAT or planning to start soon, you can read my detailed article here: How to start preparing for CAT

    The complete list of books and material you will need for your CAT preparation can be found here: List of Important CAT Preparation Books

    Now lets come to why people quit their jobs to prepare for CAT. Most of the time it is a bad manager, less salary or disillusionment with the current job. It makes sense to leave something for something much better. But you have to decide the right time to do it.

    Having a job has multiple advantages for your CAT preparation as described below.

    1) Without a job, you are in a do-or-die situation

    If you have a job, no matter what happens, your career is not ruined. A jobless preparation becomes a do-or-die scenario because one has to have a career no matter how they perform in CAT. This puts undue pressure on the candidate and many times they are not even able to concentrate as much as they could if they prepared along with their jobs.

    2) Job gives you a routine

    This may seem trivial, but when you are working, you have a fixed routine everyday. You wake up on time, go to office, eat on time, sleep on time. Your efficiency is very high and you try to utilize every free minute you find during the day to prepare for CAT. When you leave your job, you have no compulsion to follow this routine anymore. And that’s where you lose focus. Without a routine, without discipline, you unknowingly waste time and your efficiency gets low. Combined with the first point above, it is a disastrous situation to be in.

    3) Pre-MBA experience matters in campus placements

    If you left your job for preparation and got into your dream B-School, your pre-MBA job experience will still play a role in your campus placements. It is usually easier to answer job based questions in interview compared to academics. Many companies count this experience to calculate offered CTC and designation. Even a few months of extra experience may get you a higher position at a better salary compared to your classmates.

    4) A gap is a negative point in your CV

    Quitting job to prepare for CAT puts a gap in your CV which is hard to defend in any job interview. No matter what you say, you are seen as a quitter who could not handle job pressure along with studies. This may not be true for you, but for an interviewer, this matters and it can ruin one’s chances to get the job.

    5) A job is your plan B

    Job acts as a plan B in case things do not turn out as you wish. A lot of aspirants argue that thinking about a plan B is doubting their capability even before they start. This thinking is wrong, as it does not consider the unpredictable scenarios. One may be perfectly capable of cracking the exam, but life is full of uncertainties and it does not harm to have a backup option.

    6) Your savings will help you pay your bills

    This may not look like a critical point, but it does have its own importance. If you are selected into multiple B-Schools, sometimes you need to pay booking amount for multiple colleges in case you are waiting for your dream college convert. Your savings from job will help you pay these. Also, with each passing year, MBA is getting more expensive. Even if you get into an IIM, you will have to pay more than 20 lakh rupees just in fees, accommodation, food etc. Add your personal expenses to this, and the amount will increase even more. Though you will easily get collateral free education loan as this is a risk free loan for banks, it will definitely ease you if you have some savings from your job which you can use either to pay first installment of fees or for your personal expenses.


    All these factors are important and should be considered while making the decision.

    When I was preparing for CAT, I was working too. I was tempted to leave my job based on reasons similar to most other CAT aspirants. It was a very hectic job coupled with many other factors. But I did not. And it was a good decision.

    I always advise against leaving your job for CAT preparation. However, there may be exceptions and one should take this decision based on their own circumstances.

    I hope my experience and views will help you make the right decision.

  • How to count words in Unicode string using PHP

    How to count words in Unicode string using PHP

    How to count words in Unicode string using PHP?

    How to count words in Unicode string using PHP? This sounds too easy. After all, PHP has so many string manipulation functions. To count words, we can simply use str_word_count and we are good to go. But there is a problem.

    While this function works fine for English strings, developers find this function unpredictable as sometimes it also counts some symbols. But the real problem is that this function doesn’t work accurately for Unicode strings.

    I faced this problem while working on one of my websites which is entirely in Hindi. When I searched, I was surprised to find that there is no straight forward solution or function to do this. There should be a standard function which should work for all languages, but the variation in structure of languages does not allow this.

    A new function to count words in Unicode string using PHP

    So, I wrote a small function which can be used anywhere to count the words in a Unicode string and works for a large number of popular languages. It first removes all the punctuation marks & digits to ensure that we do not count them as words. Then it replaces all white space blocks, including tab, new line etc., by a single space character.

    Now all words of the string are separated by a single space separator. We can simply split/explode them into an array and count its elements to find the word count.

    You can see the code below.

    Just copy this code to your PHP project and start using this function to count words in any Unicode string.

    And this is equally good for English strings as well. I found it more accurate than str_word_count.

    Remember, it will work accurately for all those strings where spaces are used for word separation. But it may not work accurately for languages like Mandarin, where words are not separated by spaces.

    Please do let me know how you like this article "How to count words in Unicode string using PHP" through comments section below.

  • I missed you too

    I missed you too

    It was the best she ever looked. She was determined to fix everything today. Her flowing hair shining like gold fluttered through the breeze. Once again she looked at her cellphone mirror. “Perfect. He would love to see me.” She said to herself.

    It was a bright day, full of sunshine. As she walked by the corner of the main market road, her eyes followed her image reflecting in the huge front glasses of the shops. “He still loves me like old days. We will be together now.” She couldn’t resist talking to herself.

    After a long walk along the market main road, the residential area was in sight. She took a deep breath to prepare herself once again. She felt even more confident causing her to speed up. The white castle was now just a few steps away.

    It was a small bungalow painted pure white. When sun gazed at it in broad daylight, it shined like a dazzling white monument surrounded by lifeless stones. She crossed the gate and walked inside into the main hall.

    He was sitting in a corner on a wooden chair with a small table in front of him. There was a glass chess on the top of the table and it seemed like the game was at full swing. He was in deep thought thinking about the next move and didn’t notice her arrival.

    She quietly walked towards him and sat on the empty chair opposite to him. He was still immersed in the game looking into the emptiness. Something clicked and he rose his head with a huge smile. “Check & mate.” he cheerfully declared. His eyes were shining like he has won the world.

    She looked at him & smiled. His happiness made her happy. His joy made her cheerful. For a while, she forgot why she was here and felt the moment. He won. She felt as if she had won too.

    She waited for a few seconds as he settled down. As he rose his head, he finally noticed her. Along with the smile, a tear came rolling down his cheek. He was speechless. She was as beautiful as she had always been.

    He rose up from his chair and moved towards her. She rose up too. He hugged her so tightly as if this moment was going to last forever. It was what they both always wanted, to be together.

    A loud voice startled them both. “How dare you?” A huge man appeared from the inner house with an angry face. “Get out now, or I will call the police.”

    He froze and felt helpless loosening his arms around her. But she was determined today. While she held his hand, her other hand slowly slipped into her purse which was hanging on her shoulder and she grabbed something. A loud sound, and the man was lying on the floor, surrounded by his own blood. “It ends today” She murmered.

    She turned back to see him horrified. “It’s over. No one is going to hurt us anymore. We will go far away from all this. I missed you so much.” As he looked in shock, she slipped her gun back into her handbag and started walking towards the door still holding his hand.

     

     

    “I missed you too, Mom” he finally said and followed her out while looking back at his father’s motionless body. The headline of a local newspaper kept on the center table loudly read “Mentally unstable wife accuses husband of child abuse, escapes from asylum.”

  • List of Important CAT Preparation Books

    List of Important CAT Preparation Books

    A lot of candidates ask me about the important CAT (Common Admission Test) Preparation books to be referred while preparing for CAT.

    In this post, I will give you complete list of important books for CAT Preparation. Also, I will share some good resources/material which will help you a lot in your CAT preparation.

    I have included links to most of the books & resources. This list is the latest list of books updated for CAT 2019 preparation.

    If you are preparing for CAT or planning to start soon, you can read my detailed article here: How to prepare for CAT

    List of Important CAT Preparation Books

    The All-in-one

    If you are not willing to go through multiple reviews for CAT preparation books, you may go for this bundled package of 4 books for complete CAT preparation by Arun Sharma And Meenakshi Upadhyay.

    Continue reading below for topic-wise list of books from multiple authors as well as some additional books.

    Quantitative Ability

    There are two good books for Quantitative Ability. Practicing only one of these is enough for your preparation.

    How to Prepare for Quantitative Aptitude for the CAT by Arun Sharma

    This is the most popular book for quant preparation. It is a very good book with questions segregated into different difficulty levels.

    Quantitative Aptitude Quantum CAT For Admission into IIMs by Sarvesh K. Verma

    This is another good book. It was suggested to me by a friend and I referred to this book for my Quant preparation.

    Verbal Ability

    This is the most important section of CAT which becomes the reason for unexpected CAT scores. Following books should be referred for this section.

    Word Power Made Easy by Norman Lewis

    This is the most important book of your entire CAT preparation. Read it from end-to-end as per the instructions in the book and your vocab would never be the same.

    How to Prepare for Verbal Ability and Reading Comprehension for CAT by Arun Sharma & Meenakshi Upadhyay

    This is a good book for Verbal Ability and can be used as the base reference.

    Wiley’s ExamXpert Verbal Ability and Reading Comprehension for CAT 2019

    This is another popular book for verbal and reading comprehension preparation. You should go only for one of these two books.

    Apart from these, for Verbal Ability and Reading Comprehension section, you must have excellent English language skills which can be developed through regular reading. I have written a detailed article about this which you can read here: How to Develop the Habit of Reading

    Data Interpretation & Logical Reasoning

    DI & LR are very scoring sections of CAT and should be handled very efficiently. I have listed three books here- two individual books for DI & LR each, and one book for both DI & LR. Do not get all three. Either get first two books, or the third one.

    How to Prepare for Data Interpretation for the CAT by Arun Sharma

    This book by Arun Sharma is a popular choice for DI.

    How to Prepare for Logical Reasoning for the CAT by Arun Sharma

    This is a book on Logical Reasoning by Arun Sharma.

    Logical Reasoning and Data Interpretation for the CAT by Nishit K. Sinha

    This is a good book which covers both the Data Interpretation & Logical Reasoning. You can practice DI & LR questions from this book.

    Previous Year’s Papers

    Once you get through the basics, start practicing previous year’s papers. It will give you a good idea about the exam. You can choose any book as the questions are going to be the same. The following is the latest available book containing last 24 years CAT solved papers.

    24 years CAT Topic-wise Solved Papers (2017-1994) with 6 Online Practice Sets 11th edition

    Study Material

    If you complete these books, you may also refer to the study material of any one good coaching institute. No need to collect material from multiple institutes. You can even take someone’s old material which may be equally useful.

    For quant, study material may not be of much use to you as you will get a lot of questions in various books. But the study material may prove beneficial for Verbal Ability, Data Interpretation & Logical Reasoning. Try to practice all the questions from these topics.


    I hope this information would prove useful to you and you will crack the CAT and secure a seat in an IIM.

    All The Best.