PHP's escapeshellarg in JavaScript

How to use

You you can install via yarn add locutus and require this function via const escapeshellarg = require('locutus/php/exec/escapeshellarg').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1escapeshellarg("kevin's birthday")"'kevin'\\''s birthday'"
2escapeshellarg("/home'; whoami;''")"'/home'\\''; whoami;'\\'''\\'''"

Here’s what our current JavaScript equivalent to PHP's escapeshellarg looks like.

module.exports = function escapeshellarg(arg) {
// discuss at: https://locutus.io/php/escapeshellarg/
// Warning: this function emulates escapeshellarg() for php-running-on-linux
// the function behaves differently when running on Windows, which is not covered by this code.
//
// original by: Felix Geisendoerfer (https://www.debuggable.com/felix)
// improved by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: divinity76 (https://github.com/divinity76)
// example 1: escapeshellarg("kevin's birthday")
// returns 1: "'kevin'\\''s birthday'"
// example 2: escapeshellarg("/home'; whoami;''")
// returns 2: "'/home'\\''; whoami;'\\'''\\'''"

if (arg.indexOf('\x00') !== -1) {
throw new Error('escapeshellarg(): Argument #1 ($arg) must not contain any null bytes')
}

// Check if the script is running on Windows
let isWindows = false
if (typeof process !== 'undefined' && process.platform) {
isWindows = process.platform === 'win32'
}
if (typeof window !== 'undefined' && window.navigator.platform) {
isWindows = window.navigator.platform.indexOf('Win') !== -1
}

if (isWindows) {
// Windows escaping strategy
// Double quotes need to be escaped and the whole argument enclosed in double quotes
return '"' + arg.replace(/(["%])/g, '^$1') + '"'
} else {
// Unix-like escaping strategy
return "'" + arg.replace(/'/g, "'\\''") + "'"
}
}

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP exec functions


Star