PHP 字符串与斜杠和变量的连接

PHP string concat with slashes and variables

我正在尝试通过 PHP 脚本执行 rclone 命令。调用的纯文本版本如下所示:

rclone copy /media/storage/Events/01//999/001 events:testing-events-lowres/Events/01/999/001 --size-only --exclude /HiRes/* --include /Thumbs/* --include /Preview/* -P --checkers 64 --transfers 8 --config /home/admin/.config/rclone/rclone.conf -v --log-file=/www/html/admin/scripts/upload_status/001.json --use-json-log

但是当我 运行 它时,我遗漏了一堆东西并且得到除以 0 的错误。

exec("rclone copy $baseDir/".$mainEventCode/".$eventCode".  " events:testing-gfevents-lowres/Events/01/$mainEventCode/".$eventCode/" --size-only --exclude /HiRes/* --include /Thumbs/* --include /Preview/* -P --checkers 64 --transfers 8 --config /www/html/admin/scrips/rclone.conf -v --log-file=$directoryName/$eventCode.json --use-json-log");

我已经尝试了 / 和 " 的许多其他组合,但无法完全拨入。

如果下面的工作正常

rclone 复制 /media/storage/Events/01//999/001 事件:testing-events-lowres/Events/01/999/001 --size-only --exclude /HiRes/* --include /Thumbs/* --include /Preview/* -P --checkers 64 --transfers 8 --config /home/admin/.config/rclone/rclone.conf -v --log-file=/www/html/admin/scripts/upload_status/001.json --use- json-log

下面是相关的 PHP 代码,假设您的变量将包含正确的值。你在连接时犯了一些错误,没有使用正确的 . (点)和“(引号)。

exec("rclone copy ".$baseDir."/".$mainEventCode."/".$eventCode." events:testing-events-lowres/Events/01/".$mainEventCode."/".$eventCode. " --size-only --exclude /HiRes/* --include /Thumbs/* --include /Preview/* -P --checkers 64 --transfers 8 --config /www/html/admin/scrips/rclone.conf -v - -log-file=$directoryName/".$eventCode.".json --use-json-log");

有两种不同的方法可以将变量插入到 PHP 中的字符串中,并且可以混合使用这两种方法 - 这可以很好地工作,但会使代码更难阅读,正如您所发现的。

第一种方法称为插值,您将整个字符串放在“双引号”内,任何变量都插入其中你提到他们。您不需要使用 " 关闭字符串,或在各部分之间使用 .。仅使用插值,您的命令可能如下所示:

exec("rclone copy $baseDir/$mainEventCode/$eventCode events:testing-gfevents-lowres/Events/01/$mainEventCode/$eventCode/ --size-only --exclude /HiRes/* --include /Thumbs/* --include /Preview/* -P --checkers 64 --transfers 8 --config /www/html/admin/scrips/rclone.conf -v --log-file=$directoryName/$eventCode.json --use-json-log");

另一个称为 concatenation,您可以在其中创建 多个单独的字符串 ,然后使用 . 运算符将它们连接在一起.某些部分可以是字符串文字,使用“双引号”或 'single quotes',它们在您编写 时完全成为字符串的一部分 ,包括空格、斜杠和点。其他部分可以是值为字符串的变量。对于长字符串,这很方便,因为您可以在 . 运算符周围添加换行符而不影响输出。通过串联分解您的命令可能如下所示:

exec(
   "rclone copy " . $baseDir . "/" . $mainEventCode . "/" . $eventCode
   . "events:testing-gfevents-lowres/Events/01/" . $mainEventCode
   . "/" . $eventCode . "/ --size-only --exclude /HiRes/*"
   . " --include /Thumbs/* --include /Preview/* -P --checkers 64"
   . " --transfers 8 --config /www/html/admin/scrips/rclone.conf"
   . " -v --log-file=" . $directoryName . "/" . $eventCode . ".json"
   . " --use-json-log"
);

顺便说一下,在动态生成这样的命令时要非常小心,不要让用户直接控制任何变量,否则他们可以选择获得什么 运行 并有可能控制您的服务器。