Skip to content

Archive / page 98

All articles

Every practical article from the Nalar archive, newest first.

Web Development Updated 07 Sep 2025 2 min read

Finding the Last Day of a Month in PHP

Finding the number of days in a month is useful for reporting, billing periods, scheduling, and date validation. PHP can do this directly with its date APIs, including support for leap years. A Simple getLastDay Function The following function accepts a month in YYYY-MM format and returns the number of days in that month: function getLastDay(string $month): int { $date = new DateTimeImmutable($month . '-01'); return (int) $date->format('t'); } How the Code Works Create a date for the first day of the month

Web Development Updated 07 Sep 2025 2 min read

Extracting Usernames from Social Media URLs with PHP

Web applications sometimes need to extract a profile identifier from a social-media URL for normalization, imports, or display. PHP’s URL parsing functions are usually easier to maintain than one large regular expression because they let you validate the hostname and path separately. A parseUsername Function The following example supports several common profile URL formats: function parseUsername(string $url): string { $host = strtolower((string) parse_url($url, PHP_URL_HOST)); $path = trim((string) parse_url($url, PHP_URL_PATH), '/'); $supportedHosts = [ 'twitter.com', 'www.twitter.com', 'x.com', 'www.x.com', 'medium.com', 'www.medium.com', 'facebook.com', 'www.facebook.com', 'vimeo.com', 'www.vimeo.com', 'instagram.com', 'www.instagram.com', ]; if (!in_array($host, $supportedHosts, true) || $path === '') { return $url; } return explode('/', $path)[0]; } How It Works Parse the hostname and path

Linux Updated 02 Sep 2025 2 min read

Synchronizing Files with `rsync` over SSH

rsync is a reliable tool for copying and synchronizing files locally or between machines. When the remote side is accessed through SSH, the transfer is encrypted and can use the same authentication model as normal SSH sessions. Basic Remote Synchronization A common command is: rsync -avP /home/user/documents/ user@example.com:/home/user/backup/ The options are:

JavaScript Updated 02 Sep 2025 1 min read

Truncate Text to a Maximum Length in JavaScript

User interfaces often need a shortened preview of longer text. A small helper can truncate a string to a maximum length and append an ellipsis when necessary. function limitText(text, limit) { if (typeof text !== 'string') return ''; if (!Number.isInteger(limit) || limit < 0) { throw new RangeError('limit must be a non-negative integer'); } if (text.length <= limit) return text; return `${text.slice(0, limit)}...`; } Examples:

JavaScript Updated 02 Sep 2025 1 min read

Extract a YouTube Video ID from a URL with JavaScript

YouTube links appear in several common formats, including youtube.com/watch?v=..., youtu.be/..., Shorts URLs, and embed URLs. A small JavaScript helper can normalize those formats and return the video ID. Use the URL API function getYouTubeVideoId(input) { const url = new URL(input); if (url.hostname === 'youtu.be') { return url.pathname.slice(1).split('/')[0] || null; } if (url.hostname.endsWith('youtube.com')) { if (url.pathname === '/watch') { return url.searchParams.get('v'); } const match = url.pathname.match(/^\/(?:embed|shorts|live)\/([^/?]+)/); return match?.[1] ?? null; } return null; } Examples console.log(getYouTubeVideoId('https://www.youtube.com/watch?v=QOM0xWASUwE')); console.log(getYouTubeVideoId('https://youtu.be/QOM0xWASUwE')); console.log(getYouTubeVideoId('https://www.youtube.com/embed/QOM0xWASUwE')); console.log(getYouTubeVideoId('https://www.youtube.com/shorts/QOM0xWASUwE')); Each returns:

JavaScript Updated 02 Sep 2025 2 min read

Remove Duplicates from JavaScript Arrays

Removing duplicates depends on what “duplicate” means for your data. Primitive values, objects with unique IDs, and records compared by several properties need different strategies. Primitive Values with Set const values = [1, 2, 3, 2, 4, 3]; const unique = [...new Set(values)]; console.log(unique); // [1, 2, 3, 4] Keep the First Object for Each ID const items = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice again' }, ]; const seen = new Set(); const unique = items.filter((item) => { if (seen.has(item.id)) return false; seen.add(item.id); return true; }); Keep the Last Object for Each ID A Map naturally overwrites earlier values for the same key:

Database Updated 07 Sep 2025 2 min read

Exporting and Restoring MongoDB Databases with `mongodump` and `mongorestore`

Backups are an important part of MongoDB administration. Two standard command-line tools for logical backups and restores are mongodump and mongorestore, which work with BSON data and collection metadata. 1. Back Up a Database with mongodump Use mongodump to create a BSON backup that can later be restored. Basic syntax: mongodump -d <database_name> -o <backup_directory> -d <database_name> → the database to back up. -o <backup_directory> → the directory where the dump will be written. Example:

Database Updated 07 Sep 2025 2 min read

Using MongoDB Aggregation to Build Hierarchical Category Structures

