<?php
/* 1 */
$dom_bandera = null;
if (!empty($domold)) {
    $dom_bandera = $dom;   // guardo el dom original
    $dom = $domold;        // uso el dom alternativo
}

$sql3 = "SELECT * FROM publicidades_gif WHERE ID = ?";
$stmt3 = $conn->prepare($sql3);
if ($stmt3 === false) {
    // si querés, logueá $conn->error
} else {
    $stmt3->bind_param("i", $ID_publicidad);
    $stmt3->execute();
    $res3 = $stmt3->get_result();

    while ($row3 = $res3->fetch_assoc()) {
        $ID           = $row3['ID'];
        $img          = $row3['img'];
        $url          = $row3['url'];
        $carpetafoto1 = $row3['carpetafoto'];

        $imgHref = rtrim((string)$dom, '/') . '/' . ltrim((string)$carpetafoto1, '/') . '/' . ltrim((string)$img, '/');
        $imgSrc  = $imgHref;

        if (empty($url)) {
            $aHref   = $imgHref;
            $aTarget = '';
        } else {
            // tu lógica original: quitar http/https y dejar "scheme-relative" (//...)
            $u = (string)$url;
            $u = str_replace(['https:', 'http:'], '', $u);
            $aHref   = $u;
            $aTarget = ' target="_blank" rel="noopener"';
        }
        ?>
        <a class="col-12 col-sm-12" id="imagensidebar" href="<?php echo htmlspecialchars($aHref, ENT_QUOTES, 'UTF-8'); ?>"<?php echo $aTarget; ?>>
            <img
                alt="PUBLICIDAD"
                width="100%"
                class="img-responsive"
                border="0"
                src="<?php echo htmlspecialchars($imgSrc, ENT_QUOTES, 'UTF-8'); ?>"
            />
        </a>
        <?php
    }

    $stmt3->close();
}

/* 2 */
if ($dom_bandera !== null) {
    $dom = $dom_bandera; // restauro el dom original
}
?>