PHP and CURL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function browse($url, $postData = null) {
    $fields = '';
    if(is_array($postData) && sizeof($postData) >= 1){
        $fields = http_build_query($postData);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if($fields !=='') {
        curl_setopt($ch, CURLOPT_POST, count($postData));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    // Write cookie if needed  .. also try:  dirname(__FILE__) . '/cookie.txt';
    curl_setopt($ch, CURLOPT_COOKIEJAR , '/tmp/cookie.txt');
    // Read cookie if needed
    curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookie.txt');

    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}
Posted in PHP, Web Development | Comments Off on PHP and CURL

How to Share Directories Between Linux and Windows Systems

Sharing files and directories between Linux and Windows systems can be challenging, but with the right tools and configuration, it’s straightforward. This guide covers both directions: making a Linux directory accessible from Windows, and accessing Windows shared directories from Linux.

Sharing a Linux Directory to Windows

Overview: We’ll use Samba, a free and open-source implementation of the SMB/CIFS protocol. This allows Windows computers to access Linux folders as if they were Windows network shares.

To make a Linux folder accessible to Windows computers on your network, follow these steps:

Step 1: Install Samba

1
2
$ sudo apt-get install samba
$ sudo smbpasswd -a USERNAME

💡 Tip: The smbpasswd command sets a password specifically for Samba — this is separate from your Linux user password. You’ll use this password when connecting from Windows.

Step 2: Create the Shared Directory

1
$ mkdir /home/USERNAME/sharedfolder

Step 3: Configure Samba

Edit the Samba configuration file:

1
$ sudo vi /etc/samba/smb.conf

Add the following configuration block at the end:

1
2
3
4
5
6
7
8
[sharedfolder]
path = /home/USERNAME/sharedfolder
available = yes
valid users = USERNAME
read only = no
browsable = yes
public = yes
writable = yes

🔍 Why this works: The section [sharedfolder] defines a new share. The path specifies what Linux directory to expose. valid users restricts access to that Linux user. writable = yes allows Windows users to write to the share.

Step 4: Restart the Samba Service

1
$ sudo systemctl restart smbd

Your Linux directory is now visible as a network share on Windows. Browse to \\<linux-ip-address>\sharedfolder in Windows Explorer and authenticate with the Samba username and password.

Reference: Samba Official Documentation, AskUbuntu: Can’t access Ubuntu’s shared folders from Windows 7

Accessing Windows Shared Directories from Linux

Overview: We’ll use CIFS (Common Internet File System), the SMB/CIFS client for Linux. This protocol allows Linux to connect to Windows shares and mount them as local folders.

To mount a Windows shared directory on your Linux system:

1
sudo mount -t cifs //192.168.1.101/sharedirectoryabc -o username=YOURUSERNAME,password=YOURPASSWORD /home/userabc/sharedirectoryabc

Replace the IP address, share name, username, password, and mount point with your actual values.

⚠️ Heads up: Storing your password in plain text in the command history is a security risk. For a one-time mount, consider using sudo mount -t cifs -o user which will prompt for the password interactively. For permanent mounts, use a credentials file with restricted permissions (see next section).

Permanent Mount (Optional):

To automatically mount a Windows share at boot, add an entry to /etc/fstab:

1
sudo vi /etc/fstab

Add this line:

1
//192.168.1.101/sharedirectoryabc /home/userabc/sharedirectoryabc cifs username=YOURUSERNAME,password=YOURPASSWORD,uid=1000,gid=1000 0 0

Then mount it:

1
sudo mount -a

🐧 Note: Replace uid=1000 and gid=1000 with your actual user/group IDs (run id to check). This ensures the mounted share has the correct ownership for your user account.

Posted in Linux, Operating System, Windows 7 | Comments Off on How to Share Directories Between Linux and Windows Systems

Choosing the default network card (NIC) that should access the Internet

When a machine has more than one Network Interface Card (NIC) — say a Wi-Fi adapter and an Ethernet port, or a physical NIC alongside a Virtual Private Network (VPN) adapter — Windows has to decide which one to send internet traffic through. It makes that call using the interface metric: every route has a metric value, and the interface with the lower metric wins. Usually Windows assigns metrics automatically based on link speed, but when you need to force a specific adapter to be the default, you set the metric yourself.

See the current metrics

Open Command Prompt and run:

1
route print

You’ll get a list of active routes; the last column is the Metric. Lower-metric routes are preferred over higher ones, so whichever adapter carries the lowest metric on the default route (0.0.0.0) is the one currently reaching the internet.

Set the metric from the GUI

  1. Open the network adapter properties: Control Panel > Network and Internet > Network Connections, then right-click the adapter and choose Properties.
  2. Select Internet Protocol Version 4 (TCP/IPv4) and click Properties.
  3. Click Advanced.
  4. Untick Automatic metric and enter an Interface metric — for example 10 for the adapter you want preferred.
  5. Click OK until all the dialogs close.
  6. Repeat for each other adapter, giving them higher numbers (e.g. 20, 30) so they’re less preferred.

Or do it in one line with PowerShell

On Windows 8 and later, PowerShell is faster and scriptable. List every interface and its metric:

1
Get-NetIPInterface

Note the ifIndex of the adapter you want preferred, then set its metric (run PowerShell as Administrator):

1
Set-NetIPInterface -InterfaceIndex 12 -InterfaceMetric 10

🔍 Why this works: Windows builds a routing table where each candidate route to a destination carries a metric. For the default route, it compares metrics across all interfaces and uses the lowest one. Setting a manual metric overrides the automatic, link-speed-based heuristic, so a slower-but-preferred adapter can still win.

⚠️ Heads up: the metric is set per address family. If you only adjust IPv4 but the network also offers IPv6, Windows may still prefer the other adapter over IPv6. Set the metric for IPv6 too (in the GUI under Internet Protocol Version 6 (TCP/IPv6), or with Set-NetIPInterface -AddressFamily IPv6), or disable IPv6 on the adapter you don’t want used.

Finally, confirm the change took effect by running route print again and checking that the default route now shows your chosen metric. Remember the rule throughout: lower metric wins.

Original technique adapted from a SpeedGuide FAQ.

Posted in Operating System, Windows 7 | Tagged , | Comments Off on Choosing the default network card (NIC) that should access the Internet

Getting the current filename using bash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ cat ./testfilename.sh
#!/bin/bash
fullfile=`basename $0`
filename=$(basename "$fullfile")
echo "filename:"$filename
extension="${filename##*.}"
echo "extension:"$extension
justfilename="${filename%.*}"
echo "justfilename:"$justfilename


$ ./testfilename.sh
filename:testfilename.sh
extension:sh
justfilename:testfilename
Posted in Linux, Operating System | Comments Off on Getting the current filename using bash

Customize your Vim editor using .vimrc

Quick notes:
– imap is for when you are in insert mode
– map is when your are in command mode

Thus when you are in the insert mode, sometime you need to exit to the command mode first using the esc key.
The i is for going back to the inser mode. The cr key is the Enter key.

The script below will make vim to:
– Find and Replace when I hit F3
– Undo when I hit F9
– Saves when I hit F10
– Quit when I hit F12
– Prints a debugging statement for PHP when I press F8
– Also disables the REPLACE mode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
""""""""""""""""""""""""""""""""""""""
" Quick commands using F keys
"
""""""""""""""""""""""""""""""""""""""
:imap <F3> <esc>:%s/search/replace/gc
:map <F3> :%s/search/replace/gc

:imap <F9> <esc>:u<cr>i
:map <F9> :u<cr>i

:imap <F10> <esc>:w!<cr>i
:map <F10> :w!<cr>i

:imap <F12> <esc>:q!<cr>
:map <F12> :q!<cr>

:imap <F8> error_log("\n".__FILE__ . ' ['. __LINE__. '] ' . __CLASS__.'::'.__FUNCTION__.'() D>'. print_r(, true));<cr>
:map <F8> ierror_log("\n".__FILE__ . ' ['. __LINE__. '] ' . __CLASS__.'::'.__FUNCTION__.'() D>'. print_r(, true));<cr>

"""""""""""""""""""""""""""""""""""""""
"
Disable REPLACE mode
"""""""""""""""""""""""""""""""""""""""
function s:ForbidReplace()
    if v:insertmode isnot# 'i'
        call feedkeys("
\<Insert>", "n")
    endif
endfunction
augroup ForbidReplaceMode
    autocmd!
    autocmd InsertEnter  * call s:ForbidReplace()
    autocmd InsertChange * call s:ForbidReplace()
augroup END
Posted in Linux | Comments Off on Customize your Vim editor using .vimrc

Search and replace withing a file

1
2
3
4
5
6
7
sed -i -e"s/SEARCH_TEXT/REPPLACE_TEXT/g" FILENAME.txt

# another example using bakup
sed -i.bak -e"s/SEARCH_TEXT/REPPLACE_TEXT/g" FILENAME.txt

# another example using variable
sed -i -e"s/\/pathname/\/pathname-$date/g" "filename-"$date".xml"
Posted in Bash, Linux, Operating System | Comments Off on Search and replace withing a file

Bash Scripting Basics (Variable Assignment, If, Loop)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
##################################################
# Benchmark the processing time when wkhtmltopdf
# converts an html file to a pdf file
##################################################

if [[ $1 = "" || $2 = "" || $3 = "" ]]; then
        echo "Usage: `basename $0` sourceFile.html destinationFile.pdf iteartionRunTime"
else
        _min=9999
        _max=0
        _total=0
        _iteration=$3
        for (( _i=1; _i<=$_iteration; _i++ ))
        do
                _start_time=`date +%s`
                echo "running $_i"
                ~MYUSER/bin/benchmarkWkhtmltopdf.sh $1 $2  > /dev/null 2>&1
                _end_time=`date +%s`
                _processing_time=$((_end_time-_start_time))
                if [ "$_processing_time" -lt "$_min" ]; then
                        _min=$_processing_time
                fi
                if [ "$_processing_time" -gt "$_max" ]; then
                        _max=$_processing_time
                fi
                _total=$(($_total+$_processing_time))
        done
       _processing_time_average=$(echo - | awk "{print $_total/$_iteration}")
        echo "Processing time avg: $_processing_time_average  min:$_min  max:$_max total:$_total"
fi
Posted in Bash, Linux | Comments Off on Bash Scripting Basics (Variable Assignment, If, Loop)

Compress and Extract Files in Linux

Extract:

.tar.bz2
To extract a tar (Tape ARchiver) file, type the following in the shell prompt:

1
tar xvjf yourFileName.tar.bz2

Which will untar it to the current directory. Depending on the file structure that being compressed, it might create sub-directories.
Parameters:
x – extract
v – verbose output (lists all files as they are extracted)
j – deal with bzipped file
f – read from a file, rather than a tape device

.tar.gz or .tgz

1
2
tar xvzf file.tar.gz
tar xvzf file.tgz

Parameters:
-x, –extract, –get extract files from an archive
-v, –verbose verbosely list files processed
-z, –gzip, –gunzip, –ungzip filter the archive through gzip
-f, –file=ARCHIVE use archive file or device ARCHIVE

.bz2 file

1
tar jxf YOUR_FILE_NAME.bz2

.zip file

1
unzip YOUR_FILE_NAME.zip
Posted in Bash, Linux | Tagged | Comments Off on Compress and Extract Files in Linux

Using VBA macro for Excel

Let’s start with something simple. Assume that we have a big spreadsheet and we want to highlight it based on a certain subject — for example, expenses about car. For the sake of the example we’ll keep it short, but in real life you could be dealing with hundreds of rows.

Excel challenge 1

We can see that cell B2 and B7 contain the word “car”, so how do you highlight these cells? You can do this with a VBA macro — VBA gives you full programmatic control of Excel and is far more flexible than a single cell formula.

So let’s start programming!

1. Enable the VBA development environment. In Excel, press Alt + F11. If that doesn’t work:

  • Go to File > Options > Customize Ribbon
  • In the main tabs panel, check Developer
  • Click the Visual Basic icon
  • A new window will open titled “Microsoft Visual Basic for Applications”

Double-click Sheet 1, then go to Insert > Procedure at the top menu. Give it a meaningful name like HighlightCarExpenses.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Public Sub HighlightCarExpenses()
    Rem this is a comment
    Dim emptyCounter As Integer, currentRow As Integer
    Dim currentCell As Range
    Dim currentCellValue As String

    Rem Set initial value for the empty cell counter
    emptyCounter = 0
    currentRow = 1
    currentCellValue = ""

    Rem Scan all column B values
    Rem Stop scanning if we see 3 empty cells in column B in a row
    Do While (emptyCounter < 3)
        currentCellValue = ActiveSheet.Cells(currentRow, 2).Value
        Debug.Print "Value at row " & currentRow & ": " & currentCellValue

        If (currentCellValue = "") Then
            emptyCounter = emptyCounter + 1
        ElseIf InStr(1, currentCellValue, "car", 1) Then
            Debug.Print "Car is found at row: " & currentRow
            ActiveSheet.Cells(currentRow, 2).Interior.Color = RGB(255, 0, 0)
        End If
        currentRow = currentRow + 1
    Loop
    Debug.Print "last row " & currentRow
End Sub

The macro walks down column B and stops once it sees three empty cells in a row — a simple way to guess where the data ends without hard-coding a row count. InStr(1, currentCellValue, “car”, 1) does a case-insensitive substring search (the trailing 1 is the vbTextCompare flag), so “Car”, “CAR”, and “old car” all match.


A few things worth knowing.

RGB values go 0–255, not 0–256. The original macro had RGB(256, 0, 0) which is technically out of range — different Excel versions handle the overflow differently (some clamp to 255, some wrap, some raise an error). The version above uses RGB(255, 0, 0), which is the actual “pure red”. Easy mistake to make if you’re used to 0-indexed integers; VBA’s RGB isn’t.

Dim a, b As Integer doesn’t do what you’d expect. Coming from C, Java, or JavaScript, you’d assume Dim emptyCounter, currentRow As Integer declares both as Integer. It doesn’t — VBA only types the last variable on the line; emptyCounter ends up as Variant. The fix is to type each variable explicitly, as in the macro above: Dim emptyCounter As Integer, currentRow As Integer. This is genuinely one of VBA’s most copy-pasted bugs.

Conditional Formatting can do this without VBA. The original post said you couldn’t highlight “contains car” with a formula — that’s not quite true. Excel’s built-in Conditional Formatting has had a “Format only cells that contain → Specific Text → containing → car” rule for years, and it’ll do exactly what this macro does without writing any code. Reach for VBA when you need behaviour that Conditional Formatting can’t express — multi-step logic, data manipulation, talking to other workbooks — not for simple highlight-by-text.

VBA still works, but Office Scripts is the modern alternative. VBA is great on Windows desktop Excel and isn’t going anywhere, but if you’re on Excel for Mac or Excel on the web, look at Office Scripts — TypeScript-based, runs in Microsoft 365, and it’s the path Microsoft is investing in for cross-platform automation. Same kind of “loop down a column and tweak cells” model, just with modern syntax. 💡

Glossary

Comment: A part of the code (sentences) that will not be executed by the system. A way for the programmer to leave a note. In VBA, comments start with an apostrophe () or the keyword Rem.

Debug: Trace value(s) to find and remove mistakes, or just to ensure program correctness. Debug.Print writes to the Immediate Window in the VBE (open it with Ctrl + G).

Dim: A declaration for a variable.

Sub: A procedure that runs but does not return a value. Public Sub means it can be called from other modules and shows up in the Macros dialog.

Range: A reference to one or more cells (e.g. a single cell, a row, a column, or a rectangular block). The base type for almost everything you do in Excel programmatically.

Integer: A whole-number data type. Examples: 1, 2, 3.

String: An alpha-numeric data type. Examples: “I have 2 dogs”, “Expenses are bad”. Strings are always written in double quotes.

Posted in Visual Basic | Comments Off on Using VBA macro for Excel

Remote copy using scp

Do you ever need to copy one file from one server to another? If you have ssh access to the remote server then you can do an scp command like so:

1
$ scp remoteUsername@remoteServername:remoteFile localFile
Posted in Linux, Operating System | Tagged | Comments Off on Remote copy using scp