Applications often need to represent hierarchical data such as parent categories, child categories, and deeper descendants. MongoDB’s aggregation framework includes $graphLookup, which can recursively traverse relationships within a collection. This article shows how to use $graphLookup to retrieve a category hierarchy from documents that reference their parent category. 1. Data Structure Consider the following documents in a MongoDB collection: { "_id" : 1, "cat_id" : 1, "title" : "Parent Category", "parent" : null } { "_id" : 2, "cat_id" : 2, "title" : "Child Category", "parent" : 1 } { "_id" : 3, "cat_id" : 3, "title" : "Sub Child Category", "parent" : 2 } The relationships are:

JavaScript Updated 07 Sep 2025 1 min read

Sort JavaScript Object Arrays by a Property Value

JavaScript comparator functions make it straightforward to sort arrays of objects by a numeric property. const data = [ { name: 'Edward', order: 21 }, { name: 'Sharpe', order: 37 }, { name: 'And', order: 45 }, { name: 'The', order: -12 }, { name: 'Magnetic', order: 13 }, { name: 'Zeros', order: 37 }, ]; Descending Order const sorted = data.toSorted((a, b) => b.order - a.order); This places the largest order value first.

Database Updated 07 Sep 2025 2 min read

How to Create Users and Databases in MySQL

Managing users and databases is a fundamental MySQL administration task. This guide shows how to create a user, create a database, and grant that user the permissions needed to work with the database. 1. Create a New MySQL User Start by creating a user with its own login credentials. Basic syntax: CREATE USER 'user' IDENTIFIED BY 'password'; 'user': the username to create. 'password': the password for that user. Example:

Python Updated 02 Sep 2025 2 min read

Finding Text in a String with a Custom Python Function

Python already provides several ways to search strings, but sometimes you want more than a yes/no result. For example, a search interface may need to return a snippet containing the matching keyword plus some surrounding context. A Context-Aware Search Function def find_text(text, keyword, context=100): index = text.find(keyword) if index == -1: return None start = max(index - context, 0) end = min(len(text), index + len(keyword) + context) return text[start:end] The function:

Python Updated 02 Sep 2025 2 min read

Processing API Data with `requests` and Lambdas in Python

Python’s requests library makes HTTP calls straightforward, while small lambda functions can be useful as transformation or sorting keys. This article shows how to combine them without turning simple data processing into hard-to-read one-liners. Install requests python -m pip install requests Fetch JSON from an API import requests response = requests.get( "https://jsonplaceholder.typicode.com/posts", timeout=10, ) response.raise_for_status() data = response.json() Two details matter here:

JavaScript Updated 02 Sep 2025 1 min read

Find Text and Extract Context from a JavaScript String

Sometimes a search result is more useful when it includes nearby text instead of returning only an index. A small helper can find a substring and return a configurable amount of context around it. function findTextContext(text, query, context = 100) { const index = text.indexOf(query); if (index === -1) return null; const start = Math.max(0, index - context); const end = Math.min(text.length, index + query.length + context); return text.slice(start, end); } Example const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor.'; const result = findTextContext(text, 'consectetur', 20); console.log(result); The helper finds the first occurrence and includes up to 20 characters before and after it.

JavaScript Updated 07 Sep 2025 2 min read

Filter JavaScript Arrays Quickly and Clearly

Array.prototype.filter() creates a new array containing only the elements that satisfy a predicate. It does not modify the original array. Filter by a Condition const values = [1, 2, 3, 4, 5, 6]; const even = values.filter((value) => value % 2 === 0); console.log(even); // [2, 4, 6] Filter Objects by a Property const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, ]; const age25 = users.filter((user) => user.age === 25); Remove Duplicates For primitive values, a Set is usually clearer than using filter() with indexOf:

JavaScript Updated 02 Sep 2025 2 min read

Manage Asynchronous Operations with Promises and Async/Await in JavaScript

Promises represent values that may become available later. async and await provide syntax for working with promises using control flow that resembles synchronous code. Create a Promise function callFirstName() { return new Promise((resolve) => { setTimeout(() => resolve('John'), 1000); }); } A promise can be fulfilled with resolve or rejected with reject.

Web Development Updated 07 Sep 2025 3 min read

Understanding HTTP Status Codes in Laravel: A Developer's Guide

HTTP status codes tell clients whether a request succeeded, failed, requires authentication, or encountered another condition. Choosing the right status code makes Laravel APIs easier to consume and helps clients implement predictable error handling. 200: OK Use 200 OK when a request succeeds and the response includes a representation or other useful content. Common cases: A successful GET request that returns data. A successful update that returns the updated resource. A successful action endpoint that returns a result. 201: Created Use 201 Created after successfully creating a new resource, usually from a POST request.

Web Development Updated 07 Sep 2025 3 min read

Managing Image Uploads and Resizing with Laravel and Intervention Image

Image handling is a common requirement in web applications. Uploading original files, creating thumbnails, converting formats, and cleaning up old files all need to be handled consistently. Laravel’s filesystem abstraction works well with image-processing libraries such as Intervention Image. The code in this article uses the classic Intervention Image v2-style API (Image::make, fit, and encode). Intervention Image v3 uses a different API, so check the package version installed in your project before copying the example directly.