【问题标题】:PHP message: PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on stringPHP 消息:PHP 致命错误:未捕获的 TypeError:无法访问字符串上类型字符串的偏移量
【发布时间】:2021-06-08 01:18:09
【问题描述】:

我收到以下错误:

PHP message: PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on string

在这一行:

if ($uploadZoneData[1]['size'] != 0) {

在 php 7.4 上我有任何问题,但在 php 8 上我有。

可能是什么问题?

编辑:相关功能的完整代码:

function uploadSingleFile($zoneImage, $fileMoveTo, $fileAllowedExtensions, $fileAllowedSize, $zoneCustomer, $zone)
{
    global $config;

    // define file upload settings
    $errors = array();
    $fileName = $zoneImage['name'];
    $fileSize = $zoneImage['size'];
    $fileTmp = $zoneImage['tmp_name'];
    $fileType = $zoneImage['type'];
    $fileExt = strtolower(end(explode('.', $zoneImage['name'])));
    $MBtoByte = $fileAllowedSize * 1048576;
    $extensions= $fileAllowedExtensions;

    // define errors
    if (in_array($fileExt, $extensions) === false) {
        $errors[] = "Dieser Datei-Typ ist nicht erlaubt";
    }

    if ($fileSize > $MBtoByte) {
        $errors[] = 'Die Datei ist zu gross';
    }

    // finally try to upload the file
    if (empty($errors) == true) {
        $temp = explode(".", $zoneImage["name"]);
        $newfilename = $zoneCustomer . '-' . strtoupper($zone) . '-' . uniqid() . '.' . end($temp);

        move_uploaded_file($fileTmp, $_SERVER["DOCUMENT_ROOT"] . $fileMoveTo . $newfilename);
        $status = '1';
    } else {
        $status = '0';
    }

    // build array of the different outputs
    $uploadStatus = array($status, $newfilename, $errors);

    return $uploadStatus;
}

function updateZoneData($zoneFile, $zoneCustomer, $zone, $zoneLink, $maxWidth, $bannerID)
{
    global $db;

    // get customer values
    $getCustomerValues = getColumnValue('customers', "WHERE `customerNr` = '" . $zoneCustomer . "'");

    // define redirect url
    switch ($zone) {
      case "a1":
        $redirectZone = "zones.php#zones-overview-a1-overview";
      break;
      case "a2":
        $redirectZone = "zones.php#zones-overview-a2-overview";
      break;
      case "b1":
        $redirectZone = "zones.php#zones-overview-b1-overview";
      break;
      case "b2":
        $redirectZone = "zones.php#zones-overview-b2-overview";
      break;
      case "b3":
        $redirectZone = "zones.php#zones-overview-b3-overview";
      break;
      case "b4":
        $redirectZone = "zones.php#zones-overview-b4-overview";
      break;
      case "a9":
        $redirectZone = "zones.php#zones-overview-a9-overview";
      break;
      case "a9-1":
        $redirectZone = "zones.php#zones-overview-a9-1-overview";
      break;
      case "a11":
        $redirectZone = "zones.php#zones-overview-a11-overview";
      break;
      default:
        $redirectZone = "zones.php";
      }

    // upload file to the server
    $uploadZoneData = uploadSingleFile($zoneFile, '/adserver/banners/', array("jpg", "jpeg", "png", "gif"), '3', $zoneCustomer, $zone);

    if ($uploadZoneData[1]['size'] != 0) {
        if ($uploadZoneData[0] == '1') {

            // create ZIP-Backup (zone-banners) from '/adserver/banners' to '/cp/includes/files/zip-backups'
            createZipBackup('/adserver/banners', '/cp/includes/files/zip-backups', 'adserver-banners.zip');

            // get zone values & delete old bannerImg from file-system
            $getZoneDeleteValues = getColumnValue('zones', "WHERE `customerNr` = '" . $zoneCustomer . "' AND `zone` = '" . $zone . "' AND `id` = '" . $bannerID . "'");
            unlink($_SERVER["DOCUMENT_ROOT"] . '/adserver/banners/' . $getZoneDeleteValues['0']['bannerImg']);

            // execute action
            $updateZoneData = $db->update("zones", [
                                                   "customerNr" => $zoneCustomer,
                                                   "customer" => $getCustomerValues['0']['customer'],
                                                   "zone" => $zone,
                                                   "bannerImg" => $uploadZoneData[1],
                                                   "bannerLink" => $zoneLink,
                                                   "maxWidth" => $maxWidth,
                                                   "changeDate" => date("Y-m-d H:i:s")
                                                   ], [
                                                      "id" => $bannerID
                                                      ]);

            redirectTo($redirectZone, 1, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » wurde erfolgreich aktualisiert.", 'ZONES');
        } else {

        // collect and save errors (file-upload)
            $collectedErrors = array_flatten($uploadZoneData[2]);
            setcookie("collectedErrors", '1', time() + (1 * 5), "/"); // expire in 5 seconds
            $_SESSION["collectedErrors"] = $collectedErrors;

            redirectTo($redirectZone, 0, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » konnte nicht aktualisiert werden.", 'ZONES');
        }
    } else {

        // execute action
        $updateZoneData = $db->update("zones", [
                                               "customerNr" => $zoneCustomer,
                                               "customer" => $getCustomerValues['0']['customer'],
                                               "zone" => $zone,
                                               "bannerLink" => $zoneLink,
                                               "maxWidth" => $maxWidth,
                                               "changeDate" => date("Y-m-d H:i:s")
                                               ], [
                                                  "id" => $bannerID
                                                  ]);

        redirectTo($redirectZone, 1, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » wurde erfolgreich aktualisiert.", 'ZONES');
    }
}

【问题讨论】:

  • 这能回答你的问题吗? Cannot use string offset as an array in php
  • 不幸的是,由于它在 php 7.4 下工作,所以不知道我需要在受影响的行上更改什么:/
  • 您不应该与== 进行比较,而不是在if 语句中分配= 吗? -> if ($uploadZoneData[1]['size'] != 0) { ?
  • 否,因为 If 查询检查文件大小是否不为 0,但根据错误消息,这不是问题。
  • $uploadZoneData[1] 是包含来自 $newfilenamenull 的值的 string 而不是索引为 sizearray 如果您试图确定字符串是否为为空,您需要改用strlen($uploadZoneData[1])empty(($uploadZoneData[1])。问题是在 PHP 7.4 中它是一个警告,在 8 中它现在是一个致命错误

标签: php string nginx typeerror offset


【解决方案1】:

首先,欢迎来到 Stack Overflow!

这个错误意味着你试图访问字符串的索引[1]['size'],这是无效的。请务必检查 uploadSingleFile(...) 是否返回一个数组而不是字符串。

我检查了你的代码,我看到返回的uploadSingleFile数组有这三个项目:

$uploadStatus = array($status, $newfilename, $errors);

$newfilename 不是数组。它是一个字符串,正如您在此处定义的那样:

$newfilename = $zoneCustomer . '-' . strtoupper($zone) . '-' . uniqid() . '.' . end($temp);

【讨论】:

  • 感谢您的解释,我现在看到,在 php7.4 中这是一个警告,现在是一个错误,所以要检查它是否为空,我需要替换 "if ($uploadZoneData[1][ 'size'] != 0) {" with "!empty(($uploadZoneData[1])",对吗?
  • @Omexlu 没错!使用!empty(($uploadZoneData[1]['size']),您可以在使用之前证明该数组包含正确的索引。但是请注意,字符串也可以有索引,但它们只是数字,用于访问和修改字符串的字符。
【解决方案2】:

感谢您的回答,我的问题的解决方案是。

替换这个

if ($uploadZoneData[1]['size'] != 0) {

以下内容:

if (!empty($uploadZoneData[1])) {

【讨论】:

    【解决方案3】:

    我不是技术人员,所以我发现自己经常在 StackOverflow 上寻找答案。我遇到了这个问题,来到这里寻找答案。我已经定义了数组(在我的例子中是 $CA = [];),但是它在数组中比 1 更深的级别上失败了。在最深处,我的数组看起来像这样:

    $CA[$row[2]][$row[3]][$row[4]][$row[5]]
    

    我能找到给出这个答案的最简单的方法是必须定义数组的每一级,所以我在数据集的每个循环中都得到了这个:(注意:如果 $row[x] 不为空,所有 $row[任何小于 x 的数字] 都不会为空。)

    WHILE ($row = $result->fetch_row()) {
        if ( !is_null($row[2]) && !is_array($CA[$row[2]]) ) { $CA[$row[2]] = []; }
        if ( !is_null($row[3]) && !is_array($CA[$row[2]][$row[3]]) ) { $CA[$row[2]][$row[3]] = []; }
        if ( !is_null($row[4]) && !is_array($CA[$row[2]][$row[3]][$row[4]]) ) { $CA[$row[2]][$row[3]][$row[4]] = []; }
        if ( !is_null($row[5]) && !is_array($CA[$row[2]][$row[3]][$row[4]][$row[5]]) ) { $CA[$row[2]][$row[3]][$row[4]][$row[5]] = []; }
      ... Code to set the array elements below ...
    

    PHP 不再自动创建您需要的数组深度;您必须明确设置它以避免错误。希望这能让这个页面上的其他非技术人员更清楚。我对任何更好的方法感兴趣(我喜欢保持我的代码简洁!)

    【讨论】:

      【解决方案4】:

      你应该升级你的 php.ini 文件。这将对您有所帮助。因为许多代码不适用于旧版本。所以升级PHP会有所帮助。 否则分享您的完整代码。我们会尽快解决您的错误。

      【讨论】:

      • 请仔细阅读,我使用的是最后一个 php 8 版本。此代码适用于 php 7.4,但不适用于 php 8。我更新了上面的完整代码。
      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 2018-07-21
      • 2021-10-15
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      相关资源
      最近更新 更多