Get started with MongoDB and PHP with XAMPP on Windows

Getting started with MongoDB on Windows and developing it with PHP turned out to be quite easy.

You can create a MongoDB database “in the cloud” for free with MongoDB’s Atlas platform – https://cloud.mongodb.com. No credit card required and you’re up and running in under 10 minutes (most of that time is waiting) after filling in a simple form fill and a few button clicks.

Next you need to setup XAMPP if haven’t already. Follow my post Setting up XAMPP for WordPress Development on Windows for details on how to do that. That gives you Apache and PHP running capability.

Finally you need to install MongoDB drivers for PHP under XAMPP. I use https://www.configserverfirewall.com/mongodb/install-mongodb-php-driver-ubuntu-windows/#install-php-mongodb-driver-on-windows to figure that out. The steps are:

  1. Download the drivers for Windows from https://pecl.php.net/package/mongodb and extract the archive (select the “DLL” link for the version you want, scroll to the bottom of the next page, then download from the “DLL List” section for your version of PHP and OS architecture.
  2. Copy the extracted php_mongodb.dll file into <drive>:\xampp\php\ext folder.
  3. Open XAMPP php.ini and add the line: extension=php_mongodb.dll.
  4. Restart the Apache server in XAMPP. You’re good to go.

 

MongoDB Atlas connection string in PHP

If you run MongoDB locally you’ll have PHP code something link this to establish a connection:

<?php
$connection = new MongoDB\Driver\Manager("mongodb://localhost:27017");
var_dump($connection);
?>

If you connect Atlas use a connection string something like:

new MongoDB\Driver\Manager("mongodb+srv://<db-username>:<db-password>@azure-westus-1-fzl9p.azure.mongodb.net/test?retryWrites=true&w=majority");

Where <db-username> and <db-password> are the username and password you created in Atlas.
“azure-westus-1-fzl9p.azure.mongodb.net” is for my the specific Mongo instance – it will be different for you.

The connection string between the double-quotes is the same as was generated when you go into your collection, select the “Connect” button and follow the prompts.

Git: Reset a local branch to last remote commit, remove unstages files, and fix file permissions

I use the Codeanywhere online IDE for my WordPress development. Sometimes I screw up something I’m testing (usually when I try to manipulate the filesystem with PHP) and need to reset my local branch to the last clean commit I sent to remote.

(Note that I said “remote”. I don’t trust local commits. I continually push to remote to have a safe restore point, especially if I need to do a full delete of my local branch. Yes, it has happened more than once.)

Occasionally I find folder permissions screw up as well and I need to reset via the bash command line.

The following commands are what I always come back to.

Note: The “$” in the command below represent the command-line prompt. The actual commands follow it.

 

Reset a local branch to the the last remote commit of the branch

$ git reset --hard HEAD

 

Clean up any uncommitted folders/files that the reset didn’t remove

$ git clean -f -d

 

Set full permission recursively on a folder and all files/sub-folders

Change directory (cd) to the parent folder of the folder you want to set permission on.

$ sudo chmod -R 777 vylesk-module-z1

 

Recursively delete a folder and all files/sub-folders

Change directory (cd) to the parent folder of the folder you want to delete.

$ rm -rf vylesk-module-z1

Note: The “f” means you are not prompted to delete each file/folder.

Bash: Remove file and folder with Windows style directory names and backslashes

The Problem

While working with zip files in WordPress (I’m setting up my own update server and package update process), I manually created a zip file in using 7zip in Windows (my primary operating system) and extracted it via PHP in a Codeanywhere Ubuntu workspace.

The problem was the zip file was created containing Windows paths, so I ended up file with a file name “vylesk-test-plugin\vylesk-test-plugin.txt” and directory name “D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\“.
Notice the backslashes and “D:” drive path.

Removing the file and directory was a problem.

Attempting to perform a simple rm and rm -rf resulted in:

rm: cannot remove './vylesk-test-plugin\vylesk-test-plugin.txt': Permission denied
rm: cannot remove '_temp/vylesk-test-plugin.1.1/D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\': Permission denied

I tried changing file permissions using chmod and that also resulted in:

chmod: changing permissions of 'vylesk-test-plugin.1.1/D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\': Operation not permitted
chmod: changing permissions of 'vylesk-test-plugin.1.1/vylesk-test-plugin\vylesk-test-plugin.txt': Operation not permitted

 

The Solution

The solution turned out to be very simple. I just needed to prefix the command with sudo.

