PWA, WebAssembly and GraphQL – 2018 new tech trends and what a web developer needs to know

After another tech giant Facebook adapted the PWA, it seems PWA has become one of the most popular technical terms for current web development.

Reference: “Facebook takes first steps in Progressive Web Apps (PWA)”

 

As you can see there are two trends for the web development in 2018 that you (a web developer) should be very well aware of:

  1. PWA – will be integrated to Magento 2.3 with PWA studio – this will instantly enable most of PWA features for Magento on mobile platforms
  2. GraphQL – this is another Facebook invention, it’s becoming more and more popular and it's going to replace RESTful API and XML based web services.

 

By the end of the year PWA and GraphQL would be very likely to become main stream since more and more big players are coming onboard.

 

Coming from a PHP / Laravel background I’ve leant Vue.js and used it in the production, however Magento 2.3 will be released with React as the front-end PWA choice. What's more, because React had performance advantage over other frameworks, so if you are new to PWA, maybe it’s the best choice to start learning React PWA since learning it could provide the best value return in the near future.

 

Just quote it here from “What to Expect from Magento in 2018” (https://trellis.co/blog/expect-magento-2018/):

“In mid-2018, Magento will introduce Progressive Web Applications (PWA) to the platform with Magento PWA Studio. The suite of tools will allow users to build online stores as PWA’s and serve as a learning tool for developers.”

……

“The studio will introduce the new GraphQL 1.0 API style to the API collection.”

For more information, you can read about Magento PWA Studio here.

Further reading:

First Windows 10 Progressive Web Apps (PWA) published by Microsoft hit the Store https://www.windowscentral.com/first-batch-windows-10-progressive-web-apps-here

On the other hand, Golang has officially added the WebAssembly architecture to its road map and had the first commit to the compiler not long ago. Here is the technological statement of WebAssembly architecture for Go.

The WebAssembly architecture will allow Go to become an alternative to JavaScript for writing code that runs in a web browser. This new freedom of choice will hopefully have a positive impact on the software engineering ecosystem overall.

Now it's becoming more interesting.

Laravel Tinker Shell – Access a Laravel controller function through command line

Laravel Tinker Shell is an interactive command like tool that allows you to run a controller function directly via the command line.

Let's see an example below:

Say you have a controller as such: App\Http\Controllers\SomeController

Within it, there's a function call SomeFunction().

Now you want to access SomeFunction() via the Tinker command line:

php artisan tinker

$controller = app()->make('App\Http\Controllers\SomeController');

app()->call([$controller, 'SomeFunction'], []);
// the SomeFunction function is called
// the second param array [] is used to hold the parameters
// leave it empty if there's no parameter.

app()->call([$controller, 'SomeFunction'], [param1 => 321]);
// this is how the parameters are passed in

So you can see the outputs from the command line directly, this is very helpful for testing. However if  you want something permanent you probably may like to make a custom artisan command for long term use.

Laravel Tinker Docs

 

Golang – Dave Cheney talking about SOLID Go Design principle

I started learning Golang since last year and till today I have had some go API built and in production for some medium and large projects.

As a programmer coming from a PHP background, Golang's concurrency model looks mind-blowing to me in the first place and the performance is indeed awesome.

The outcome of my recent project for Glencore Australia calculation API speed upgrade was astonishing - the 7-year old legacy calculation API - which was written in Python - had been re-written completely in Go. The performance gain was pretty much guaranteed as we knew it even when in the early stage of planning and prototyping. Just as what Dropbox did a while ago - follow the link to read the Dropbox official blog post "Open Sourcing Our Go Libraries":

Dropbox owes a large share of its success to Python, a language that enabled us to iterate and develop quickly. However, as our infrastructure matures to support our ever growing user base, we started exploring ways to scale our systems in a more efficient manner. About a year ago, we decided to migrate our performance-critical backends from Python to Go to leverage better concurrency support and faster execution speed. This was a massive effort–around 200,000 lines of Go code–undertaken by a small team of engineers. At this point, we have successfully moved major parts of our infrastructure to Go.

It's been a year now and I'm quite enjoying doing heavy lifting API's in Golang, it's a really beautiful language with bare metal performance. For front-end, the most projects I would still use PHP, as Laravel stack is really nice to do all the regular CRUD - for performance critical API's let's leave to Go to do the magic. 🙂

No matter what programming language you use, having a good software design is always challenging. Designing an application that is maintainable and lasting for changes takes a lot of thinking. SOLID (object-oriented design)  is the group of those principles that could help a programmer to achieve the goal.

In Golang, there's no class. So how does SOLID work in Go? Let's just follow Dave Cheney (Go contributor and author - Australian!) to get into the SOLID design in Go. This is not a new video and it's almost 30 minutes, but well worth watching.

 

How to know if a bot claimed to be Googlebot a real Googlebot? Verify Googlebot

The answer is running Google DNS reverse lookup.

Let's see some straight forward examples:

Example 1:

> host 66.249.66.1
1.66.249.66.in-addr.arpa domain name pointer crawl-66-249-66-1.googlebot.com.

> host crawl-66-249-66-1.googlebot.com
crawl-66-249-66-1.googlebot.com has address 66.249.66.1

Example 2:

> host 66.249.90.77
77.90.249.66.in-addr.arpa domain name pointer rate-limited-proxy-66-249-90-77.google.com.

> host rate-limited-proxy-66-249-90-77.google.com
rate-limited-proxy-66-249-90-77.google.com has address 66.249.90.77

Reference: //support.google.com/webmasters/answer/80553?hl=en

HTML5 JavaScript canvas based smooth signature drawing – Online / web signature capture / hand draw signature input

HTML5 JavaScript canvas based smooth signature drawing - Online / web signature capture / hand draw signature input

This JavaScript library make it possible to hand draw smooth signatures from user input, it's useful in some applications that require user signature for signups, it can output as svg and png formats, and you can use PHP or other server side language to capture the output signature image and store for further use.

https://github.com/szimek/signature_pad

HTML5 canvas based smooth signature drawing http://szimek.github.io/signature_pad/

 

 

Example

Demo

Demo works in desktop and mobile browsers. You can check out its source code for some tips on how to handle window resize and high DPI screens. You can also find more about the latter in HTML5 Rocks tutorial.

Using linux find command – find file name contains certain pattern and change time – send to exec command for further process

This is a good example of combining find command with other commands
Linux find command: find files and send to post prosessing.

If you are dealing with files, you might wonder what the difference is between mtime, ctime and atime.

mtime, or modification time, is when the file was last modified. When you change the contents of a file, its mtime changes.

ctime, or change time, is when the file’s property changes. It will always be changed when the mtime changes, but also when you change the file’s permissions, name or location.

atime, or access time, is updated when the file’s contents are read by an application or a command such as grep or cat.

The easiest way to remember which is which is to read their alphabetical order:

  • Atime can be updated alone

  • Ctime will update atime

  • Mtime will update both atime and ctime.

find /myDir -name 'log*' -and -not -name '*.bz2' -ctime +7 -exec bzip2 -zv {} \;
# find file name has "log" and has no "bz2", with a change day longer than 7 days - send it to exec command
- {} presents the result found
References:
Linux find command - MUST KNOW:

Example:

find /dir -cmin -60 # creation time
find /dir -mmin -60 # modification time
find /dir -amin -60 # access time
 Numeric arguments can be specified as
   +n     for greater than n,
   -n     for less than n,
   n      for exactly n.
   -amin n
          File was last accessed n minutes ago.
   -anewer file
          File was last accessed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the access time of the file it points  to  is  always
          used.
   -atime n
          File  was  last  accessed  n*24 hours ago.  When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to
          have been accessed at least two days ago.
   -cmin n
          File's status was last changed n minutes ago.
   -cnewer file
          File's status was last changed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the status-change time of the file it  points
          to is always used.
   -ctime n
          File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

PHP 7.1+ Swoole v1.9.5 vs Node.js Benchmark Test PHP7 + Swoole beats Node.js

I'd like to introduce this Swoole PHP extension:

Event-driven asynchronous & concurrent & coroutine networking engine with high performance for PHP.http://www.swoole.com/

This is a game-changing extension that would change how PHP works.

According to the bench mark here, it's 12 times faster than Node.js.

Try swoole extension.

  • Ubuntu 16.04 LTS
  • Intel® Core™ i5-4590 CPU @ 3.30GHz × 4
  • 16G Memory

$http = new swoole_http_server("127.0.0.1", 1337, SWOOLE_BASE);

$http->set([
    'worker_num' => 4,
]);

$data = [
  'code' => 'ok',
  'error' => false,
  'payload' => 'Hello World'
];

$http->on('request', function ($request, swoole_http_response $response)  use($data)  {
    $response->header('Content-Type', 'application/json');   
    $response->end(json_encode($data));
});

$http->start();

Node.js v4.2.6

wrk -t4 -c400 -d10s http://127.0.0.1:1337/
Running 10s test @ http://127.0.0.1:1337/
  4 threads and 400 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    16.08ms    2.70ms 237.82ms   90.94%
    Req/Sec     6.05k   510.34     7.10k    91.00%
  240668 requests in 10.02s, 46.36MB read
Requests/sec:  24026.00
Transfer/sec:      4.63MB

PHP7.1+Swoole-v1.9.5

wrk -t4 -c400 -d10s http://127.0.0.1:1337/
Running 10s test @ http://127.0.0.1:1337/
  4 threads and 400 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     1.46ms    1.42ms  27.96ms   85.66%
    Req/Sec    75.29k    36.43k  183.55k    72.75%
  3007806 requests in 10.06s, 605.25MB read
Requests/sec: 299103.32
Transfer/sec:     60.19MB

 

 

What is the difference between MVC and MVVM?

Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?

MVC/MVVM is not an either/or choice.

The two patterns crop up, in different ways, in both ASP.Net and Silverlight/WPF development.

For ASP.Net, MVVM is used to two-way bind data within views. This is usually a client-side implementation (e.g. using Knockout.js). MVC on the other hand is a way of separating concerns on the server-side.

For Silverlight and WPF, the MVVM pattern is more encompassing and can appear to act as a replacement for MVC (or other patterns of organising software into separate responsibilities). One assumption, that frequently came out of this pattern, was that the ViewModel simply replaced the controller in MVC (as if you could just substitute VM for C in the acronym and all would be forgiven)...

The ViewModel does not necessarily replace the need for separate Controllers.

The problem is: that to be independently testable*, and especially reusable when needed, a view-model has no idea what view is displaying it, but more importantly no idea where its data is coming from.

*Note: in practice Controllers remove most of the logic, from the ViewModel, that requires unit testing. The VM then becomes a dumb container that requires little, if any, testing. This is a good thing as the VM is just a bridge, between the designer and the coder, so should be kept simple.

Even in MVVM, controllers will typically contain all processing logic and decide what data to display in which views using which view models.

From what we have seen so far the main benefit of the ViewModel pattern to remove code from XAML code-behind to make XAML editing a more independent task. We still create controllers, as and when needed, to control (no pun intended) the overall logic of our applications.

The basic MVCVM guidelines we follow are:

  • Views display a certain shape of data. They have no idea where the data comes from.
  • ViewModels hold a certain shape of data and commands, they do not know where the data, or code, comes from or how it is displayed.
  • Models hold the actual data (various context, store or other methods)
  • Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.

We also noted that the Sculpture code-gen framework implements MVVM and a pattern similar to Prism AND it also makes extensive use of controllers to separate all use-case logic.

Don't assume controllers are made obsolete by View-models.

I have started a blog on this topic which I will add to as and when I can. There are issues with combining MVCVM with the common navigation systems, as most navigation systems just use Views and VMs, but I will go into that in later articles.

An additional benefit of using an MVCVM model is that only the controller objects need to exist in memory for the life of the application and the controllers contain mainly code and little state data (i.e. tiny memory overhead). This makes for much less memory-intensive apps than solutions where view-models have to be retained and it is ideal for certain types of mobile development (e.g. Windows Mobile using Silverlight/Prism/MEF). This does of course depend on the type of application as you may still need to retain the occasional cached VMs for responsiveness.

Note: This post has been edited numerous times, and did not specifically target the narrow question asked, so I have updated the first part to now cover that too. Much of the discussion, in comments below, relates only to ASP.Net and not the broader picture. This post was intended to cover the broader use of MVVM in Silverlight, WPF and ASP.Net and try avoid people replacing controllers with ViewModels

JavaScript object operations – How to add / remove item from a JavaScript object

Getting into JavaScript frameworks like vue.js and react.js, now it's time to review some of the JavaScript fundamentals.

 

How to remove item from a JavaScript object

Say I create an object as follows:

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI",
    "regex": "^http://.*"
};

