PHP's escapeshellarg in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { escapeshellarg } from 'locutus/php/exec/escapeshellarg'.

Or with CommonJS: const { escapeshellarg } = require('locutus/php/exec/escapeshellarg')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

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

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

export function escapeshellarg(arg: string): string {
// discuss at: https://locutus.io/php/escapeshellarg/
// parity verified: PHP 8.3
// 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.includes('\x00')) {
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.includes('Win')
}

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, "'\\''") + "'"
}
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP exec functions


Star