-2

Hello im using ad rotator dor my website to show different ads per refresh homeeber some ad codes dont work and give php errors. How can i fix that? Getting errors on key,format,height,width,params and document write section. Error is T_STRING unexpected


<?php
$advert = array();

$advert[] = '<script type="text/javascript">
    atOptions = {
        'key' : '123456789',
        'format' : 'iframe',
        'height' : 90,
        'width' : 728,
        'params' : {}
    };
    document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.website/invoke.js"></scr' + 'ipt>');
</script>';

shuffle($advert);
echo $advert[0];
?>```
Hilkai
  • 3
  • 2
  • If you are using adrotate on a wordpress install, it has that option without your custom code. – Michael Mano Jul 22 '21 at 23:41
  • Thanks but im not using wordpress – Hilkai Jul 23 '21 at 00:48
  • Bad practices. Stay away from `document.write`. Also, once a JavaScript script tag is cached it comes from the memory. I would do something more like: `prop1 = 'value 1'; $a = ['key'=>'123456789', 'format'=>'iframe', 'height'=>90, 'width'=>728, 'params'=>$o]; $keys = array_keys($a); shuffle($keys); foreach($keys as $k){ $r[k] = $a[$k]; } echo json_encode($r); ?>` That just gives you a JavaScript Object, so you would need to use AJAX or do like `const resultArray = /* put the above code here */;` – StackSlave Jul 23 '21 at 01:03

1 Answers1

-1

In your code you're creating a single-quoted string containing your Javascript and assigning it to a PHP array element.

However, your string contains single quotes in a variety of places, so PHP sees a jumble of quoted and unquoted strings which it can't make sense of.

Change the code to use HEREDOC syntax:

<?php
$advert = array();

$advert[] = <<<EOT     // <<< is the HEREDOC preamble. EOT is the delimiter
<script type="text/javascript">
    atOptions = {
        'key' : '123456789',
        'format' : 'iframe',
        'height' : 90,
        'width' : 728,
        'params' : {}
    };
    document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.website/invoke.js"></scr' + 'ipt>');
</script>

EOT;           // EOT delimiter marks the end of the string

shuffle($advert);
echo $advert[0];
?>