What is the best way to remove the property regex to end up with new myObject as follows?

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI"
};
var test = {'red':'#FF0000', 'blue':'#0000FF'};
delete test.blue; // or use => delete test['blue'];
console.log(test);

this deletes test.blue

 

There are two ways to add new properties to an object:

var obj = {
    key1: value1,
    key2: value2
};

Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]" 
How do I add a property to a JavaScript Object using a variable as the name?

You can use this equivalent syntax:

obj[name] = value;
 
How do I check if an object has a key in JavaScript? 

http://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript

Try the javascript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if keyis available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key')produces the result most code is looking for.

 

You'll have to iterate:

for (var k in obj) {
  if (!obj.hasOwnProperty(k)) continue;
  if (obj[k] === "orange") {
    /* yaay! an orange! */
  }
}

Now that "hasOwnProperty" test in there is to make sure you don't stumble over properties inherited from the prototype. That might not be desirable in some cases, and really it's one of the things you kind-of need to understand in order to know for sure whether you do or don't want to make that test. Properties that you pick up from an object's prototype can sometimes be things dropped there by various libraries. (I think the ES5 standard provides for ways to control whether such properties are "iterable", but in the real world there's still IE7.)

 

11.2.1 Property Accessors

I want to use the value of an objects property to name the property of another object. Easy to do in PHP:

$object1->property = 'name';
$object2->{$object1->property} = "value";
echo $object2->name; //outputs "value"

But in Javascript I can't figure out how to do this. The curly braces are used a different way.

Anyone know the php equivalent in javascript?

Thanks 🙂

object2[object1.property] = "value";

 

obj[type]

You use subscript notation.

11.2.1 Property Accessors

Properties are accessed by name, using either the dot notation:

MemberExpression . IdentifierName
CallExpression . IdentifierName

or the bracket notation:

MemberExpression [ Expression ]
CallExpression [ Expression ]

Change paste to paste and indent in sublime text 2/3

Change paste to paste and indent in sublime text 2/3:

Go to Sublime's menu -> preferences -> 'Key Bindings' -> edit the user preference file to add the below:

[
    { "keys": ["ctrl+shift+v"], "command": "paste" },
    { "keys": ["ctrl+v"], "command": "paste_and_indent" }
]

This will turn ctrl+v to paste and indent instead of the default paste.

 

 

OctoberCMS RESTful API plugins

API Generator

Generates RESTful APIs using available models

RESTful API

RESTful API (WebService) for Import/Export Operations with Extended Features

RESTful

Create RESTful APIs with ease

You can start building your custom REST API based on these plugins.

Emmet LiveStyle – live CSS style editing in Chrome via Sublime Text [highly recommended]

This is one of the best live css extension to use with sublime text editor, live css preview and more.
LiveStyle — the first bi-directional real-time edit tool for CSS, LESS and SCSS.
Instantly updates your web-page stylesheet while you edit CSS, LESS or SCSS file in your text editor. No file saving or page reloading: pure real-time experience! And this is the first tool that transfers updates from DevTools back into source code the right way.

Includes Remote View: creates publicly-available URL (aka “reverse tunnel”) to test your local web-sites on any internet-connect device or services like BrowserStack.

 

 

 

My Brackets extension list

Here is my list of brackets extensions for productivity.  http://brackets.io/

Animations deactivatorAlexander Taratin 1.0.0

1279

Disable animations for better perfomance

More info…

Auto console.log generatorBorja Guzman 0.2.6

5962

Allows you to console.log a var with a simple shortcut

More info…

beautify.iodingdong (https://github.com/dingdong-io)1.2.1

167417

Format JavaScript, HTML, and CSS files

More info…

Brackets Additional Right Click MenuDeddy Lasmono Putro 0.5.1

21548

A Brackets extension that add additional functionality to Brackets editor right menu, like cut, copy, paste, select all, Camel Case, UPPERCASE, lowercase, fix indentation and some functionality from ...

More info…

Brackets GitMartin Zagora0.16.6

447216

Integration of Git into Brackets

More info…

Translated into 7 languages, including yours

Brackets PreferencesKonrad Lipner1.0.0

12491

Preferences editor for Brackets. Display/edit all preferences. Have regex search for preference.

More info…

Brackets SASSJason San Jose (https://github.com/jasonsanjose)2.0.5

13545

***IMPORTANT*** Read "More info..." if you have issues removing or installing. Compiles SASS *.sass/*.scss files when changed. Updates styles during Live Preview. Experimental support for Quick Edit.

More info…

Brackets SASS Code HintsAmin Ullah Khan (https://github.com/sprintr)0.1.0

16586

Provides code hints for SASS documents

More info…

Brackets Sass HintsKamil Armatys (https://github.com/karmatys)1.0.3

7737

An extension for Brackets to show SASS hints in the code editor.

More info…

Brackets ToolsYasin Kuyu 0.2.0

44436

Brackets developer tools extension

More info…

Translated into 8 languages, including yours

Brackets TwigAthorcis (https://github.com/Athorcis)1.1.3

12914

Highlight Twig syntax inside HTML files

More info…

Translated into 2 languages, including yours

brackets-compareHubert B Manilla0.2.7

28853

A diff tool for brackets

More info…

BracketstoIXApptoIX Limited 3.3.0

49203

[3.0]Execute,Lorem ipsum, Break Line, Recent Files.Change(Case, Quote, Slash, Tab, Encoding), Sort, (Un)Tag, Clipboard, Internet, (Minify, traceur, sass, compass), Text Replace, Extrators, JSLint ...

More info…

Translated into 3 languages, including yours

ConsoleAlexandru Ghiura1.4.1

22333

Shows console.log & console.error & console.warn without developer tools.

More info…

copycaseAnoop Elias 0.0.1

3194

CopyCase plugin for brackets enable copying text in snake-case to CamelCase and vice-versa, useful for angular developers
Delkos Dark ThemeDavid Sánchez i Gregori0.0.5

33948

A dark, elegant, easy readable theme.

More info…

File Info to ClipboardVince Malone 1.1.0

4168

Copy name, path and directory path of a file to the clipboard.

More info…

FuncDocrOle Kröger 0.8.41

85723

Generates JSDoc,PHPDoc annotations for your functions.

More info…

Indent GuidesLance Campbell (https://github.com/lkcampbell)1.3.7

211281

Show indent guides in the code editor.

More info…

JS CSS MinifierAndrew Bagshaw2.0.0

64092

Easily minify single files or all files in a project. Also includes concatenation features as well as auto-minification on save.

More info…

Translated into 6 languages, including yours

JSHintRaymond Camden (http://www.raymondcamden.com)2.2.20

220503

Adds JSHint support to Brackets.

More info…

Magento 2 HintRafael Corrêa Gomes0.1.0

3235

Ideal for developing Magento 2 themes, get hints of the main functions, classes and methods.

More info…

Translated into 6 languages, including yours

MinimapSenko Anton 3.2.6

90893

The minimap shows a smaller version of your code at the right of the screen. It can be used to quickly scroll to a certain part of your file. This is a fork of brackets-wdminimap by Brian Adams ...

More info…

Paste and IndentAndrew Huth (https://github.com/ahuth)0.2.0

49753

Automatically apply the correct indentation to pasted text

More info…

Permanent ScrollbarsMatt Stow matt@mattstow.com (http://mattstow.com)0.1.0

2410

Makes the file list scrollbars always visible

More info…

PHP Code Quality ToolsMikael Jorhult (http://jorhult.se)0.1.11

69495

Analyze and lint PHP using several code analysis tools. Please note that this extension needs PHP to be installed on your machine to work properly.

More info…

Translated into 5 languages, including yours

PHP SmartHintsAndrew MacKenzie (https://github.com/mackenza)1.2.2

114141

Provides code hints for PHP files including PHP keywords, built-in functions, constants and variables. Also provides hinting for variables in the current open PHP document. Note that this is a ...

More info…

Translated into 4 languages, including yours

PHPLinter for BracketsSerghei1.0.2

13861

This extension works using `php -l` command
Pretty JsonStephen Keep (https://github.com/stephenkeep/)0.1.2

24109

Make Your Json Pretty and Linted, turn a single line of json into multiple lines with ctrl+shift+J

More info…

SASS/SCSS HintsKonstantin Kobs1.2.0

10112

Autocompletion for SASS/SCSS variables and mixins. Color previews included. Forked and updated from: https://github.com/konstantinkobs/brackets-SASShints

More info…

Select Tag ContentsMatthew Seiler 1.0.3

7941

Provides a shortcut (Ctrl/Cmd+Shift+A) for selecting all content between tags in HTML, PHP, XML

More info…

Show WhitespaceDennis Kehrig (https://github.com/DennisKehrig)2.0.1

39215

Visualizes whitespace similar to how Sublime Text does it

More info…

Smarty Syntax HighlightingJeremy Lee (https://github.com/JeremyLee)1.0.0

4891

Enables the built-in Smarty syntax highlighting for the .tpl file type.

More info…

Strip trailing spacesRosen Stoyanov (http://pockata.org)1.3.0

8675

A Brackets extension to strip traling whitespace at the end of the line on document save.

More info…

Tab To SpaceDavid Deraedt (http://www.dehats.com)1.0.0

12800

Converts indentation to tabs or spaces.

More info…

Various improvementsDammmien2.2.1

27999

Add more informations in the status bar, lowercase and uppercase converter, super clipboard, button close all folders in file tree, files search

More info…

White Space SanitizerMiguel Castillo 1.2.1

27523

Bring sanity to your white spaces and tabs leveraging Brackets settings

More info…

Whitespace NormalizerDimitar Bonev (https://github.com/dsbonev/)0.3.0

30850

trims trailing whitespaces; transforms tabs to spaces; adds newline at the end of file

More info…

Fix fatal error for inlcude path and included file not existed using include or require for cron job

When running php in cron, the include and require path may not work.

Eg. when your file has below require or include statement:

require '../includes/common.php';

You will get a fatal error when running using php-cli or php-cli in cron

# php-cli
php /home/username123/public_html/cron/mycronjob.php
# cron
* * * * * php /home/username123/public_html/cron/mycronjob.php

Error got:

Fatal error: require(): Failed opening required '../includes/common.php'
 (include_path='.:/usr/lib/php:/usr/local/lib/php') in
 /home/username123/public_html/cron/mycronjob.php on line 2

To fix this, you need to use php to set include_path attributes so when running cron it'll set the path so the script will learn where to look for the include / require files.

set_include_path

reference: http://php.net/manual/en/function.set-include-path.php

example:

set_include_path('/home/username123/public_html/includes/');
require 'common.php';

My experiences of changing php cron job running by wget to php-cli /usr/bin/php

tool used to convert the cron interval to human readable time: https://crontab.guru/

This is one of my real world experiences.

Lately we migrated some websites with the entire WHM and all the cron jobs running as is.

There were about 12 cron jobs running, something like below:

59 23 6 /usr/bin/wget -O /dev/null "http://www.somedomain.net.au/some-api-data.php" >/dev/null 2>&1

However because of the domain and IP routing changes, we could no longer run wget for any of the php files under these domains.

So my alternative is to move these script running via wget to internally running via php-cli.

Below is the approach:

Firstly created a test cron.

SSH as root, put a small php script to output the time stamp and run as cronjob every minute as below. ( crontab -l will show this line at the bottom)

          • /usr/bin/php /home/website/public_html/date_cron_test.php >> /usr/logs/date_cron_test.log 2> /dev/null
            Successfully generates the log file and had correct record for outputs of each round.

            Then change all the cron jobs like below

            59 23 6 /usr/bin/wget -O /dev/null "http://www.somedomain.net.au/some-api-data.php" >/dev/null 2>&1

to

59 23 6 /usr/bin/php /home/somedomain/public_html/some-api-data.php >> /usr/logs/some-api-data.log 2> /dev/null

Change all the old wget ones to the /usr/bin/php php-cli ones accordingly.

Also the php needs to be set mode with x as executable, eg 755, this depends on your actual server settings.

Finally run service crond reload

It's all set up. All we need to do is checking the cron and php log later to verify.

 

References:

  • Cron job executing php trouble shooting: http://stackoverflow.com/questions/7397469/why-is-crontab-not-executing-my-php-script
  • crontab php file and output to log file result (append mode): http://stackoverflow.com/questions/9456424/crontab-php-file-and-output-to-log-file-result
  • Meanings of 2>&-, 2>/dev/null, |&, &>/dev/null and >/dev/null 2>&1: http://unix.stackexchange.com/questions/70963/difference-between-2-2-dev-null-dev-null-and-dev-null-21
  • cron "BAD FILE MODE": https://www.redhat.com/archives/rhl-list/2005-February/msg02458.html