<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mahfuzur Rahman on Medium]]></title>
        <description><![CDATA[Stories by Mahfuzur Rahman on Medium]]></description>
        <link>https://medium.com/@mahfuz34?source=rss-4c5b77fe77c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TLOBl6oU5joUJxplyNY97w.png</url>
            <title>Stories by Mahfuzur Rahman on Medium</title>
            <link>https://medium.com/@mahfuz34?source=rss-4c5b77fe77c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:24:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahfuz34/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Linux Terminal Cheat Sheet (From ZTM)]]></title>
            <link>https://medium.com/@mahfuz34/the-linux-terminal-cheat-sheet-from-ztm-8d9de9eb5c79?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d9de9eb5c79</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ztm]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Mon, 26 May 2025 07:14:10 GMT</pubDate>
            <atom:updated>2025-05-26T07:14:47.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHd3jBvTeXNho9T-qyD9qQ.avif" /></figure><h3>Getting Help in Linux</h3><h4>MAN Pages</h4><ul><li>Use man command to view the manual for a command.</li><li><strong>Example</strong>: man ls</li></ul><p>The man pages are navigated using the less command with shortcuts:</p><ul><li>h: Get help within less.</li><li>q: Quit less.</li><li>enter: Show next line.</li><li>space: Show next screen.</li><li>/string: Search forward for a string.</li><li>?string: Search backward for a string.</li><li>n / N: Next/previous appearance of the search term.</li></ul><h4>Checking Command Type</h4><ul><li>type rm: Check if rm is a shell built-in or an executable file.</li><li><strong>Example</strong>: rm is /usr/bin/rm</li><li>type cd: Check if cd is a shell built-in.</li><li><strong>Example</strong>: cd is a shell builtin</li></ul><h4>Getting Help for Shell Built-in Commands</h4><ul><li>help command: Get help for shell built-in commands.</li><li><strong>Example</strong>: help cd</li><li>command --help: Get help for executable commands.</li><li><strong>Example</strong>: rm --help</li></ul><h4>Searching Man Pages</h4><ul><li>man -k uname: Search for uname in all man pages.</li><li>man -k &quot;copy files&quot;: Search for &quot;copy files&quot; in man pages.</li><li>apropos passwd: Search for passwd related man pages.</li></ul><h3>Keyboard Shortcuts</h3><pre>TAB TAB: Display all commands or filenames starting with written letters.<br>CTRL + L: Clear the current line.<br>CTRL + D: Close the shell.<br>CTRL + U: Cut the current line.<br>CTRL + A: Move cursor to start of the line.<br>Ctrl + E: Move cursor to the end of the line.<br>CTRL + C: Stop the current command.<br>CTRL + Z: Sleep the running program.<br>CTRL + ALT + T: Open a terminal.</pre><h3>Bash History</h3><ul><li>history: Display the history.</li><li>history -d 100: Remove a specific line from history.</li><li>history -c: Clear the entire history.</li><li>echo $HISTFILESIZE: Print the number of commands saved in the history file.</li><li>echo $HISTSIZE: Print the number of history commands saved in memory.</li><li>!!: Rerun the last command.</li><li>!20: Run a specific command from history.</li><li>!-10: Run the last nth command.</li><li>!abc: Run the last command starting with abc.</li><li>!abc:p: Print the last command starting with abc.</li><li>CTRL + R: Reverse search through history.</li><li>HISTTIMEFORMAT=&quot;%d/%m/%y %T &quot;: Record date/time of each command (add to ~/.bashrc for persistence).</li></ul><h3>Getting Root Access (sudo, su)</h3><ul><li>sudo command: Run a command as root (for users in sudo or wheel group).</li><li>sudo su: Become root temporarily.</li><li>sudo passwd root: Set the root password.</li><li>passwd username: Change a user&#39;s password.</li><li>su: Become root (if root has a password).</li></ul><h3>Linux Paths</h3><h4>Paths</h4><ul><li><strong>Absolute</strong>: Starts with /</li><li><strong>Relative</strong>: Relative to the current location</li><li>.: Current working directory</li><li>..: Parent directory</li><li>~: User&#39;s home directory</li></ul><h4>Changing Directories</h4><ul><li>cd: To user&#39;s home directory</li><li>cd ~: To user&#39;s home directory</li><li>cd -: To the last directory</li><li>cd /path_to_dir: To path_to_dir</li><li>pwd: Print the current working directory</li></ul><h4>Installing Tools</h4><ul><li>sudo apt install tree: Installs the tree command</li></ul><h4>Using Tree</h4><ul><li>tree directory/: Example: tree .</li><li>tree -d .: Print only directories</li><li>tree -f .: Print absolute paths</li></ul><h3>The ls Command</h3><p>Usage: ls [OPTIONS] [FILES]</p><h4>Listing Directories</h4><ul><li>ls, ls .: Current directory</li><li>ls ~ /var /: Multiple directories</li></ul><h4>Options</h4><ul><li>-l: Long listing</li><li>-a: All files (including hidden)</li><li>-1: Single column</li><li>-d: Directory information</li><li>-h: Human-readable sizes</li><li>-S: Sort by size</li><li>-X: Sort by extension</li><li>--hide: Hide specific files</li><li>-R: Recursive listing</li><li>-i: Inode number</li></ul><h4>Disk Usage</h4><ul><li>du -sh ~: Size of home directory</li></ul><h4>File Timestamps and Date</h4><ul><li>ls -lu: Access time (atime)</li><li>ls -l, ls -lt: Modification time (mtime)</li><li>ls -lc: Change time (ctime)</li><li>stat file.txt: All timestamps</li><li>ls -l --full-time /etc/: Full timestamps</li></ul><h4>Modifying Timestamps with Touch</h4><ul><li>touch file.txt: Create or update timestamps</li><li>touch -a file, touch -m file: Modify atime or mtime</li><li>touch -m -t 201812301530.45 a.txt: Specific date/time</li><li>touch -d &quot;2010-10-31 15:45:30&quot; a.txt: Both atime and mtime</li><li>touch a.txt -r b.txt: Copy timestamps</li></ul><h4>Date and Calendar</h4><ul><li>date: Current date/time</li><li>cal, cal 2021, cal 7 2021: Calendars</li><li>cal -3: Previous, current, next month</li><li>date --set=&quot;2 OCT 2020 18:00:00&quot;: Set date/time</li></ul><h4>Sorting with ls</h4><ul><li>ls -l: Sorted by name</li><li>ls -lt: Sorted by mtime, newest first</li><li>ls -ltu: Sorted by atime</li><li>ls -ltu --reverse: Reverse order</li></ul><h3>Viewing Files (cat, less, more, head, tail, watch)</h3><h4>Displaying File Contents</h4><ul><li>cat filename: Display content</li><li>cat -n filename: Line numbers</li><li>cat filename1 filename2 &gt; filename3: Concatenate</li></ul><h4>Less Shortcuts</h4><ul><li>h: Help</li><li>q: Quit</li><li>enter: Next line</li><li>space: Next screen</li><li>/string: Search forward</li><li>?string: Search backward</li><li>n / N: Next/previous search result</li></ul><h4>Tail and Head</h4><ul><li>tail filename: Last 10 lines</li><li>tail -n 15 filename: Last 15 lines</li><li>tail -n +5 filename: Starting with line 5</li><li>tail -f filename: Real-time updates</li><li>head filename: First 10 lines</li><li>head -n 15 filename: First 15 lines</li></ul><h4>Monitoring Commands</h4><ul><li>watch -n 3 ls -l: Refresh every 3 seconds</li></ul><h3>Working with Files and Directories</h3><h4>Creating and Updating Files</h4><ul><li>touch filename: Create a new file or update timestamps.</li></ul><h4>Creating Directories</h4><ul><li>mkdir dir1: Create a new directory.</li><li>mkdir -p mydir1/mydir2/mydir3: Create nested directories.</li></ul><h4>The cp Command</h4><p>Copy files and directories:</p><ul><li>cp file1 file2: Copy file1 to file2.</li><li>cp file1 dir1/file2: Copy to another directory with a different name.</li><li>cp -i file1 file2: Prompt before overwrite.</li><li>cp -p file1 file2: Preserve permissions.</li><li>cp -v file1 file2: Verbose output.</li><li>cp -r dir1 dir2/: Recursively copy directories.</li><li>cp -r file1 file2 dir1 dir2 dest_dir/: Copy multiple items to a destination.</li></ul><h4>The mv Command</h4><p>Move or rename files and directories:</p><ul><li>mv file1 file2: Rename a file.</li><li>mv file1 dir1/: Move to a directory.</li><li>mv -i file1 dir1/: Prompt before overwrite.</li><li>mv -n file1 dir1/: Prevent overwriting.</li><li>mv -u file1 dir1/: Update based on modification time.</li><li>mv file1 dir1/file2: Move and rename.</li><li>mv file1 file2 dir1/ dir2/ dest_dir/: Move multiple items.</li></ul><h4>The rm Command</h4><p>Remove files and directories:</p><ul><li>rm file1: Remove a file.</li><li>rm -v file1: Verbose removal.</li><li>rm -r dir1/: Remove a directory.</li><li>rm -rf dir1/: Force removal without prompt.</li><li>rm -ri file1 dir1/: Prompt for each removal.</li></ul><h4>Secure File Deletion</h4><ul><li>shred -vu -n 100 file1: Securely overwrite and remove a file.</li></ul><h3>Piping and Command Redirection</h3><h4>Piping Examples</h4><ul><li>ls -lSh /etc/ | head: View the top 10 largest files.</li><li>ps -ef | grep sshd: Check if sshd is running.</li><li>ps aux --sort=-%mem | head -n 3: Top 3 processes by memory.</li></ul><h4>Command Redirection</h4><p>Redirect output and errors:</p><ul><li>ps aux &gt; processes.txt: Output to a file.</li><li>id &gt;&gt; users.txt: Append output.</li><li>tail -n 10 /var/log/*.log &gt; output.txt 2&gt; errors.txt: Separate output and errors.</li><li>tail -n 2 /etc/passwd /etc/shadow &gt; all.txt 2&gt;&amp;1: Redirect all to one file.</li><li>cat /var/log/auth.log | grep &quot;fail&quot; | wc -l: Count occurrences.</li></ul><h3>Finding Files with locate and find</h3><h4>locate</h4><ul><li>sudo apt install plocate: Install plocate.</li><li>sudo updatedb: Update the database.</li><li>locate filename: Find a file by name.</li><li>locate -i filename: Case insensitive search.</li><li>locate -b &#39;\filename&#39;: Exact name search.</li><li>locate -r &#39;regex&#39;: Regular expression search.</li><li>locate -e filename: Check file existence.</li><li>which command: Show command path.</li></ul><h4>find</h4><p>Search with various options:</p><ul><li>find ~ -type f -size +1M: Files over 1MB.</li><li>Options include -type, -name, -iname, -size, -perm, -links, -atime, -mtime, -ctime, -user, and -group.</li></ul><h3>Searching for Text Patterns with grep</h3><p>Usage: grep [OPTIONS] PATTERN FILE</p><h4>Options</h4><ul><li>-n: Print line number.</li><li>-i: Case insensitive.</li><li>-v: Invert match.</li><li>-w: Match whole words.</li><li>-a: Include binary files.</li><li>-R: Recursive search.</li><li>-c: Count matches.</li><li>-C n: Context display (n lines around the match).</li></ul><h4>Extracting ASCII Characters from Binary Files</h4><ul><li>strings binary_file: Example strings /bin/ls.</li></ul><h3>VIM — Text Editor</h3><h4>Modes</h4><ul><li>Command Mode: Default on entry.</li><li>Insert Mode: Editing text.</li><li>Last Line Mode: Save/exit commands.</li></ul><h4>Config File</h4><ul><li>VIM settings: ~/.vimrc.</li></ul><h4>Commands</h4><ul><li>i, I, a, A, o: Enter Insert Mode.</li><li>:w!, :q!, :wq!, :e!: Save/quit commands in Last Line Mode.</li><li>x, dd, ZZ, u, G, $, 0, ^: Editing commands in Command Mode.</li><li>/string, ?string, n, N: Search commands in Command Mode.</li><li>vim -o file1 file2: Open files in stacked windows.</li><li>vim -d file1 file2: Highlight differences.</li></ul><h4>Navigation</h4><ul><li>Ctrl+w: Switch between files.</li></ul><h3>Account Management</h3><pre>## Account Management<br>/etc/passwd # users and info: <br>/etc/shadow # users&#39; passwords<br>/etc/group # groups</pre><pre>## User Commands<br>useradd [OPTIONS] username # Create user.<br>usermod [OPTIONS] username # Modify user.<br>userdel -r username        # Delete user.</pre><pre>## Group Commands<br>groupadd group_name # Create group.<br>groupdel group_name # Delete group.</pre><pre>## Examples<br>useradd -m -d /home/john -c &quot;C++ Developer&quot; -s /bin/bash -G sudo,adm,mail john # Example of creating a user.<br>usermod -aG developers,managers john # Example of modifying a user.</pre><h4>Monitoring Users</h4><pre>## Commands<br>who -H    # User info.<br>id        # User info.<br>whoami    # User info.<br>w         # System usage.<br>uptime    # System usage.<br>last      # Login history.<br>last -u username # Login history for a specific user.</pre><h3>File Permissions</h3><h4>Understanding Permissions</h4><ul><li><strong>Legend</strong>: u (user), g (group), o (others), a (all), r (read), w (write), x (execute), - (no access).</li></ul><h4>Displaying Permissions</h4><ul><li>ls -l /etc/passwd: View file permissions.</li><li>stat /etc/shadow: Detailed permission stats.</li></ul><h4>Changing Permissions</h4><ul><li>chmod u+r filename: Add read to user.</li><li>chmod u+r,g-wx,o-rwx filename: Adjust multiple permissions.</li><li>chmod ug+rwx,o-wx filename: Set multiple permissions.</li><li>chmod ugo+x filename: Add execute to all.</li><li>chmod a+r,a-wx filename: Modify all permissions.</li></ul><h4>Absolute Mode</h4><ul><li>chmod 777 filename: Set all permissions for all.</li><li>chmod 755 filename: Read &amp; execute for group and others.</li><li>chmod 644 filename: Read-only for group and others.</li></ul><h4>Special Permissions</h4><ul><li><strong>SUID</strong>: chmod u+s executable_file.</li><li><strong>SGID</strong>: chmod g+s projects/.</li><li><strong>Sticky Bit</strong>: chmod o+t temp/.</li></ul><h4>UMASK</h4><ul><li>Display: umask.</li><li>Set new value: umask new_value.</li></ul><h4>Ownership</h4><ul><li>Owner: chown new_owner file.</li><li>Group: chgrp new_group file.</li><li>Both: chown new_owner:new_group file.</li><li>Recursive: chown -R new_owner file.</li></ul><h4>File Attributes</h4><ul><li>Display: lsattr filename.</li><li>Change: chattr +-attribute filename.</li></ul><h3>Processes</h3><h4>Process Viewing</h4><ul><li>type rm: Check if rm is built-in or executable.</li><li>ps: Processes in current terminal.</li><li>ps -ef, ps aux, ps aux | less: System processes.</li><li>ps aux --sort=%mem | less: Sort by memory usage.</li><li>ps -ef --forest: ASCII process tree.</li><li>ps -f -u username: Processes by user.</li><li>pgrep -l sshd, pgrep -f sshd, ps -ef | grep sshd: Check for sshd.</li><li>pstree, pstree -c: Hierarchical process tree.</li></ul><h4>Dynamic Real-Time View</h4><ul><li>top: Start system monitor.</li><li>top shortcuts: h for help, space for refresh, d for delay, etc.</li><li>top -d 1 -n 3 -b &gt; top_processes.txt: Top in batch mode.</li><li>Install htop for an interactive view.</li></ul><h4>Killing Processes</h4><ul><li>kill -l: List signals.</li><li>kill pid, kill -SIGNAL pid1 pid2 ...: Send signals.</li><li>kill -2 pid, kill -HUP pid: Send specific signal.</li><li>pkill process_name, killall process_name: Kill by name.</li><li>kill $(pidof process_name): Kill using pidof.</li></ul><h4>Background and Foreground Management</h4><ul><li>command &amp;: Run in background.</li><li>jobs: List jobs.</li><li>Ctrl + Z: Stop process.</li><li>fg %job_id: Resume in foreground.</li><li>bg %job_id: Resume in background.</li><li>nohup command &amp;: Immune to hangups.</li></ul><h3>Networking</h3><h4>Getting Network Interface Information</h4><ul><li>ifconfig: Enabled interfaces.</li><li>ifconfig -a, ip address show: All interfaces.</li><li>ifconfig enp0s3, ip addr show dev enp0s3: Specific interface.</li><li>ip -4 address: Only IPv4 info.</li><li>ip -6 address: Only IPv6 info.</li><li>ip link show, ip link show dev enp0s3: L2 info, including MAC.</li><li>route, route -n, ip route show: Default gateway.</li><li>systemd-resolve --status: DNS servers.</li></ul><h4>Setting Network Interfaces</h4><ul><li>ifconfig enp0s3 down, ip link set enp0s3 down: Disable interface.</li><li>ifconfig enp0s3 up, ip link set enp0s3 up: Enable interface.</li><li>ifconfig -a, ip link show dev enp0s3: Check status.</li><li>ifconfig enp0s3 192.168.0.222/24 up, ip address add 192.168.0.112/24 dev enp0s3: Set IP.</li><li>ifconfig enp0s3:1 10.0.0.1/24: Secondary IP.</li><li>route del default gw, ip route del default, ip route add default via: Default gateway.</li><li>ifconfig enp0s3 hw ether, ip link set dev enp0s3 address: Change MAC.</li></ul><h4>Netplan for Static Network Configuration on Ubuntu</h4><ol><li>Stop/Disable NetworkManager.</li><li>Create/Modify YAML in /etc/netplan.</li><li>Apply config: sudo netplan apply.</li><li>Verify: ifconfig, route -n.</li></ol><h3>OpenSSH Configuration and Management</h3><h4>Installation</h4><p><strong>Ubuntu</strong></p><p>sudo apt update &amp;&amp; sudo apt install openssh-server openssh-client</p><p><strong>CentOS</strong></p><p>sudo dnf install openssh-server openssh-clients</p><h4>Server Connection</h4><pre>ssh -p 22 username@server_ip  # Connect using default SSH port<br>ssh -p 22 -l username server_ip  # Connect with a specific username<br>ssh -v -p 22 username@server_ip  # Connect in verbose mode for detailed information</pre><pre># Ubuntu<br>sudo systemctl status ssh  # Check SSH status<br>sudo systemctl stop ssh    # Stop SSH service<br>sudo systemctl restart ssh # Restart SSH service<br>sudo systemctl enable ssh  # Enable SSH to start on boot<br>sudo systemctl is-enabled ssh  # Check if SSH is enabled on boot</pre><pre># CentOS<br>sudo systemctl status sshd  # Check SSH status<br>sudo systemctl stop sshd    # Stop SSH service<br>sudo systemctl restart sshd # Restart SSH service<br>sudo systemctl enable sshd  # Enable SSH to start on boot<br>sudo systemctl is-enabled sshd  # Check if SSH is enabled on boot</pre><h4>Security Configuration</h4><p>Edit /etc/ssh/sshd_config and then apply changes by restarting SSH:</p><ul><li>Change port: Port 2278</li><li>Disable root login: PermitRootLogin no</li><li>Restrict user access: AllowUsers user1 user2</li><li>Configure firewall to filter SSH access</li><li>Enable Public Key Authentication, disable password-based login</li><li>Use SSH Protocol 2 only</li><li>Set client session intervals and max attempts for security</li></ul><p>Remember to consult the man page (man sshd_config) for detailed configuration options.</p><h3>File Transfer Techniques with SCP and RSYNC</h3><h4>SCP Usage</h4><pre># Copy local file to remote host<br>scp a.txt john@80.0.0.1:~<br>scp -P 2288 a.txt john@80.0.0.1:~ # Custom port</pre><pre># Copy from remote to local<br>scp -P 2290 john@80.0.0.1:~/a.txt .</pre><pre># Copy entire directory to remote<br>scp -P 2290 -r projects/ john@80.0.0.1:~</pre><h4>RSYNC Commands</h4><pre># Sync local directory to local backup<br>sudo rsync -av /etc/ ~/etc-backup/</pre><pre># Mirror directory, deleting extraneous files from dest<br>sudo rsync -av --delete /etc/ ~/etc-backup/</pre><pre># Exclude files during sync<br>rsync -av --exclude-from=&#39;~/exclude.txt&#39; /source/ /dest/</pre><pre># Sync over SSH with custom port<br>sudo rsync -av -e &#39;ssh -p 2267&#39; /etc/ student@192.168.0.108:~/etc-backup/</pre><h4>Exclude Patterns Example</h4><pre># exclude.txt could include patterns like:<br>*.avi<br>music/<br>abc.mkv</pre><pre># Exclude specific file types during transfer<br>rsync -av --exclude=&#39;*.mkv&#39; /source/ /dest/</pre><h4>WGET for File Download</h4><pre># Install wget<br>sudo apt install wget # Ubuntu<br>sudo dnf install wget # CentOS</pre><pre># Basic file download<br>wget <a href="https://example.com/file.iso">https://example.com/file.iso</a></pre><pre># Resume incomplete download<br>wget -c <a href="https://example.com/file.iso">https://example.com/file.iso</a></pre><pre># Download with bandwidth limit<br>wget --limit-rate=100k <a href="https://example.com/file.iso">https://example.com/file.iso</a></pre><pre># Download multiple files<br>wget -i urls.txt # urls.txt contains list of URLs</pre><pre># Recursive download for offline viewing of a website<br>wget -mkEpnp <a href="http://example.org/">http://example.org</a></pre><p>Use these commands to efficiently copy files and directories across systems and for downloading content from the internet, ensuring data synchronization and maintaining web accessibility.</p><h3>NETSTAT and SS Usage</h3><pre># Display all ports and connections<br>sudo netstat -tupan<br>sudo ss -tupan</pre><pre># Check if port 80 is open<br>netstat -tupan | grep :80</pre><h3>LSOF Commands</h3><pre># List open files<br>lsof</pre><pre># Files opened by a specific user<br>lsof -u username</pre><pre># Files opened by a specific command/process<br>lsof -c sshd</pre><pre>Open files for TCP ports in LISTEN state<br>lsof -iTCP -sTCP:LISTEN<br>lsof -iTCP -sTCP:LISTEN -nP</pre><p>Use these commands to monitor network connections, check for open ports, and view files opened by users or processes, especially for security and troubleshooting.</p><h3>Nmap Scanning Guide</h3><pre># SYN Scan (root required)<br>nmap -sS 192.168.0.1</pre><pre># TCP Connect Scan<br>nmap -sT 192.168.0.1</pre><pre># Scan All Ports<br>nmap -p- 192.168.0.1</pre><pre># Scan Specific Ports<br>nmap -p 20,22-100,443,1000-2000 192.168.0.1</pre><pre># Service Version Detection<br>nmap -p 22,80 -sV 192.168.0.1</pre><pre># Ping Scan Network<br>nmap -sP 192.168.0.0/24</pre><pre># Skip Host Discovery<br>nmap -Pn 192.168.0.0/24</pre><pre># Exclude Specific IP from Scan<br>nmap -sS 192.168.0.0/24 --exclude 192.168.0.10</pre><pre># Output Scan to File<br>nmap -oN output.txt 192.168.0.1</pre><pre># OS Detection<br>nmap -O 192.168.0.1</pre><pre># Aggressive Scan<br>nmap -A 192.168.0.1</pre><pre># Read Targets from File &amp; Output to File without DNS Resolution<br>nmap -n -iL hosts.txt -p 80 -oN output.txt</pre><p>Only scan your own networks and systems, or those you have explicit permission to test. Unauthorized scanning can be illegal.</p><h3>Software Management with DPKG and APT</h3><h4>DPKG</h4><ul><li>View .deb file info: dpkg --info package.deb</li><li>Install from .deb: sudo dpkg -i package.deb</li><li>List installed programs: dpkg --get-selections or dpkg-query -l</li><li>Find by name: dpkg-query -l | grep ssh</li><li>List package files: dpkg -L openssh-server</li><li>Find owning package: dpkg -S /bin/ls</li><li>Remove package: sudo dpkg -r package</li><li>Purge package: sudo dpkg -P package</li></ul><h4>APT</h4><ul><li>Update index: sudo apt update</li><li>Install/update: sudo apt install apache2</li><li>List upgradable: sudo apt list --upgradable</li><li>Full upgrade: sudo apt full-upgrade</li><li>Remove: sudo apt remove package</li><li>Purge: sudo apt purge package</li><li>Auto remove dependencies: sudo apt autoremove</li><li>Clean cache: sudo apt clean</li><li>List all packages: sudo apt list</li><li>Search: sudo apt list | grep nginx</li><li>Show package info: sudo apt show nginx</li><li>List installed: sudo apt list --installed</li></ul><h3>Task Scheduling using Cron</h3><pre>crontab -e # Edit crontab<br>crontab -l # List tasks<br>crontab -r # Remove tasks</pre><pre># Schedule Format:<br>* * * * * command # Every minute<br>15 * * * * command # Hourly<br>30 18 * * * command # Daily<br>3 22 * * 1 command # Weekly<br>10 6 1 * * command # Monthly<br>@yearly command # Yearly<br>@reboot command # At reboot</pre><h3>Getting System Hardware Information</h3><h4>General Hardware</h4><pre>lshw               # Full hardware info<br>lshw -short        # Short format<br>lshw -json         # JSON format<br>lshw -html         # HTML format</pre><h4>CPU Information</h4><pre>lscpu              # CPU details<br>lshw -C cpu        # Hardware-specific CPU details<br>lscpu -J           # JSON format</pre><h4>Memory Information</h4><pre>dmidecode -t memory           # RAM specs<br>dmidecode -t memory | grep -i size<br>dmidecode -t memory | grep -i max<br>free -m                       # Memory usage</pre><h4>PCI and USB Devices</h4><pre>lspci                         # PCI buses and connected devices<br>lspci | grep -i wireless<br>lspci | grep -i vga<br>lsusb                         # USB controllers and devices<br>lsusb -v                      # Verbose output</pre><h4>Storage Devices</h4><pre>lshw -short -C disk<br>fdisk -l                      # List disks<br>fdisk -l /dev/sda<br>lsblk                         # Block devices list</pre><h4>Network Devices</h4><pre>lshw -C network<br>iw list                       # Wi-Fi cards<br>iwconfig                      # Wi-Fi configuration<br>iwlist scan                   # Wi-Fi networks scan</pre><h4>System Information via /proc</h4><pre>cat /proc/cpuinfo             # CPU info<br>cat /proc/meminfo             # Memory info<br>cat /proc/version             # System version<br>uname -r                      # Kernel version<br>uname -a                      # All system info</pre><h4>Battery Power</h4><pre>acpi -bi                      # Battery info<br>acpi -V                       # All ACPI info</pre><h4>Working with Device Files (dd)</h4><pre># Backup MBR<br>dd if=/dev/sda of=~/mbr.dat bs=512 count=1</pre><pre># Restore MBR<br>dd if=~/mbr.dat of=/dev/sda bs=512 count=1</pre><pre># Clone partition<br>dd if=/dev/sda1 of=/dev/sdb2 bs=4M status=progress</pre><p>Use these commands to check hardware specifications and perform operations with device files safely.</p><h3>Service Management</h3><pre># Analyze boot process<br>systemd-analyze<br>systemd-analyze blame</pre><pre># List active units<br>systemctl list-units<br>systemctl list-units | grep ssh</pre><pre># Service status<br>sudo systemctl status nginx.service</pre><pre># Stop service<br>sudo systemctl stop nginx</pre><pre># Start service<br>sudo systemctl start nginx</pre><pre># Restart service<br>sudo systemctl restart nginx</pre><pre># Reload service config<br>sudo systemctl reload nginx<br>sudo systemctl reload-or-restart nginx</pre><pre># Enable service at boot<br>sudo systemctl enable nginx</pre><pre># Disable service at boot<br>sudo systemctl disable nginx</pre><pre># Check if service is enabled at boot<br>sudo systemctl is-enabled nginx</pre><pre># Mask service<br>sudo systemctl mask nginx</pre><pre># Unmask service<br>sudo systemctl unmask nginx</pre><h4>Ubuntu</h4><pre>sudo systemctl status ssh       # Check SSH service status<br>sudo systemctl stop ssh         # Stop SSH service<br>sudo systemctl restart ssh      # Restart SSH service<br>sudo systemctl enable ssh       # Enable SSH to start on boot<br>sudo systemctl is-enabled ssh   # Check if SSH is enabled on boot</pre><h4>CentOS</h4><pre>sudo systemctl status sshd       # Check SSHD service status<br>sudo systemctl stop sshd         # Stop SSHD service<br>sudo systemctl restart sshd      # Restart SSHD service<br>sudo systemctl enable sshd       # Enable SSHD to start on boot<br>sudo systemctl is-enabled sshd   # Check if SSHD is enabled on boot</pre><h3>Security Configuration</h3><p>To configure security settings, edit /etc/ssh/sshd_config. Apply changes by restarting SSH. Key configurations include:</p><ul><li>Change SSH port: Port 2278</li><li>Disable root login: PermitRootLogin no</li><li>Restrict user access to specified users only: AllowUsers user1 user2</li><li>Configure the firewall to filter SSH access</li><li>Enable Public Key Authentication and disable password-based login</li><li>Use SSH Protocol 2 only</li><li>Set client session intervals and maximum attempts for increased security</li></ul><p><strong>Note</strong>: Consult the man page (man sshd_config) for detailed configuration options.</p><h3>Bash Programming</h3><h4>Bash Aliases</h4><pre>alias                     # List all aliases<br>alias name=&#39;command&#39;      # Create an alias<br>unalias name              # Remove an alias</pre><h4>Useful Aliases</h4><pre>alias c=&#39;clear&#39;<br>alias cl=&#39;clear; ls; pwd&#39;<br>alias root=&#39;sudo su&#39;<br>alias ports=&#39;netstat -tupan&#39;<br>alias sshconfig=&#39;sudo vim /etc/ssh/sshd_config&#39;<br>alias update=&#39;sudo apt update &amp;&amp; sudo apt dist-upgrade -y &amp;&amp; sudo apt clean&#39;</pre><h4>Interactive File Manipulation</h4><pre>alias cp=&#39;cp -i&#39;<br>alias mv=&#39;mv -i&#39;<br>alias rm=&#39;rm -i&#39;</pre><h4>Bash Variables</h4><pre>variable=&quot;value&quot;          # Define a variable<br>echo $variable            # Reference a variable<br>declare -r const=100      # Define a read-only variable<br>unset variable            # Unset a variable<br>env | grep PATH           # Find an environment variable<br>export PATH=$PATH:~/bin   # Modify the PATH variable</pre><h4>Special Variables</h4><pre>$0, $1, $2, ..., ${10}    # Script name &amp; positional arguments<br>$#                        # Number of positional arguments<br>&quot;$*&quot;                      # All positional arguments as a single string<br>$?                        # Exit status of the last command</pre><h4>Program Flow Control</h4><pre>if [ condition ]; then command; fi                          # Basic if statement<br>if [ condition ]; then command; else other_command; fi       # If-else statement<br>if [ condition ]; then command; elif [ condition ]; then...  # If-elif-else statement</pre><h4>Test Conditions</h4><pre># Numeric comparisons: -eq, -ne, -lt, -le, -gt, -ge<br># File checks: -s, -f, -d, -x, -w, -r<br># String comparisons: =, !=, -n (not zero), -z (is zero)<br># Logical operators: &amp;&amp; (and), || (or)</pre><h4>Loops and Functions</h4><pre>for i in {1..5}; do echo &quot;Loop $i&quot;; done               # For loop<br>while [ condition ]; do command; done                  # While loop<br>case &quot;$variable&quot; in pattern) command;; esac            # Case statement<br>function name() { command; }                           # Function definition<br>name() { command; }                                    # Alternative function syntax<br>name                                                   # Call a function</pre><h4>Command Examples</h4><pre>crontab -e    # Edit crontab file<br>crontab -l    # List crontab entries<br>crontab -r    # Remove crontab entries</pre><p>Combine these constructs to write effective bash scripts for task automation and system management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d9de9eb5c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Problem Solving Patterns: Basic To Advanced]]></title>
            <link>https://medium.com/@mahfuz34/problem-solving-patterns-basic-to-advanced-e66cff05dcdb?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e66cff05dcdb</guid>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 05:59:51 GMT</pubDate>
            <atom:updated>2025-03-12T05:59:51.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hyRYYMs0DeRNjfSh.jpg" /><figcaption>Collected From Google</figcaption></figure><h3>1. Sliding Window</h3><p><strong>Description:</strong> Used for contiguous subarray problems by maintaining a window that expands or shrinks.</p><p><strong>LeetCode Problems:</strong></p><p>3. Longest Substring Without Repeating Characters</p><p>424. Longest Repeating Character Replacement</p><p>209. Minimum Size Subarray Sum</p><h3>2. Two Pointers</h3><p><strong>Description:</strong> Uses two pointers to traverse a data structure efficiently.</p><p><strong>LeetCode Problems:</strong></p><p>167. Two Sum II — Input Array Is Sorted</p><p>125. Valid Palindrome</p><p>15. 3Sum</p><h3>3. Fast &amp; Slow Pointers (Floyd’s Cycle Detection)</h3><p><strong>Description:</strong> Uses two pointers moving at different speeds to detect cycles.</p><p><strong>LeetCode Problems:</strong></p><p>141. Linked List Cycle</p><p>142. Linked List Cycle II</p><p>202. Happy Number</p><h3>4. Frequency Counter</h3><p><strong>Description:</strong> It uses a hash map to count the occurrences of elements.</p><p><strong>LeetCode Problems:</strong></p><p>242. Valid Anagram</p><p>387. First Unique Character in a String</p><p>49. Group Anagrams</p><h3>5. Binary Search</h3><p><strong>Description:</strong> Efficiently finds an element in a sorted array by repeatedly dividing the search space.</p><p><strong>LeetCode Problems:</strong></p><p>704. Binary Search</p><p>33. Search in Rotated Sorted Array</p><p>153. Find Minimum in Rotated Sorted Array</p><h3>6. Divide and Conquer</h3><p><strong>Description:</strong> Breaks problems into smaller subproblems, solves them recursively, and combines results.</p><p><strong>LeetCode Problems:</strong></p><p>53. Maximum Subarray (Kadane’s Algorithm can also be used)</p><p>169. Majority Element</p><p>241. Different Ways to Add Parentheses</p><h3>7. Dynamic Programming (DP)</h3><p><strong>Description:</strong> Solves overlapping subproblems using memoization or tabulation.</p><p><strong>LeetCode Problems:</strong></p><p>70. Climbing Stairs</p><p>300. Longest Increasing Subsequence</p><p>416. Partition Equal Subset Sum</p><h3>8. Backtracking</h3><p><strong>Description:</strong> Explores all possible solutions recursively and backtracks when a condition is not met.</p><p><strong>LeetCode Problems:</strong></p><p>78. Subsets</p><p>39. Combination Sum</p><p>51. N-Queens</p><h3>9. Greedy Algorithm</h3><p><strong>Description:</strong> Makes local optimal choices at each step to get a globally optimal solution.</p><p><strong>LeetCode Problems:</strong></p><p>55. Jump Game</p><p>435. Non-overlapping Intervals</p><p>621. Task Scheduler</p><h3>10. Graph Traversal (BFS &amp; DFS)</h3><p><strong>Description:</strong> Uses BFS for shortest path problems and DFS for depth-first exploration.</p><p><strong>LeetCode Problems:</strong></p><p>200. Number of Islands</p><p>133. Clone Graph</p><p>127. Word Ladder (BFS)</p><h3>11. Union-Find (Disjoint Set Union — DSU)</h3><p><strong>Description:</strong> Helps detect cycles and find connected components.</p><p><strong>LeetCode Problems:</strong></p><p>684. Redundant Connection</p><p>547. Number of Provinces</p><p>990. Satisfiability of Equality Equations</p><h3>12. Topological Sorting</h3><p><strong>Description:</strong> Orders tasks in a dependency graph using DFS or Kahn’s algorithm.</p><p><strong>LeetCode Problems:</strong></p><p>207. Course Schedule</p><p>210. Course Schedule II</p><p>329. Longest Increasing Path in a Matrix</p><h3>13. Bit Manipulation</h3><p><strong>Description:</strong> Uses bitwise operations for optimization and mathematical tricks.</p><p><strong>LeetCode Problems:</strong></p><p>136. Single Number</p><p>78. Subsets (Bitmasking approach)</p><p>137. Single Number II</p><h3>14. Prefix Sum / Cumulative Sum</h3><p><strong>Description:</strong> Precomputes sums for fast range sum queries.</p><p><strong>LeetCode Problems:</strong></p><p>303. Range Sum Query — Immutable</p><p>523. Continuous Subarray Sum</p><p>560. Subarray Sum Equals K</p><h3>15. Monotonic Stack / Queue</h3><p><strong>Description:</strong> Uses a stack or queue to maintain increasing/decreasing sequences.</p><p><strong>LeetCode Problems:</strong></p><p>739. Daily Temperatures</p><p>84. Largest Rectangle in Histogram</p><p>496. Next Greater Element I</p><h3>16. Meet in the Middle</h3><p><strong>Description:</strong> Splits a problem into two halves to reduce complexity.</p><p><strong>LeetCode Problems:</strong></p><p>1755. Closest Subsequence Sum</p><p>1498. Number of Subsequences That Satisfy the Given Sum Condition</p><h3>17. Kadane’s Algorithm</h3><p><strong>Description:</strong> Finds the maximum sum subarray in O(n) time.</p><p><strong>LeetCode Problems:</strong></p><p>53. Maximum Subarray</p><p>918. Maximum Sum Circular Subarray</p><h3>18. Tree Traversals (DFS &amp; BFS)</h3><p><strong>Description:</strong> DFS uses Preorder, Inorder, Postorder; BFS explores level by level.</p><p><strong>LeetCode Problems:</strong></p><p>102. Binary Tree Level Order Traversal (BFS)</p><p>94. Binary Tree Inorder Traversal (DFS)</p><p>124. Binary Tree Maximum Path Sum</p><h3>19. Heaps (Priority Queue)</h3><p><strong>Description:</strong> Uses a min-heap or max-heap to efficiently find top elements.</p><p><strong>LeetCode Problems:</strong></p><p>703. Kth Largest Element in a Stream</p><p>215. Kth Largest Element in an Array</p><p>295. Find Median from Data Stream</p><h3>20. Top-K Elements Pattern</h3><p><strong>Description:</strong> Finds the top k largest or smallest elements using a heap or quickselect.</p><p><strong>LeetCode Problems:</strong></p><p>347. Top K Frequent Elements</p><p>973. K Closest Points to Origin</p><p>692. Top K Frequent Words</p><h3>21. Sliding Window Maximum (Deque Approach)</h3><p><strong>Description:</strong> Uses a deque to maintain max/min values efficiently.</p><p><strong>LeetCode Problems:</strong></p><p>239. Sliding Window Maximum</p><p>1696. Jump Game VI</p><h3>22. Morris Traversal (Tree Traversal Without Extra Space)</h3><p><strong>Description:</strong> Inorder traversal of a binary tree in O(1) extra space.</p><p><strong>LeetCode Problems:</strong></p><p>94. Binary Tree Inorder Traversal (without recursion or stack)</p><p>NB: ChatGPT helped me generate this List.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e66cff05dcdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ultimate Docker Cheat Sheet]]></title>
            <link>https://medium.com/@mahfuz34/ultimate-docker-cheat-sheet-2047f662602d?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2047f662602d</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 15:42:10 GMT</pubDate>
            <atom:updated>2025-02-02T15:42:10.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*rTkb0KOnY2hbr8rf.jpeg" /></figure><p>Here’s a <strong>Docker Cheat Sheet</strong> with all the essential commands and their explanations:</p><h3>Docker Basics</h3><ol><li>docker --version Check the installed Docker version</li><li>docker infoDisplay system-wide information about Docker</li><li>docker helpGet help on Docker commands</li></ol><h3>Docker Images</h3><ol><li>docker imagesList all locally available Docker images</li><li>docker pull &lt;image&gt;Download an image from Docker Hub</li><li>docker build -t &lt;image_name&gt; .Build a Docker image from a Dockerfile in the current directory</li><li>docker tag &lt;image_id&gt; &lt;repo_name&gt;:&lt;tag&gt;Add a tag to an image</li><li>docker rmi &lt;image_id&gt;Remove an image</li></ol><h3>Docker Containers</h3><ol><li>docker psList running containers</li><li>docker ps -aList all containers (including stopped ones)</li><li>docker run -d &lt;image&gt;Run a container in detached mode (background)</li><li>docker run -it &lt;image&gt; /bin/bashRun a container interactively with a Bash shell</li><li>docker run --name &lt;name&gt; -p 8080:80 &lt;image&gt;Run a container with a specific name and port mapping</li><li>docker stop &lt;container_id&gt;Stop a running container</li><li>docker start &lt;container_id&gt;Start a stopped container</li><li>docker restart &lt;container_id&gt;Restart a container</li><li>docker rm &lt;container_id&gt;Remove a stopped container</li><li>docker logs &lt;container_id&gt;View logs of a container</li><li>docker exec -it &lt;container_id&gt; /bin/bashAccess a running container’s shell</li></ol><h3>Docker Networks</h3><ol><li>docker network lsList all networks</li><li>docker network create &lt;network_name&gt;Create a new network</li><li>docker network rm &lt;network_name&gt;Remove a network</li><li>docker network inspect &lt;network_name&gt;View network details</li><li>docker network connect &lt;network&gt; &lt;container&gt;Connect a container to a network</li><li>docker network disconnect &lt;network&gt; &lt;container&gt;Disconnect a container from a network</li></ol><h3>Docker Volumes (Data Persistence)</h3><ol><li>docker volume lsList all volumes</li><li>docker volume create &lt;volume_name&gt;Create a volume</li><li>docker volume inspect &lt;volume_name&gt;Get volume details</li><li>docker volume rm &lt;volume_name&gt;Remove a volume</li><li>docker run -v &lt;volume_name&gt;:/data &lt;image&gt;Mount a volume to a container</li></ol><h3>Docker Compose</h3><ol><li>docker-compose upStart containers defined in docker-compose.yml</li><li>docker-compose up -dStart in detached mode (background)</li><li>docker-compose downStop and remove containers, networks, and volumes</li><li>docker-compose psList running services</li><li>docker-compose logsView logs of services</li><li>docker-compose buildBuild services in docker-compose.yml</li></ol><h3>Dockerfile Commands</h3><ol><li>FROM &lt;image&gt;Specifies the base image</li><li>RUN &lt;command&gt;Runs a command in the container during the build</li><li>COPY &lt;src&gt; &lt;dest&gt;Copies files from local to container</li><li>ADD &lt;src&gt; &lt;dest&gt;Copies files and extracts archives</li><li>CMD [&quot;executable&quot;, &quot;arg1&quot;, &quot;arg2&quot;]Default command to run in a container</li><li>ENTRYPOINT [&quot;executable&quot;, &quot;arg1&quot;]Default executable for a container</li><li>EXPOSE &lt;port&gt;Opens a port for external access</li><li>WORKDIR &lt;path&gt;Sets the working directory</li><li>ENV &lt;key&gt;=&lt;value&gt;Sets environment variables</li><li>VOLUME [&quot;/data&quot;]Creates a mount point for persistence</li></ol><h3>Docker Container Management</h3><ol><li>docker top &lt;container&gt;Display running processes inside a container</li><li>docker stats &lt;container&gt;Display real-time resource usage of a container</li><li>docker inspect &lt;container&gt;Get detailed information about a container</li></ol><h3>Docker Cleanup</h3><ol><li>docker system pruneRemove all stopped containers, unused networks, and dangling images</li><li>docker container pruneRemove all stopped containers</li><li>docker image pruneRemove unused images</li><li>docker volume pruneRemove unused volumes</li><li>docker network pruneRemove unused networks</li></ol><h3>Docker Registry &amp; Pushing Images</h3><ol><li>docker loginLog in to Docker Hub</li><li>docker tag &lt;image_id&gt; &lt;username&gt;/&lt;repo&gt;:&lt;tag&gt;Tag an image for Docker Hub</li><li>docker push &lt;username&gt;/&lt;repo&gt;:&lt;tag&gt;Push an image to Docker Hub</li><li>docker pull &lt;username&gt;/&lt;repo&gt;:&lt;tag&gt;Pull an image from the Docker Hub</li></ol><h3>Docker Security &amp; User Management</h3><ol><li>docker run --user &lt;uid&gt;:&lt;gid&gt; &lt;image&gt;Run a container as a specific user</li><li>docker run --read-only &lt;image&gt;Run a container with a read-only filesystem</li><li>docker scan &lt;image&gt;Scan an image for vulnerabilities</li></ol><h3>Docker Swarm (Orchestration)</h3><ol><li>docker swarm initInitialize a Docker Swarm</li><li>docker swarm join --token &lt;token&gt; &lt;manager_ip&gt;:&lt;port&gt;Join a node to a swarm</li><li>docker service create --name &lt;service_name&gt; &lt;image&gt;Deploy a service in Swarm</li><li>docker service lsList running services</li><li>docker service rm &lt;service_name&gt;Remove a service</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2047f662602d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring MySQL Full-Text Search and Its Implementation in Laravel]]></title>
            <link>https://medium.com/@mahfuz34/exploring-mysql-full-text-search-and-its-implementation-in-laravel-48e030fe6aa0?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e030fe6aa0</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 06:06:41 GMT</pubDate>
            <atom:updated>2025-02-02T06:06:41.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1Vs92Y-E3aMmE6LHlfQJmw.png" /><figcaption>collected from internet</figcaption></figure><p>Imagine you’re building a news website or a blog, and you need a fast and efficient way to search through thousands (or even millions) of articles. Traditional LIKE queries in MySQL won’t cut it they’re slow and inefficient. This is where <strong>MySQL Full-Text Search (FTS)</strong> comes into play! 🚀</p><p>Full-Text Search is MySQL’s built-in solution for powerful, efficient text searching. In this article, we’ll break down what it is, how it works, and how you can implement it in Laravel.</p><h3>What is MySQL Full-Text Search?</h3><p>Full-Text Search (FTS) is a feature in MySQL that allows you to perform advanced text-based queries using <strong>indexes</strong> rather than scanning entire tables. This makes searches much faster compared to the traditional LIKE operator.</p><h3>How It Works 🔍</h3><ol><li><strong>Indexing:</strong> MySQL creates a <strong>FULLTEXT</strong> index on specific columns.</li><li><strong>Tokenization:</strong> Text is broken into words (tokens) and stored in an index.</li><li><strong>Ranking:</strong> When a search query is executed, MySQL retrieves results based on relevance scoring.</li></ol><h3>Full-Text Search Modes</h3><p>MySQL provides two main modes:</p><ol><li><strong>Natural Language Mode (Default) </strong>Returns results ranked by relevance.</li><li><strong>Boolean Mode</strong> — Allows custom search logic using operators like +, -, OR, NOT.</li></ol><h3>Setting Up Full-Text Search in Laravel</h3><h3>1. Creating the Database Table</h3><p>First, create a migration to add a FULLTEXT index to your table:</p><pre>Schema::create(&#39;news&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;title&#39;);<br>    $table-&gt;text(&#39;content&#39;);<br>    $table-&gt;timestamps();<br>    <br>    $table-&gt;fullText([&#39;title&#39;, &#39;content&#39;]); // Adding FULLTEXT index<br>});</pre><h3>2. Performing a Full-Text Search</h3><p>You can now use MySQL’s MATCH() function in Laravel queries:</p><pre>$search = &#39;election results&#39;;<br><br>$results = DB::table(&#39;news&#39;)<br>    -&gt;whereRaw(&quot;MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE)&quot;, [$search])<br>    -&gt;get();</pre><p>This query will return articles ranked by relevance.</p><h3>3. Using Boolean Mode for Advanced Searches</h3><p>Need more control? Use Boolean Mode:</p><pre>$search = &#39;+election -fake&#39;;<br><br>$results = DB::table(&#39;news&#39;)<br>    -&gt;whereRaw(&quot;MATCH(title, content) AGAINST(? IN BOOLEAN MODE)&quot;, [$search])<br>    -&gt;get();</pre><p>This ensures results <strong>must contain</strong> “election” but <strong>must not contain</strong> “fake.”</p><h3>4. Full-Text Search in Eloquent</h3><p>Want a cleaner approach? Use Eloquent:</p><pre>class News extends Model<br>{<br>    public function scopeSearch($query, $keywords)<br>    {<br>        return $query-&gt;whereRaw(&quot;MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE)&quot;, [$keywords]);<br>    }<br>}<br><br>$articles = News::search(&#39;technology trends&#39;)-&gt;get();</pre><p>This makes it reusable across your application.</p><h3>Optimizing Full-Text Search Performance</h3><ul><li><strong>Use Short Columns</strong>: Store only necessary text in the FULLTEXT index.</li><li><strong>Limit Results</strong>: Always paginate or limit query results.</li><li><strong>Consider External Search Engines</strong>: If your dataset is huge, try <strong>Meilisearch</strong> or <strong>Elasticsearch</strong>.</li></ul><p>MySQL Full-Text Search is a powerful tool for fast and efficient text searching. When combined with Laravel, it provides an easy and flexible way to implement advanced search features.</p><p>So, whether you’re building a news portal, a blog, or an e-commerce site, leveraging <strong>Full-Text Search</strong> can significantly enhance the user experience.</p><p>And with Redis Caching, it will be a lot faster. Happy Coding!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e030fe6aa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Multi-Container Deployment with GitHub Actions in Laravel]]></title>
            <link>https://medium.com/@mahfuz34/docker-multi-container-deployment-with-github-actions-in-laravel-42e8971b0165?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/42e8971b0165</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 06:59:42 GMT</pubDate>
            <atom:updated>2025-01-20T07:16:15.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*6J0VkOQDozu_q6UPSSCgBA.png" /><figcaption>Collected from google</figcaption></figure><p>In today’s tech world, applications often rely on multiple interconnected services (containers) to function seamlessly — think of a web app working alongside a database, a cache, and a load balancer. Deploying such a multi-container application can seem daunting, but with <strong>GitHub Actions</strong>, you can set up a smooth CI/CD pipeline to deploy your app to production. Here’s a casual walk-through of how it’s done.</p><h4>What’s Multi-Container Deployment?</h4><p>It’s the process of deploying multiple Docker containers that work together as a system. For instance, a Laravel app might use:</p><ul><li>A container for the application code.</li><li>Another is for the MySQL database.</li><li>Nginx is used to serve static files and proxying requests.</li></ul><h4>Step 1: Prerequisites</h4><p>Before jumping into deployment:</p><ol><li><strong>Dockerize Your Application</strong>: Ensure each service has a Dockerfile.</li><li><strong>Set Up Docker Compose</strong>: A docker-compose.yml file to orchestrate the containers.</li><li><strong>Provision a Server</strong>: A VPS (like DigitalOcean or AWS Lightsail) with Docker and Docker Compose installed.</li></ol><h4>Step 2: Build Your GitHub Actions Workflow</h4><p>GitHub Actions lets you automate testing, building, and deploying. Here’s a simple workflow for deploying a Dockerized app:</p><pre>name: Multi-Container Deployment<br>on:<br>  push:<br>    branches: [main]<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      # Checkout code<br>      - name: Checkout Repository<br>        uses: actions/checkout@v2<br>      # Build Docker Images<br>      - name: Build Docker Images<br>        run: |<br>          docker-compose -f docker-compose.yml build<br>      # Push Images to Docker Hub<br>      - name: Push Images<br>        env:<br>          DOCKER_USERNAME: ${{ secrets.DOCKER_HUB_USERNAME }}<br>          DOCKER_PASSWORD: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}<br>        run: |<br>          echo &quot;$DOCKER_PASSWORD&quot; | docker login -u &quot;$DOCKER_USERNAME&quot; --password-stdin<br>          docker-compose -f docker-compose.yml push<br>      # Deploy to VPS<br>      - name: Deploy to VPS<br>        uses: appleboy/ssh-action@v0.1.4<br>        with:<br>          host: ${{ secrets.VPS_SERVER_IP }}<br>          username: ${{ secrets.VPS_USERNAME }}<br>          key: ${{ secrets.SSH_PRIVATE_KEY }}<br>          script: |<br>            cd /path/to/your/app<br>            docker-compose pull<br>            docker-compose down<br>            docker-compose up -d</pre><h4>How It Works</h4><ol><li><strong>Trigger on Push</strong>: The workflow starts whenever you push to the main branch.</li><li><strong>Build Docker Images</strong>: Images for each container are built using docker-compose.yml.</li><li><strong>Push to Docker Hub</strong>: Built images are uploaded to Docker Hub (or another container registry).</li><li><strong>Deploy to VPS</strong>: The workflow logs into your server via SSH, pulls the latest images, and restarts the containers using docker-compose.</li></ol><h4>Why This Workflow Rocks</h4><ul><li><strong>Automation</strong>: No manual SSH-ing or running commands — it’s all automated.</li><li><strong>Consistency</strong>: Every deployment uses the same images built in CI, ensuring consistency.</li><li><strong>Simplicity</strong>: Docker Compose simplifies managing multi-container apps.</li></ul><p>And that’s it! With this workflow, you can confidently deploy your multi-container app without breaking a sweat. Happy deploying! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42e8971b0165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens When You Run “php artisan serve” in Laravel?]]></title>
            <link>https://medium.com/@mahfuz34/what-happens-when-you-run-php-artisan-serve-in-laravel-51e2069e4a39?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e2069e4a39</guid>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 18:38:42 GMT</pubDate>
            <atom:updated>2024-12-02T18:38:42.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image Collected Form Google" src="https://cdn-images-1.medium.com/max/849/1*vfosg-UqepvC1Mvc5tYq_g.png" /></figure><p>Laravel is one of the most popular PHP frameworks, making web development efficient and enjoyable. As a developer, you’ve likely used the php artisan serve command to quickly start a local development server. But have you ever wondered what happens behind the scenes when you run this command? Let’s explore this in detail, step by step, understand how Laravel identifies and runs the ServeCommand, and dive into what PHP’s built-in server is and how it compares to traditional web servers like Nginx or Apache.</p><h3>What is php artisan serve?</h3><p>The php artisan serve command is a Laravel feature that starts a local web server for your project. It uses PHP’s built-in server to make your Laravel application accessible at a specific address (e.g., http://127.0.0.1:8000) during development.</p><p>This command is especially useful for local development because it doesn’t require setting up a full-fledged web server like Nginx or Apache.</p><h3>Step-by-Step Process: What Happens When You Run php artisan serve?</h3><h4>1. User Runs the Command</h4><p>When you type php artisan serve in the terminal, Laravel&#39;s Artisan Console—a command-line tool for Laravel—kicks into action. It’s like a toolbox with various commands to assist in building, testing, and running Laravel applications.</p><h4>2. Artisan Entry Point</h4><ul><li>The artisan file in your project’s root directory acts as the entry point for all Artisan commands.</li><li>When you run php artisan serve, the artisan file does the following:</li></ul><ol><li>Includes Composer’s autoloader (vendor/autoload.php).</li><li>Bootstraps the Laravel framework using bootstrap/app.php.</li></ol><h4>3. Artisan Finds the ServeCommand</h4><ul><li>Laravel registers all Artisan commands when the application boots. For built-in commands like serve, Laravel registers them in the Illuminate\Foundation\Providers\ArtisanServiceProvider.</li><li>This provider maps the command name (serve) to its corresponding class (Illuminate\Foundation\Console\ServeCommand).</li></ul><h4>4. Command Resolution and Autoloading</h4><ul><li>The ServeCommand is located in the vendor/laravel/framework directory under the namespace Illuminate\Foundation\Console.</li><li>Laravel uses Composer’s PSR-4 autoloading configuration to locate and load the class.</li><li>This allows the ServeCommand class to be loaded without the full Laravel framework being fully initialized yet.</li></ul><h4>5. Preparing the Server</h4><ul><li>The ServeCommand configures the PHP built-in server:</li><li><strong>Host</strong>: Default is 127.0.0.1 (localhost).</li><li><strong>Port</strong>: Default is 8000 (or a custom one via --port option).</li><li><strong>Document Root</strong>: Points to the public directory where Laravel’s entry file (index.php) resides.</li><li>Internally, the command executes:</li></ul><pre>php -S 127.0.0.1:8000 -t public server.php</pre><ul><li>php -S: Starts PHP’s built-in server.</li><li>-t public: Specifies the document root.</li><li>server.php: A router file to handle dynamic requests.</li></ul><h4>6. Handling Requests</h4><ul><li>The server.php file acts as a router:</li><li>If the requested file (e.g., CSS, JS) exists, it is served directly.</li><li>Otherwise, requests are forwarded to index.php.</li></ul><h4>7. Laravel Processes the Request</h4><ul><li>The index.php file initializes Laravel’s framework and handles incoming HTTP requests.</li><li>It routes the request to the appropriate controller, processes the logic, and generates a response (e.g., HTML or JSON).</li></ul><h4>8. Response is Sent Back</h4><ul><li>The Laravel response is sent back to the PHP built-in server, which then delivers it to the browser.</li></ul><h3>What is PHP’s Built-In Server?</h3><p>PHP’s built-in server is a simple development server introduced in PHP 5.4. It’s designed to help developers test applications without needing to install or configure a full web server.</p><h4>Features of PHP Built-In Server:</h4><ul><li><strong>Ease of Use</strong>: Start it with a single command (php -S).</li><li><strong>Dynamic and Static Files</strong>: Serves both PHP scripts and static files like images or stylesheets.</li><li><strong>Custom Routing</strong>: Allows custom handling of requests through a router script (like Laravel’s server.php).</li></ul><h3>Comparison: PHP Built-In Server vs. Nginx/Apache</h3><ol><li><strong>Purpose</strong>: The PHP Built-in Server is For Development purposes only. Nginx/Apache is for both Production-ready and development.</li><li><strong>Performance:</strong> The PHP built-in server is Single-threaded (one request at a time) and Nginx/Apache is Multi-threaded (handles many requests concurrently)</li><li><strong>Configuration: </strong>The PHP built-in server minimal setup requires. nginx/Apache needs configuration files.</li><li><strong>Advanced Features: </strong>The PHP built-in server is Limited (e.g., no caching). Nignx/Apache can be used for Caching, load balancing, and more.</li></ol><p>While this setup is convenient, it’s meant only for development. For live applications, web servers like Nginx or Apache provide the scalability and performance necessary for handling production traffic.</p><p>P.S. It always interests me to learn how things work behind the scenes. This helps me understand what is actually happening when I am building an application. You can read my other articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e2069e4a39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is PHP Fiber? Does PHP Fiber Really Give You Asynchronous Execution?]]></title>
            <link>https://medium.com/@mahfuz34/what-is-php-fiber-does-php-fiber-really-give-you-asynchronous-execution-370c69dee686?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/370c69dee686</guid>
            <category><![CDATA[php-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 18:56:45 GMT</pubDate>
            <atom:updated>2024-11-29T18:56:45.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONJSFCpqT3rE5d_CkL4vfQ.jpeg" /></figure><p>When PHP 8.1 introduced <strong>Fibers</strong>, many developers wondered if they were a solution to PHP’s long-standing limitation as a single-threaded, synchronous language. Could Fibers make PHP asynchronous, like JavaScript with its event loops or Node.js? The answer is subtle: Fibers don’t provide true asynchronous execution, but they are a powerful tool for managing tasks more efficiently. Let’s explore this concept in detail.</p><h3>What Are PHP Fibers?</h3><p>Fibers are a mechanism for implementing <strong>cooperative multitasking</strong> in PHP. They allow you to pause and resume specific parts of code without blocking the entire PHP process. Think of a Fiber as a specialized function that can “yield” control back to the main program and then continue execution from where it left off when requested.</p><h4>Key Features of Fibers:</h4><ul><li>You can start, pause, and resume their execution.</li><li>They operate within the same PHP process and do not introduce multi-threading.</li><li>They are particularly useful for structuring non-blocking code.</li></ul><h3>What Happens When a Fiber Is Paused?</h3><p>When a Fiber is paused using Fiber::suspend(), the control returns to the main PHP script. This means:</p><ul><li>The main process is free to continue executing other parts of your program.</li><li>The Fiber’s execution is halted temporarily, waiting for a resume() call.</li></ul><p>For example:</p><pre>$fiber = new Fiber(function () {<br>    echo &quot;Fiber started\n&quot;;<br>    Fiber::suspend();<br>    echo &quot;Fiber resumed\n&quot;;<br>});<br><br>echo &quot;Before Fiber\n&quot;;<br>$fiber-&gt;start();<br>echo &quot;After Fiber Start\n&quot;;<br>$fiber-&gt;resume();<br>echo &quot;After Fiber Resume\n&quot;;</pre><p><strong>Output:</strong></p><pre>Before Fiber<br>Fiber started<br>After Fiber Start<br>Fiber resumed<br>After Fiber Resume</pre><p>Here’s what’s happening:</p><ol><li>Fiber::suspend() pauses the Fiber. Execution shifts back to the main script after $fiber-&gt;start().</li><li>The main script continues running (“After Fiber Start”).</li><li>When resume() is called, the Fiber picks up where it left off and completes its task.</li></ol><h3>Does Resuming a Fiber Block the Main Process?</h3><p>Yes, but only temporarily. When you call Fiber::resume(), the Fiber runs synchronously within the main PHP process. During this time:</p><ul><li>Other parts of your script (or other Fibers) cannot execute until the Fiber completes or pauses again.</li><li>The execution of the Fiber is blocking because PHP remains single-threaded.</li></ul><p>For example:</p><pre>$fiber = new Fiber(function () {<br>    echo &quot;Processing Fiber...\n&quot;;<br>    sleep(2); // Simulates a blocking task<br>    echo &quot;Fiber Done\n&quot;;<br>});<br><br>echo &quot;Before Fiber\n&quot;;<br>$fiber-&gt;start();<br>echo &quot;Between Fiber Start and Resume\n&quot;;<br>$fiber-&gt;resume();<br>echo &quot;After Fiber\n&quot;;</pre><p><strong>Output:</strong></p><pre>Before Fiber<br>Processing Fiber...<br>Fiber Done<br>Between Fiber Start and Resume<br>After Fiber</pre><p>Here, the Fiber blocks the main process during the sleep(2) call. So, while Fibers provide a way to structure code for efficiency, they don’t magically enable parallel or truly asynchronous execution.</p><h3>How Are Fibers Still “Non-Blocking”?</h3><p>The term “non-blocking” refers to <strong>how Fibers enable better task management, not parallel execution</strong>. A Fiber doesn’t block the main process while it’s paused; instead, control is handed back to the main script or an event loop.</p><p>This is particularly useful for libraries or frameworks that use event-driven architectures, like <strong>ReactPHP</strong> or <strong>Amp</strong>, where:</p><ul><li>Long-running or waiting tasks (e.g., database queries, API calls) can be suspended.</li><li>Other tasks can continue running in the meantime.</li><li>Once the task is ready, the Fiber is resumed, and its execution continues.</li></ul><p>Imagine you are a chef preparing multiple dishes:</p><ol><li>You start cooking a dish but pause to wait for something to boil.</li><li>While waiting, you begin preparing another dish.</li><li>When the first dish is ready, you return to it and continue cooking.</li></ol><p>Similarly, Fibers allows PHP to “pause” a task and return to it later without holding up the entire process.</p><h3>Event Loops and Fibers</h3><p>To achieve practical non-blocking behavior, Fibers are often combined with <strong>event loops</strong>. An event loop tracks multiple tasks and decides which one to execute next. Here’s how it works:</p><ol><li>When a blocking task is encountered (e.g., a database query), the Fiber suspends itself.</li><li>The event loop picks up another task to process in the meantime.</li><li>When the blocking task is complete, the event loop resumes the corresponding Fiber.</li></ol><p>Libraries like <strong>Amp</strong> and <strong>ReactPHP</strong> leverage Fibers and event loops to implement asynchronous task handling.</p><h3>Why Fibers Are Not Truly Asynchronous</h3><p>Unlike asynchronous programming in JavaScript or Node.js, where tasks can run in parallel using threads or an event loop, Fibers:</p><ul><li>Execute synchronously within a single PHP process.</li><li>Provide cooperative multitasking by allowing the developer to manually control task suspension and resumption.</li></ul><p>In other words:</p><ul><li><strong>Fibers don’t introduce parallelism</strong> (tasks still run one at a time).</li><li>They are a tool for managing and structuring non-blocking code more efficiently.</li></ul><p>While PHP Fibers don’t make PHP truly asynchronous, they are a powerful addition to the language. Here’s why:</p><ol><li><strong>Improved Task Management:</strong> They allow you to pause and resume tasks, freeing the main process to handle other work in the meantime.</li><li><strong>Non-Blocking Workflows:</strong> Combined with event loops, Fibers enable non-blocking task handling.</li><li><strong>Synchronous Execution:</strong> When resumed, Fibers execute synchronously, temporarily blocking the process.</li></ol><p>Fibers represent a step forward for PHP developers building applications that require efficient multitasking, particularly in areas like real-time applications, background jobs, or APIs. However, for true parallelism, you’ll still need external solutions like multi-threading via extensions or separate processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370c69dee686" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP is a Single-Threaded Language, So How Does Laravel Handle Queue Jobs Asynchronously?]]></title>
            <link>https://medium.com/@mahfuz34/php-is-a-single-threaded-language-so-how-does-laravel-handle-queue-jobs-asynchronously-e5f15cd45ca7?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5f15cd45ca7</guid>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 11:39:00 GMT</pubDate>
            <atom:updated>2024-11-28T11:39:00.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*3YOp8Rg2t7Dej9vgJ_4XXQ.jpeg" /></figure><p>PHP is known as a <strong>single-threaded</strong> language, meaning it can only execute one task at a time within a single process. However, Laravel provides a robust queue system to handle multiple tasks “asynchronously.” If PHP is single-threaded, how does Laravel achieve this magic? Let’s break it down in simple terms.</p><h3>What is a PHP Process?</h3><p>Before diving into queues, we need to understand <strong>what a PHP process is</strong>.</p><p>A <strong>process</strong> is like a worker hired to complete a task. When you execute a PHP script (e.g., php my_script.php), the operating system creates a new process. This process:</p><ul><li>Loads the PHP script.</li><li>Executes the code step-by-step.</li><li>Stops and “dies” when the task is done.</li></ul><p>For example:</p><pre>echo &quot;Hello World!&quot;;</pre><p>When you run this script, PHP starts a process, displays “Hello World!”, and then the process ends.</p><h3>PHP in Web Applications</h3><p>In web applications:</p><ol><li>A <strong>web server</strong> (like Apache or Nginx) receives an HTTP request from a browser.</li><li>The server creates a new PHP process to handle the request.</li><li>PHP processes the request (e.g., fetching data from a database or rendering a page).</li><li>The process ends after sending a response to the browser.</li></ol><p>PHP processes are short-lived. They handle one request at a time and then stop. This design makes PHP simple and efficient for web applications.</p><h3>What is Single-Threaded?</h3><p>PHP is <strong>single-threaded</strong>, meaning:</p><ul><li>A PHP process can only handle one task at a time.</li><li>It doesn’t perform multiple tasks simultaneously in the same process.</li></ul><p>For example:</p><pre>echo &quot;Task 1&quot;;<br>// Waits for Task 1 to finish before starting Task 2<br>echo &quot;Task 2&quot;;</pre><p>PHP executes Task 1 first. Only after it’s done does it move to Task 2. This behavior is different from languages like JavaScript, where tasks can run in parallel in the same process.</p><h3>How Does Laravel Handle Queues Then?</h3><p>Laravel’s <strong>queue system</strong> allows you to run multiple tasks in the background without blocking the main application. For example:</p><ul><li>Sending emails.</li><li>Processing image uploads.</li><li>Sending notifications.</li></ul><p>These tasks run in the background, so your main application can respond to users faster.</p><p>But PHP can only handle one task at a time, right? How does Laravel make it seem asynchronous? The answer lies in <strong>workers</strong> and <strong>multiple processes</strong>.</p><h3>What is a Worker?</h3><p>A <strong>worker</strong> in Laravel is a long-running PHP process that listens for jobs in a queue and executes them.</p><p>When you run the command:</p><pre>php artisan queue:work</pre><p>A new PHP process (or <strong>worker</strong>) starts. This process:</p><ol><li>Connects to the queue system (like Redis or a database).</li><li>Waits for new jobs (tasks) to arrive in the queue.</li><li>Picks up and processes jobs one by one.</li></ol><h4>Example</h4><p>Imagine you have a task to send 1,000 emails:</p><ol><li>The main application sends 1,000 jobs to the queue.</li><li>A worker process picks up one job, sends the email, and moves to the next job.</li></ol><h3>How Does Laravel Achieve Asynchronous Behavior?</h3><p>Laravel achieves “asynchronous” behavior by running multiple workers <strong>at the same time</strong>. Each worker is a separate PHP process.</p><p>Here’s how it works:</p><ol><li>When you run php artisan queue:work, it starts with one worker (one PHP process).</li><li>You can start multiple workers to process jobs in parallel on different tabs locally and in production using the process manager like the supervisor.</li><li>This will start multiple PHP processes. Each worker handles jobs independently, making it seem like tasks are running simultaneously.</li></ol><h3>What Happens When a Job is Queued?</h3><p>When you queue a job in Laravel, here’s what happens step-by-step:</p><ol><li><strong>Job Creation</strong>: The job (e.g., send an email) is serialized (converted into a storable format) and added to the queue backend (like Redis or a database).</li><li><strong>Worker Polls the Queue</strong>:</li></ol><ul><li>Workers continuously check the queue for new jobs.</li><li>If a job is found, the worker picks it up.</li></ul><p><strong>3. Job Execution</strong>:</p><ul><li>The worker deserializes the job and runs its handle() method.</li><li>Once done, the job is marked as completed.</li></ul><p><strong>4. Job Completion</strong>:</p><ul><li>The worker removes the job from the queue.</li><li>If the job fails, Laravel retries it or moves it to a “failed jobs” list (based on your configuration).</li></ul><h3>Example Scenario: Sending Emails</h3><p>Imagine you have a Laravel application where users submit a contact form. When the form is submitted:</p><ol><li>The main application processes the form and responds to the user immediately.</li><li>Instead of sending the email right away, it adds the email-sending task to a queue.</li></ol><p>In the background:</p><ul><li>A worker picks up the email-sending job.</li><li>Sends the email.</li><li>Moves to the next job.</li></ul><p>This way, the user doesn’t have to wait for the email to be sent, making the app faster.</p><h3>How Do Workers Run in Production?</h3><p>In production, Laravel workers are managed by tools like <strong>Supervisor</strong>. The supervisor keeps workers running 24/7 and restarts them if they crash.</p><h4>Supervisor Configuration Example:</h4><pre>[program:laravel-worker]<br>command=php /path/to/artisan queue:work --tries=3<br>numprocs=5</pre><ul><li><strong>command</strong>: Runs the queue:work command.</li><li><strong>numprocs=5</strong>: Starts 5 workers (5 PHP processes) to handle jobs.</li></ul><h3>Is It Truly Asynchronous?</h3><p>Technically, Laravel queues are not asynchronous in the way JavaScript or Node.js handle tasks. Instead:</p><ul><li>Each worker handles one job at a time.</li><li>Multiple workers (processes) provide parallelism, giving the appearance of asynchronous execution.</li></ul><h3>Key Points to Remember</h3><ol><li>PHP is single-threaded, so a single PHP process handles one task at a time.</li><li>Laravel uses <strong>workers</strong> (long-running PHP processes) to process queue jobs.</li><li>Multiple workers can run simultaneously, allowing jobs to be processed in parallel.</li><li>Queue backends (like Redis) act as middlemen to store jobs until workers pick them up.</li><li>Tools like <strong>Supervisor</strong> ensure workers run continuously in production.</li></ol><p>Laravel’s queue system is a smart way to handle tasks in the background, improving application performance and user experience. While PHP itself is single-threaded, Laravel achieves parallelism by running multiple processes (workers). This simple yet effective design allows Laravel to handle heavy workloads, even with PHP’s limitations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5f15cd45ca7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Caching (Redis) Strategy in Laravel: A Guide to Fast and Efficient Caching]]></title>
            <link>https://medium.com/@mahfuz34/best-caching-redis-strategy-in-laravel-a-guide-to-fast-and-efficient-caching-bdf0c2eb5408?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdf0c2eb5408</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 06:05:19 GMT</pubDate>
            <atom:updated>2024-11-11T06:05:19.780Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Best Redis Caching Strategy in Laravel: A Guide to Fast and Efficient Caching</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*MkfWGE3XSfV1d9L8.jpg" /></figure><p>Laravel and Redis are a powerful combination for boosting application speed and performance. Redis, an in-memory key-value store, is perfect for caching, especially when you need fast and frequent data access. In this guide, we’ll look at effective caching strategies in Laravel with Redis. We’ll cover how to cache data, manage expiration times, and efficiently clear caches.</p><h3>Why Use Redis Caching?</h3><p>When you cache with Redis in Laravel, you’re essentially saving data temporarily to reduce the time spent querying the database. Caching speeds up data retrieval, reduces server load, and improves user experience by making pages load faster.</p><p>Redis is ideal for caching because it:</p><ul><li>Can quickly store and retrieve data</li><li>Supports various data structures like strings, lists, and hashes</li><li>Offers tools for managing cache expiration and clearing old data</li></ul><p>Let’s explore how to best use Redis caching in Laravel.</p><p>Let’s say we have a <strong>News Paper </strong>Site. Now we need to build Api to Get News.</p><h3>1. Setting Up Basic Caching with Laravel and Redis</h3><p>To start, let’s cache a simple API response, like a list of the latest news articles.</p><pre>$data = Cache::remember(&#39;latest_news&#39;, 3600, function () {<br>    return News::latest()-&gt;get();<br>});</pre><p>In this example:</p><ul><li>Cache::remember stores data with a key (latest_news) and a time-to-live (TTL) of 3600 seconds (1 hour).</li><li>If a request for latest_news comes in again within the hour, Redis serves the cached data without querying the database.</li></ul><h3>2. Structuring Cache Keys and Expiration Times</h3><p>To keep the data fresh without overloading Redis:</p><ul><li>Set shorter TTLs for frequently updated data (e.g., 15–30 minutes).</li><li>Use longer TTLs (e.g., 1–2 hours) for data that rarely changes.</li></ul><p>Use specific, structured cache keys that reflect the data content. For example:</p><pre>$cacheKey = &quot;news:category:category_1&quot;;</pre><p>This key is clear, unique, and self-descriptive, making it easy to identify and manage within Redis.</p><h3>3. Using Tags for Grouped Cache Management</h3><p>Redis supports tags, which let us manage grouped data under a common tag. For example, tagging all news-related caches with news:</p><pre>Cache::tags([&#39;news&#39;, &#39;category&#39;])-&gt;remember(&#39;category_news_1&#39;, 3600, function () {<br>    return $this-&gt;news_repository-&gt;getNewsByCategory(1);<br>});</pre><p>Now, if we want to clear all category-specific news caches (when news is updated), we can use:</p><pre>Cache::tags([&#39;news&#39;, &#39;category&#39;])-&gt;flush();</pre><h3>4. Caching Paginated and Filtered Data</h3><p>When adding pagination or filters (like category or tags), make each cache key unique to the parameters:</p><pre>$page = request()-&gt;input(&#39;page&#39;, 1);<br>$limit = request()-&gt;input(&#39;limit&#39;, 10);<br>$cacheKey = &quot;news:page_{$page}:limit_{$limit}&quot;;<br><br>$newsData = Cache::remember($cacheKey, 3600, function () use ($page, $limit) {<br>    return News::latest()-&gt;paginate($limit, [&#39;*&#39;], &#39;page&#39;, $page);<br>});</pre><p>This way:</p><ul><li>A unique cache entry is created for each page and limit.</li><li>Users can fetch pages quickly without re-querying the database.</li></ul><p>For filtered data, include the filter parameters in the key:</p><pre>$categoryId = request()-&gt;input(&#39;category_id&#39;);<br>$cacheKey = &quot;news:category_{$categoryId}:page_{$page}:limit_{$limit}&quot;;</pre><p>This ensures each category and page combination has its own cache entry.</p><h3>5. Automatic Cache Invalidation on Data Changes</h3><p>Clearing or “invalidating” caches ensures users see updated data when necessary. Here’s how to automate it:</p><ul><li>Use <strong>model observers</strong> for events like created, updated, or deleted to clear related caches.</li><li>Example observer for news:</li></ul><pre>public function created(News $news) {<br>    Cache::tags([&#39;news&#39;, &#39;pagination&#39;])-&gt;flush();<br>}<br><br>public function updated(News $news) {<br>    Cache::tags([&#39;news&#39;, &#39;pagination&#39;])-&gt;flush();<br>}</pre><p>Now, whenever news is added or updated, all news and pagination tagged caches are flushed, keeping the data fresh.</p><h3>6. Summary and Best Practices</h3><p>To make caching work effectively:</p><ul><li><strong>Unique Keys</strong>: Structure keys with parameters like category, page, and limit.</li><li><strong>Tags for Grouped Data</strong>: Use tags to easily manage caches for specific data groups.</li><li><strong>Automate Invalidation</strong>: Set up observers to clear outdated caches on data changes.</li><li><strong>Set Sensible Expiration</strong>: Choose TTLs based on how often the data changes, typically between 15 minutes and 1 hour.</li></ul><p>Using Redis with this structured approach makes Laravel APIs respond faster, improves server load management, and ensures a reliable, efficient cache strategy that’s easy to manage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdf0c2eb5408" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where Does Deleted Data Go? Unveiling the Secrets of File Deletion and Overwriting]]></title>
            <link>https://medium.com/@mahfuz34/where-does-deleted-data-go-unveiling-the-secrets-of-file-deletion-and-overwriting-07c25482d706?source=rss-4c5b77fe77c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/07c25482d706</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[filesystem]]></category>
            <dc:creator><![CDATA[Mahfuzur Rahman]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 13:30:32 GMT</pubDate>
            <atom:updated>2024-10-02T14:35:54.304Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered where the files go when you delete them from your computer or phone? Are they really gone or are they just playing an epic game of hide and seek behind those memory blocks, waiting to be recovered? I’ve got a burning curiosity and an urge to understand what actually happens at the lowest level when we delete a file. So, let’s embark on this journey of discovery… and hopefully, we’ll find out that the files aren’t just off on a tropical vacation!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*lwmLJH9vkQAJUdI9Jp-gCw.jpeg" /><figcaption>collected from vecteezy</figcaption></figure><p>To understand what happens when a file is deleted and overwritten, and how the storage system handles data at a deeper level, we need to break down how files are stored and managed on a storage device. We’ll also dive into the physical aspects of how bits and bytes are written, erased, and overwritten, and explain why they don’t “pile up” or continue to occupy space after being overwritten.</p><h3>1. How Data is Stored: Understanding Bits and Bytes</h3><p>At the lowest level, all files whether they’re text, images, or programs — are stored as sequences of <strong>bits</strong> (0s and 1s). These bits are grouped into <strong>bytes</strong> (8 bits make 1 byte). Bytes represent the actual data, and they are stored in blocks on a storage device.</p><ul><li><strong>Blocks</strong>: Storage devices, whether hard drives (HDDs) or solid-state drives (SSDs) are divided into chunks called <strong>blocks</strong>. Typically, each block is 4KB (4,096 bytes), and a file can occupy multiple blocks.</li><li><strong>Data Mapping</strong>: The file system keeps a record of where each file’s blocks are located. When a file is saved, it writes data to specific blocks, and when it’s deleted, the system marks those blocks as available.</li></ul><h3>2. What Happens When You Delete a File?</h3><p>When you delete a file, the following happens at a low level:</p><ul><li><strong>File table update</strong>: The file system (like NTFS, FAT, etc.) removes the file’s entry from its index (file table). This index entry is what the operating system uses to find and access the file, so removing it makes the file “invisible” to the system, but the file’s actual data still resides in the blocks on the storage device.</li><li><strong>Blocks are marked as free</strong>: The storage blocks that contained the file’s data are marked as free, meaning they can be reused for new data, but the old data is still physically present on the storage device until it is overwritten by new data.</li></ul><h3>3. What Happens During Overwriting?</h3><p>When new data is written to the blocks that were previously occupied by the deleted file, this is called <strong>overwriting</strong>. Here’s what happens at a deeper level:</p><h4>Hard Disk Drives (HDDs):</h4><p>HDDs store data magnetically on spinning disks called platters:</p><ul><li><strong>Writing data</strong>: When you save data to an HDD, the drive head changes the magnetic orientation of the material on the platter to represent 0s and 1s. These magnetic orientations store the bits.</li><li><strong>Deleting a file</strong>: When you delete a file, the file system only removes the reference to the data in the file table and marks the area as free. The magnetic patterns representing the data are still there.</li><li><strong>Overwriting data</strong>: When new data is written to the same area, the magnetic orientations of the platter are changed to reflect the new data (0s and 1s of the new file). The old data is effectively “erased” because the magnetic state has been rewritten. There is no trace of the old data once this occurs.</li></ul><h4>Solid-State Drives (SSDs):</h4><p>SSDs store data electronically in memory cells that hold charges:</p><ul><li><strong>Writing data</strong>: In an SSD, data is stored in flash memory cells. Each cell can hold a certain amount of charge, which represents a bit (0 or 1). When data is written, the SSD changes the charge in these cells to represent the bits of the data.</li><li><strong>TRIM command</strong>: When a file is deleted on an SSD, the operating system typically sends a <strong>TRIM</strong> command to the SSD. This tells the drive which blocks are no longer in use and can be erased in the background, preparing them for new data. This makes SSDs more efficient, as it allows them to write new data faster without having to first erase old data.</li><li><strong>Overwriting data</strong>: When new data is written, the cells holding the old data are erased (in SSDs, this is done in chunks called pages or blocks). The new data is written by changing the charges in the cells. Once this happens, the previous data is gone.</li></ul><h3>4. Does the Old Data “Pile Up” When Overwritten?</h3><p>No, old data does not “pile up” under the new data. Here’s why:</p><ul><li><strong>Data on an HDD</strong>: When new data is written to the same area as the old data, the magnetic field that represents the old bits is physically altered to represent the new bits. The old magnetic state is lost. There’s no layering or piling up — there’s only the new magnetic orientation that represents the new data.</li><li><strong>Data on an SSD</strong>: In an SSD, once the memory cells are overwritten, the old electrical charge that represents the old data is changed to a new charge, representing the new data. The memory cells physically store only one set of data at a time (either the old or the new, but not both).</li></ul><h3>5. What Happens to the “Space” When Data is Deleted?</h3><p>When you delete a file, the storage device doesn’t immediately free up space by removing the actual data from the drive. Instead, it simply marks the space as available for future use. Here’s how space is managed:</p><ul><li><strong>File system marking</strong>: After a file is deleted, the storage blocks used by that file are still occupied by the file’s data, but the system marks them as available for future writing. They don’t take up <em>additional</em> space because they are already part of the physical storage.</li><li><strong>No extra space used after overwriting</strong>: When new data is written to those blocks, the old data is overwritten. The new data simply replaces the old data in the same physical space on the disk, so the space isn’t consumed twice — it’s only used once, for the new data.</li></ul><h3>6. Why Secure Deletion is Needed for Sensitive Data</h3><p>Even though normal deletion doesn’t immediately remove data, it’s important to use <strong>secure deletion methods</strong> if you want to ensure the data cannot be recovered. These methods include:</p><ul><li><strong>Overwriting</strong>: Tools that securely delete data will overwrite the blocks multiple times with random data (0s and 1s), ensuring that even sophisticated recovery techniques cannot reconstruct the original data.</li><li><strong>SSD Secure Erase</strong>: SSDs have specific commands (like <strong>Secure Erase</strong>) that ensure all blocks are completely erased, making it impossible to recover data.</li></ul><h3>7. Physical Limits of Data Recovery</h3><ul><li><strong>On HDDs</strong>: In theory, even after overwriting, slight residual magnetic traces of previous data might remain, which is why advanced forensic techniques (like magnetic force microscopy) can sometimes recover bits of overwritten data. However, modern secure deletion methods make this extremely difficult.</li><li><strong>On SSDs</strong>: Once data is overwritten or erased with TRIM, it’s nearly impossible to recover because flash memory doesn’t leave behind any residual traces like magnetic media.</li></ul><h3>Summary</h3><ul><li>When you delete a file, the file system marks the space as free, but the data remains on the storage device until overwritten.</li><li>Overwriting changes the physical or electrical state of the bits in storage. The old data is not layered under the new data; instead, it is completely replaced.</li><li>The old data doesn’t take up additional space — once overwritten, only the new data exists in that space.</li><li>HDDs and SSDs handle deletion and overwriting differently due to their physical properties, but in both cases, once data is overwritten, it’s effectively erased from the storage.</li></ul><p>For sensitive data, secure deletion tools ensure the old data is completely and irreversibly overwritten, making it impossible to recover.</p><p>I wrote this entire blog with my own research and used ChatGPT to help structure it. Please let me know if there are any misunderstandings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07c25482d706" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>