PHP CLI Script

Project Background

I coded this PHP script as part of a coding challenge given by Catalyst IT Australia which is executed from the command line. It accepts a CSV file as an input (using command line options/directives) and processes the CSV file. The parsed file data is inserted into a PostgreSQL database. The CSV file contains test/dummy data, and the script processes this file appropriately.

This PHP script handles the following criteria:

  • CSV file contains user data and have three columns: name, surname, email.
  • CSV file has an arbitrary list of users.
  • The script iterates through the CSV rows and inserts each record into a dedicated PostgreSQL database into the table “users”.
  • The “users” database table is created/rebuilt as part of the PHP script. This is defined as a Command Line directive --create_table.
  • Name and surname is capitalised e.g. from “john” to “John” before being inserted into DB.
  • Email is set to be lower case before being inserted into DB.
  • The script validates the email address before inserting to make sure that it is valid.

The PHP script includes these command line options (directives):

  • --file [csv file name] – this is the name of the CSV to be parsed.
  • --create_table – this will cause the PostgreSQL users table to be built/rebuilt (and no further action will be taken).
  • --dry_run – this will be used with the --file directive in case we want to run the script but not insert into the DB. All other functions will be executed, but the database won't be altered.
  • -u – PostgreSQL username.
  • -p – PostgreSQL password.
  • -h – PostgreSQL host.
  • --help – which will output the above list of directives with details.

Source code is available in my GitHub Repository.

Interested in hiring me for your project?

Looking for an experienced full-stack developer to build your web app or ship your software product? To start an initial chat, just drop me an email at tsmand@yahoo.com or use the form on the contact page.