So I ended up with:

sudo rm vylesk-test-plugin\\vylesk-test-plugin.txt
sudo rm -rf 'D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\'

The file and directory then deleted successfully (and I didn’t need an su password, which I don’t know anywhere because it’s in a virtual environment I don’t control).

Note 2 other elements of the commands:

  • In the first ‘rm’ line the “\\” (double-backslash), because backslashes need to be escaped.
  • In the second line I surrounded the directory path with single quotes, an alternative to the double-backslash.

Excel: Cells have left padding space (but it’s not an indent)

Working in Microsoft Excel (2013 and 2016) I noticed what looked like padding (space between the left side of the cell and the text) in some cells in my sheet.

(See the highlighted cell J39)

I didn’t have text indentation in the cell, and “Format Cells > Alignment > Text alignment > Indent” was set to zero.

The cause was the formatting based on the selected cell data type (in the “Number” section of the ribbon).

I had “Accounting” selected which automatically adds some padding.
Changing it to “General” returned it to normal (removed the space) for a cell with just text.

An easy mistake to make but hard to spot.

Cannot login to Nighthawk modem router admin page

I have a NETGEAR D7000 Nighthawk modem router and you can login to the admin screen via the IP 192.168.0.1 or URL http://www.routerlogin.net/.

The problem is, when I try to login on Chrome I get an error page “This page isn’t working – www.routerlogin.net sent an invalid response” with “ERR_INVALID_HTTP_RESPONSE”:

The fix is easy:

Use the FireFox browser.

There must be something in the page that Chrome doesn’t like, bit FireFox is happy to load the page.

Predictable Links to Multiple GSuite/GMail Accounts

I run multiple personal and business domains with Google mail accounts.

I want to create links (both synced in Chrome bookmark bar and in a web page) to each mail account that I know will always take me to the account I want, even when accessing from different devices (I have a minimum of 2 primary laptop devices I login from regularly).

There is a URL schema Google uses to generated each logged-in account – e.g. https://mail.google.com/mail/u/0/#inbox (then increment the number for each inbox) – but if don’t login to each account in the exact same order on each device, then they get out of sync.

 

Today I found a solution.

To access the desired mailbox via a predictable URL, use the following template: https://mail.google.com/mail/u/?authuser=user@gmail.com.

Change the user@gmail.com to the actual email address.

This also works for emails in custom GSuite domains (e.g. my jsnelders.com domain), because underneath all @gmail.com and GSuite domain emails redirect back to the same number based URL template I originally mentioned.

I also figured out the URL to link to a specific Google Calendar is: https://calendar.google.com/calendar/?authuser=user@gmail.com.

Again, the URL will cause a redirect.

 

I’ve only tried these with accounts I’m already logged into. I’m not sure what happens on a new system where you haven’t logged in yet, but I expect they should still work just fine.

 

Resources

I originally performed a search for “link url to multiple gmail account” which lead to to answers at:

 

Update (same day): I somehow logged myself out of all Google accounts in Chrome while trying to re-establish a sync between computers. So mail account links I setup started going to the same Gmail account (the account I setup for the sync). But after logging back into each of my GMail/GSuite accounts all the links worked fine again, so I reckon that’s a validation the permalinks work.

Codeanywhere: Setup a WordPress environment from GitHub repo

Updated: 27 May 2019 (Added “Troubleshooting” at the end).

 

