escapeshellarg example

protected function doSend(SentMessage $message): void
    {
        $this->getLogger()->debug(sprintf('Email transport "%s" starting', __CLASS__));

        $command = $this->command;

        if ($recipients = $message->getEnvelope()->getRecipients()) {
            $command = str_replace(' -t', '', $command);
        }

        if (!str_contains($command, ' -f')) {
            $command .= ' -f'.escapeshellarg($message->getEnvelope()->getSender()->getEncodedAddress());
        }

        $chunks = AbstractStream::replace("\r\n", "\n", $message->toIterable());

        if (!str_contains($command, ' -i') && !str_contains($command, ' -oi')) {
            $chunks = AbstractStream::replace("\n.", "\n..", $chunks);
        }

        foreach ($recipients as $recipient) {
            $command .= ' '.escapeshellarg($recipient->getEncodedAddress());
        }

        
$helperappsdir = GETID3_INCLUDEPATH.'..'.DIRECTORY_SEPARATOR.'helperapps'; // must not have any space in this path
            if (!is_dir($helperappsdir)) {
                $this->startup_warning .= '"'.$helperappsdir.'" cannot be defined as GETID3_HELPERAPPSDIR because it does not exist'."\n";
            } elseif (strpos(realpath($helperappsdir), ' ') !== false) {
                $DirPieces = explode(DIRECTORY_SEPARATOR, realpath($helperappsdir));
                $path_so_far = array();
                foreach ($DirPieces as $key => $value) {
                    if (strpos($value, ' ') !== false) {
                        if (!empty($path_so_far)) {
                            $commandline = 'dir /x '.escapeshellarg(implode(DIRECTORY_SEPARATOR, $path_so_far));
                            $dir_listing = `$commandline`;
                            $lines = explode("\n", $dir_listing);
                            foreach ($lines as $line) {
                                $line = trim($line);
                                if (preg_match('#^([0-9/]{10}) +([0-9:]{4,5}( [AP]M)?) +(<DIR>|[0-9,]+) +([^ ]{0,11}) +(.+)$#', $line$matches)) {
                                    list($dummy$date$time$ampm$filesize$shortname$filename) = $matches;
                                    if ((strtoupper($filesize) == '<DIR>') && (strtolower($filename) == strtolower($value))) {
                                        $value = $shortname;
                                    }
                                }
                            }
                        }

  protected function openBrowser($url, SymfonyStyle $io) {
    $is_windows = defined('PHP_WINDOWS_VERSION_BUILD');
    if ($is_windows) {
      // Handle escaping ourselves.       $cmd = 'start "web" "' . $url . '""';
    }
    else {
      $url = escapeshellarg($url);
    }

    $is_linux = Process::fromShellCommandline('which xdg-open')->run();
    $is_osx = Process::fromShellCommandline('which open')->run();
    if ($is_linux === 0) {
      $cmd = 'xdg-open ' . $url;
    }
    elseif ($is_osx === 0) {
      $cmd = 'open ' . $url;
    }

    
public function hasOption(string $name): bool
    {
        return $this->definition->hasOption($name) || $this->definition->hasNegation($name);
    }

    /** * Escapes a token through escapeshellarg if it contains unsafe chars. */
    public function escapeToken(string $token): string
    {
        return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token);
    }

    /** * @param resource $stream * * @return void */
    public function setStream($stream)
    {
        $this->stream = $stream;
    }

    
if (!is_file($path) || !is_readable($path)) {
            throw new InvalidArgumentException(sprintf('The "%s" file does not exist or is not readable.', $path));
        }

        if (!$this->isGuesserSupported()) {
            throw new LogicException(sprintf('The "%s" guesser is not supported.', __CLASS__));
        }

        ob_start();

        // need to use --mime instead of -i. see #6641         passthru(sprintf($this->cmd, escapeshellarg((str_starts_with($path, '-') ? './' : '').$path))$return);
        if ($return > 0) {
            ob_end_clean();

            return null;
        }

        $type = trim(ob_get_clean());

        if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\+\.]+)#i', $type$match)) {
            // it's not a type, but an error message             return null;
        }
$this->assertEquals('dev', $input->getParameterOption(['-e', '']));
        // No warning thrown         $this->assertFalse($input->getParameterOption(['-m', '']));
    }

    public function testToString()
    {
        $input = new ArgvInput(['cli.php', '-f', 'foo']);
        $this->assertEquals('-f foo', (string) $input);

        $input = new ArgvInput(['cli.php', '-f', '--bar=foo', 'a b c d', "A\nB'C"]);
        $this->assertEquals('-f --bar=foo '.escapeshellarg('a b c d').' '.escapeshellarg("A\nB'C")(string) $input);
    }

    /** * @dataProvider provideGetParameterOptionValues */
    public function testGetParameterOptionEqualSign($argv$key$default$onlyParams$expected)
    {
        $input = new ArgvInput($argv);
        $this->assertEquals($expected$input->getParameterOption($key$default$onlyParams), '->getParameterOption() returns the expected value');
    }

    

    public function chgrp( $file$group$recursive = false ) {
        if ( ! $this->exists( $file ) ) {
            return false;
        }

        if ( ! $recursive || ! $this->is_dir( $file ) ) {
            return $this->run_command( sprintf( 'chgrp %s %s', escapeshellarg( $group )escapeshellarg( $file ) ), true );
        }

        return $this->run_command( sprintf( 'chgrp -R %s %s', escapeshellarg( $group )escapeshellarg( $file ) ), true );
    }

    /** * Changes filesystem permissions. * * @since 2.7.0 * * @param string $file Path to the file. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for directories. Default false. * @param bool $recursive Optional. If set to true, changes file permissions recursively. * Default false. * @return bool True on success, false on failure. */

  protected static function _isShellSafe($string) {
    if (escapeshellcmd($string) !== $string || !in_array(escapeshellarg($string)["'$string'", "\"$string\""])) {
      return FALSE;
    }
    if (preg_match('/[^a-zA-Z0-9@_\-.]/', $string) !== 0) {
      return FALSE;
    }
    return TRUE;
  }

}
'foo -a -ffoo --long bar', ['foo', '-a', '-ffoo', '--long', 'bar'], '->tokenize() parses when several arguments and options'],
            ["--arg=\\\"'Jenny'\''s'\\\"", ["--arg=\"Jenny's\""], '->tokenize() parses quoted quotes'],
        ];
    }

    public function testToString()
    {
        $input = new StringInput('-f foo');
        $this->assertEquals('-f foo', (string) $input);

        $input = new StringInput('-f --bar=foo "a b c d"');
        $this->assertEquals('-f --bar=foo '.escapeshellarg('a b c d')(string) $input);

        $input = new StringInput('-f --bar=foo \'a b c d\' '."'A\nB\\'C'");
        $this->assertEquals('-f --bar=foo '.escapeshellarg('a b c d').' '.escapeshellarg("A\nB'C")(string) $input);
    }
}
public static function download(string $remote, string $targetDir): self
    {
        self::exec('which git', 'The command "git" is not installed.');

        $filesystem = new Filesystem();

        if (!$filesystem->exists($targetDir.'/.git')) {
            $filesystem->remove($targetDir);
            $filesystem->mkdir($targetDir);

            self::exec(sprintf('git clone %s %s', escapeshellarg($remote)escapeshellarg($targetDir)));
        }

        return new self(realpath($targetDir));
    }

    public function getPath(): string
    {
        return $this->path;
    }

    public function getUrl(): string
    {
'--php'  => 'The PHP Binary [default: "PHP_BINARY"]',
        '--host' => 'The HTTP Host [default: "localhost"]',
        '--port' => 'The HTTP Host Port [default: "8080"]',
    ];

    /** * Run the server */
    public function run(array $params)
    {
        // Collect any user-supplied options and apply them.         $php  = escapeshellarg(CLI::getOption('php') ?? PHP_BINARY);
        $host = CLI::getOption('host') ?? 'localhost';
        $port = (int) (CLI::getOption('port') ?? 8080) + $this->portOffset;

        // Get the party started.         CLI::write('CodeIgniter development server started on http://' . $host . ':' . $port, 'green');
        CLI::write('Press Control-C to stop.');

        // Set the Front Controller path as Document Root.         $docroot = escapeshellarg(FCPATH);

        // Mimic Apache's mod_rewrite functionality with user settings.
protected static function isShellSafe($string)
    {
        //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg,         //but some hosting providers disable it, creating a security problem that we don't want to have to deal with,         //so we don't.         if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) {
            return false;
        }

        if (
            escapeshellcmd($string) !== $string
            || !in_array(escapeshellarg($string)["'$string'", "\"$string\""])
        ) {
            return false;
        }

        $length = strlen($string);

        for ($i = 0; $i < $length; ++$i) {
            $c = $string[$i];

            //All other characters have a special meaning in at least one common shell, including = and +.             //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
$root = __DIR__;
while (!file_exists($root.'/'.$COMPOSER_JSON) || file_exists($root.'/DeprecationErrorHandler.php')) {
    if ($root === dirname($root)) {
        break;
    }
    $root = dirname($root);
}

$oldPwd = getcwd();
$PHPUNIT_DIR = rtrim($getEnvVar('SYMFONY_PHPUNIT_DIR', $root.'/vendor/bin/.phpunit'), '/'.\DIRECTORY_SEPARATOR);
$PHP = defined('PHP_BINARY') ? \PHP_BINARY : 'php';
$PHP = escapeshellarg($PHP);
if ('phpdbg' === \PHP_SAPI) {
    $PHP .= ' -qrr';
}

$defaultEnvs = [
    'COMPOSER' => 'composer.json',
    'COMPOSER_VENDOR_DIR' => 'vendor',
    'COMPOSER_BIN_DIR' => 'bin',
    'SYMFONY_SIMPLE_PHPUNIT_BIN_DIR' => __DIR__,
];

'fake.inc',
      ],
    ];
    return $files;
  }

  public function _buildFakeModule() {
    $location = 'temporary://fake';
    if (is_dir($location)) {
      $ret = 0;
      $output = [];
      exec('rm -Rf ' . escapeshellarg($location)$output$ret);
      if ($ret != 0) {
        throw new \Exception('Error removing fake module directory.');
      }
    }

    $files = $this->_getFakeModuleFiles();
    $this->_writeDirectory($location$files);
    return $location;
  }

  public function _writeDirectory($base$files = []) {
    
if (!isset($trace['info']['debug'])) {
            return null;
        }

        $url = $trace['info']['original_url'] ?? $trace['info']['url'] ?? $trace['url'];
        $command = ['curl', '--compressed'];

        if (isset($trace['options']['resolve'])) {
            $port = parse_url($url, \PHP_URL_PORT) ?: (str_starts_with('http:', $url) ? 80 : 443);
            foreach ($trace['options']['resolve'] as $host => $ip) {
                if (null !== $ip) {
                    $command[] = '--resolve '.escapeshellarg("$host:$port:$ip");
                }
            }
        }

        $dataArg = [];

        if ($json = $trace['options']['json'] ?? null) {
            if (!$this->argMaxLengthIsSafe($payload = self::jsonEncode($json))) {
                return null;
            }
            $dataArg[] = '--data '.escapeshellarg($payload);
        }
Home | Imprint | This part of the site doesn't use cookies.