A quick guide to setting up a WordPress development environment in the Codeanywhere online IDE (https://codeanywhere.com/) and linking to an existing GitHub (or other) source control repository (which I assume also contains the WordPress core code).
It’s not entirely obvious so hopefully this helps.

I’m assuming

  • You have already created an account a Codeanywhere.
  • You have already linked Codeanywhere to to your GitHub (or other) source repository.

 

Step 1: In your Codeanywhere Editor page, right-click “Connections” in the left-hand pane and select “New Connection”.

 

Step 2: A “Connection Wizard” dialogue will open. Select “GitHub” (or your relevant source) from the left-side list. A list of repositories will be displayed in the dialogue.

Step 3: Select the repository you want to use. Then un-tick the “Autodetect stack” option below the list (this is what I missed the first time – autodetect doesn’t actually work that well).

 

Step 4: In the next step of the “Connection Wizard” dialogue, scroll down (or search) until you see a “PHP” stack containing “PHP Develppment Stack with Apache, PHP, MySQL, phpMyAdmin and Composer installed”. You can select either Ubuntu or Centos (I work with Ubuntu).
Then select “Create”.

 

That’s it!

A new LAMP environment connected to your GitHub repository should soon available and showing.

Note: I’m new to Codeanywhere (13 May 2019). I’m switching to this IDE from the soon-to-be-closed-and-fucked-by-AWS Cloud9 (c9.io) as my primary IDE for WordPress and so far I’ve only followed the above steps and managed to work [so far successfully] in the SSH terminal. I’m not yet sure about the lifecycle of the Codeanywhere environments yet, or how to run multiple in the editor.

 

Troubleshooting

If you have trouble updating WordPress core or plug-ins within your account and receive a message like this:

To perform the requested action, WordPress needs to access your web server.
Please enter your FTP credentials to proceed.
If you do not remember your credentials, you should contact your web host.

Then add the following line to to wp-config to allow updates:

define( 'FS_METHOD', 'direct' );

See: https://wordpress.stackexchange.com/questions/228591/to-perform-the-requested-action-wordpress-needs-to-access-your-web-server-pleas

Setting up XAMPP for WordPress Development on Windows

Background

I’ve spent the last 3-4 years doing my WordPress development in the Cloud9 IDE (c9.io) until Amazon AWS bought it, fucked up a perfectly good and extremely simple, usable IDe, and now shut down the original service.

I am in the process I switching over to the Codeanywhere IDE as my replacement WordPress development environment, however, I decided it’s time to setup a secondary/backup environment. And being a user of Windows I needed an WAMP (Windows, Apache, MySQL, PHP) style solution to suite.
In the past I’d tried WampServer on my secondary laptop but after leaving and coming back to it, it worked no more. Also, I found it more complicated than I wanted to configure (I hate complicated, particularly in development environments.

So this time I tried something different: XAMPP.

 

System/XAMPP Setup and Configuration

Setup it really easy. Just go to https://www.apachefriends.org/, select the download for you operating system (in my case Windows) and install.

For Windows do the default install, as the following screenshots show.

Step 1:

Step 2:

Step 3:

Step 4:

Step 5:

Step 6:

Step 7:

Step 8:

Step 9 (select your language – English or German):

Step 10: If you ticked “Do you want to start the Control Panel now?” in step 8 then the control panel should start and appear. Services will not start by default (there is an option for that in the control panel Config though).

See the next section for running Apache beside IIS.

 

Conflicts with IIS

If you have IIS installed (as many software developers with Windows will) then you will have conflicts on Port 80. The XAMPP FAQ suggests disabling IIS, but if you’re also a .NET developer like me then you most likely need IIS.

I chose to instead change the port XAMPP uses and this page – How to: Change Your Apache Listen Port Number in XAMPP – Alex Justesen – has all the information you need.

When XAMPP Control Panel first loads you will probably see the following errors:

This is the full log text:

When following the “Alex Justesen” blog post above, the following screenshot show the Apache “Config” and httpd.conf option you need to select.

The general configuration screen for XAMPP (note: I changed my editor from notepad.exe to Notepad++). This is the screen with the “Service and Port Settings” button the “Alex Justesen” post references:

The “Service and Port Settings” screen referenced by the “Alex Justesen” post. I changed “Main Port” to 8080 and “SSL Port” to 4443

Once you finish the the “Alex Justesen” post you can come back to the main XAMPP Control Panel and start Apache and MySQL using the “Start” buttons beside each service:

When starting Apache for the first time you will see the following Windows Security Alert. Select “Allow access” for the service to run:

When starting MySQL for the first time you will see the following Windows Security Alert. Select “Allow access” for the service to run:

You should now see the following success status and logs in XAMPP Control Panel after starting Apache and MySQL:

Select the “Admin” button on the MySQL line to easily open phpmyadmin (you will need this in the section “Setup WordPress”). Note it loads in localhost on your new port:

Select the “Admin” button on the Apache line to easily open XAMPP Dashboard page:

 

XAMPP Control Panel Shortcuts

There are no shortcuts installed to the XAMPP Control Panel (as far as I can tell), so look for xampp-control.exe in your XAMPP installation directory – likely C:\xampp if you use the default install directory.
You will need to run the .exe directly or create your own shortcut to it.

 

Setup Multiple Sites/Ports in XAMPP

Setting up multiple sites in XAMPP (running localhost on multiple ports) was easy.

I followed the following 2 pages:

What you nee to do:

  1. Open “C:\xampp\apache\conf\httpd.conf” (you can do this via the Apache “Config” button in the XAMPP Control Panel.
  2. Look for the line “Listen 80”. Add new Listen lines for any other ports you want to listen for (e.g. I started with 8080 to replace 80, and now I’m adding 8081).
  3. Open “C:\xampp\apache\conf\extra\httpd-vhosts.conf”.
  4. Everything will be commented out, but at the end there is a VirtualHost example like this:
    ##<VirtualHost *:80>
    ##ServerAdmin webmaster@dummy-host2.example.com
    ##DocumentRoot "D:/xampp/htdocs/dummy-host2.example.com"
    ##ServerName dummy-host2.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
    ##</VirtualHost>
  5. Copy and un-comment the entry, then adjust as needed. I created a new site root folder at “C:/xampp/htdocs/8081”, so my entry looks like:
    <VirtualHost *:8081>
        ServerAdmin webmaster@dummy-host2.example.com
        DocumentRoot "D:/xampp/htdocs/8081"
        ServerName dummy-host2.example.com
        ErrorLog "logs/dummy-host2.example.com-error.log"
        CustomLog "logs/dummy-host2.example.com-access.log" common
    </VirtualHost>
  6. “Stop” then “Start” Apache in XAMPP Control panel and you should be good.

 

Setup a DocumentRoot outside of XAMPP ‘htdocs’

I needed to the root document of a site to a folder outside the standard XAMPP installation ‘htdocs’ folder (i.e. pointing to a workspace for my source controlled files).

I followed all the steps above but received the following 2 errors when setting up another environment:

Access forbidden!
You don't have permission to access the requested directory. There is either no index document or the directory is read-protected.

If you think this is a server error, please contact the webmaster.

Error 403
localhost
Apache/2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.5

(Resource used: https://stackoverflow.com/questions/17816732/xampp-access-forbidden-php)

and later followed by:

Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404
localhost
Apache/2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.5

 

(Resource Used: https://stackoverflow.com/questions/17129612/xampp-localhost-returns-object-not-found-after-installing-laravel)

To resolve the issues I ended up with the following VirtualHost configuration:

<VirtualHost *:8081>
    DocumentRoot "C:/Workspaces/my-project"
    ErrorLog "logs/8081-error.log"
    CustomLog "logs/8081-access.log" common
    
    <Directory C:/Workspaces/my-project/> 
        AllowOverride All
        Require all granted 
    </Directory>
</VirtualHost>

Note the <Directory></Directory> element with ‘AllowOverride’ and ‘Require’ lines. That fixed it.

 

Setup WordPress

Note: I have core WordPress and all plug-ins under source control.

Steps to get WordPress running:

  1. Login to phpmyadmin for MySQL. You can do this via the “Admin” button beside MySQL in the XAMPP Control Panel.
  2. Create a new database for your WordPress installation.
  3. (I tried creating a new user to user as the DB user in WordPress but couldn’t get it working, so I’m just using root in this environment.
  4. Setup your site files in the website folder. In my environment C:\xampp\htdocs is the root web folder. I created a sub-folder for my WordPress site and cloned my Git repo in there.
  5. Browser to your site. My apache is running under for 8080 and my site is in a folder called “portal”, so I browser to http://localhost:8080/portal.
  6. Go through the usual process for setting up a new WordPress website.
    1. In the screen for database settings, enter the name of the database you created.
    2. Set the username to “root” and leave password blank.
    3. Leave host name as “localhost”.
  7. Your WordPress site should be good to go!

 

The following screenshots show the standard setup screens for a new WordPress site.

Step 5a – Select a language:

Step 5b – Enter your database connection details. I went with the “root” user (no password) that is created when installing MySQL with XAMPP. You will need to first create a database via the phpmyadmin interface (see steps 1 and 2):

Step 5c – WordPress should now be good to setup:

Step 5d – Create your first admin user:

Step 5e – WordPress should be successfully setup:

Step 5e – And now you can login with your new admin user:

 

 

Resolving display of /var/www/html/dportal.com/wp-content/plugins/query-monitor/wp-content/db.php

After getting WordPress running I immediately started to see “/var/www/html/dportal.com/wp-content/plugins/query-monitor/wp-content/db.php” echoed to every page.

A quick search lead me to HTML Output on site migration · Issue #101 · johnbillion/query-monitor and this comment gave me the answer.

I deleted wp-content/db.php file and no more text.

As this stage I’m not sure what is going to happen when I do this for real and start working in both Windows and my Linux-based IDE.

 

Resources

XAMPP FAQ – https://www.apachefriends.org/faq_windows.html

How to Install XAMPP and WordPress Locally on PC/Windows – WPMU DEV

How to Troubleshoot and Fix Common XAMPP and WordPress Issues – WPMU DEV

 

Uninstall/remove Spotify on Windows 10

This is mainly a post for my own reference.

I had trouble uninstalling the Windows 10 Spotify application from an old system.

Going into Control Panel\Programs\Programs and Features and trying to uninstall simply wouldn’t do anything.

A quick search lead me to https://community.spotify.com/t5/Desktop-Windows/How-to-permanently-uninstall-Spotify-on-Windows-10/td-p/1697157 which had the answer.

Here are the steps you need to take:

  1. Open Windows Task Manager and kill the “Spotify Web Connector” process (It will be something like SpotifyWebConnector.exe or SpotifyWebHelper.exe – sorry, I forgot to note the exact name before writing this post, but it will be obvious in the process list).
  2. Disable your network/internet access (turn off/disconnect your wireless or pull out your network cable).

Now you should be able to uninstall Spotify. Just be patient give it a few seconds when you first try – there’s going to be a bit of a delay before the confirmation dialog comes up.

Don’t forget reconnect your internet access.

WordPress: Changing File Upload and Processing Sizes

[This is a post for self-reference]

Up front I’m going to say I got exactly the help I need from here: https://www.wpbeginner.com/wp-tutorials/how-to-increase-the-maximum-file-upload-size-in-wordpress/.
The author of that post deserves all my credit.

I’m creating this post to summarise it in my own words and to give it a little educational context.


When allowing file uploads on a website there are 3 big things you need to think about:

  • The size of each file.
  • The total size of all files in an upload.
  • The time it takes to process the upload.

Actually, there are a couple of things to consider that are worthy of mention but I won’t cover in this post:

  • Asynchronous uploads (AJAX as we used to call them) can change the figure of an upload, because instead of uploading multiple files at one, you upload one file at a time (even if they are in parallel) so the “total size of all files” number will be different.
  • Tell users about the limits they face before they upload. Also, when uploading images a bit of guidance around things like “27MB images are a stupid side for most sites because 27MB isn’t going to be better than 7MB, and the site will trim the size down to a couple of hundred KB at most anyway.”
  • Trap, log and respond to any errors. This is on my mind because WordPress/PHP seems to like gobbling errors and not telling anyone about it (I’m in the process of hunting down how to handle this and will be a topic of another post).

 

There are 3 main ways in PHP to affect file upload sizes and times:

  • @set_init() in a PHP script itself.
  • php.ini file
  • .hataccess file.

Be aware, as a PHP/Linux novice I reckon there are other defaults and hierarchies that come into play.
This article is spawned by a situation where I was changing php.ini without realising .htaccess had a value overriding it.

 

How do you implement these values?

This is where I rip from the wpbeginner site I mentioned above for quick reference:

1. PHP script file (e.g. functions.php in WordPress themes)

@ini_set( 'upload_max_size' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );

(I haven’t tried this approach yet, but I have used @ini_set() in other instances (e.g. ‘memory_limit’) and it’s worked well.

2. php.ini

upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300

I’ve used this approach in development and it did the trick.

3 .htaccess

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300

Before writing this post I had to fix a production issue and after trying php.ini I got lucky and discovered .htaccess was where the value was coming from.
So the moral: .htaccess overrides php.ini.

Also, I did not need to restart apache for this change to take affect.

 

DISCLAIMER: I haven’t actually read in-depth how all this works. I’m a typical developer who expects other people’s shit to work, and when it doesn’t I’m usually in the middle of my own concerns so it’s a case of “search and scan by keyword until someone else’s solution works for me”.
Such is this age of software development.

 

Need to know what your current settings are?

It’s helpful in debugging and verification to know what your actual PHP settings are so you know what your starting point is (and  you have a number to search your files for).

A good way is to call phpinfo();.

For example, create a file in your site (I call mine info.php) and add the following PHP code:

<?php
phpinfo();
?>

You should see something like the following when you run it. This screenshot shows some output from the section titled “Core”, and the 3 columns are (from left to right): “Directive”, “Local Value” and “Master Value”. I can say from experience the “Local Value” is the one that matters.

phpinfo() output