#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    65
    Rep Power
    9

    Using PHP $global to set a JavaScript variable


    I have some code that sets a PHP $global that I need to access in a JavaScript and don't seem to be able to get it right. Can you use a global in the JS function? or will I have to set a separate php variable to import some how. Is it indeed possable to do this? where am I going wrong?

    Any help greatly appreciated

    Thanks

    PHP Code:
            <?PHP
        $global
    ['$var_date_color'] ="2";
        
    ?>

        <script type="text/javascript">
        // attempt 1
        // syntax error, unexpected T_ENCAPSED_AND_WHITESPACE....
        var colpicker = "<?php echo $global['$var_date_color'?> ";

        // attempt 2
        // syntax error, unexpected T_ENCAPSED_AND_WHITESPACE....
        <?php print("var colpicker = " $global['$var_date_color'] . " ;\n");?>

        </script>
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    I'm not getting any errors (PHP 5.4.7). Are you actually using PHP 4? Then that's the problem. This version has been abandoned 6(!) years ago, and it hasn't received any security patches since 2008. You're a bit late.

    This code doesn't make a lot of sense, anyway. What is '$var_date_color' supposed to do? You do realize that the $var stuff doesn't get treated as a variable, right? And what is $global? Maybe you meant $GLOBALS?

    Injecting a raw variable into a script container is also pretty suicidal.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    65
    Rep Power
    9
    My mistake - I'm using 5.3.6 NOT 4

    1/ '$var_date_color' is just a php variable name (admittedly using var in the name is confusing but it relates to a date color reference that is variable in nature) It basically sets the background color of a calendar day / date div in the PHP depending on a db query - the JS part is attached to some ajax that sets the background on click and then submits to the db.

    2/ XSS - yeah I'm aware of the implications and will sanitise when I get it working.

    3/ $global / $GLOBALS - I inherited the code as $global and it worked so left it alone. I'll investigate this further.
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    The error is not in that snippet. Show us the full code (at least up to the error line) and the complete error message (you should strip off any sensitive data like file paths, of course).
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    65
    Rep Power
    9
    Your right! - the error isn't in that snippet, I have just been fiddling on a test page...

    Top bit of the page - this does show the error.

    Relevant bits highlighted with:
    ///////////////////////////
    ///////////////////////////
    the bad thing
    ///////////////////////////
    ///////////////////////////

    Error:
    PHP Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\xxx.php on line 139

    PHP Code:
    <?PHP

    $global 
    "";
    $field "";
    $input "";
    $text "";

    $serverName "xxx.xxx.xxx.xxx";
    $connectionInfo = array( "Database"=>"xxxx""UID"=>"xxxx""PWD"=>"xxxx");

    $global['$conn'] = sqlsrv_connect$serverName$connectionInfo);
    if( 
    $conn === false ) {die( print_rsqlsrv_errors(), true));}

    $global['envself'] = $_SERVER['PHP_SELF'];

    ////////////////////////////////////
    ////////////////////////////////////
    $global['$var_date_color'] ="2";  // this goes into all the PHP functions but can't get it into the JS!
    ////////////////////////////////////
    ////////////////////////////////////

    ini_set('error_reporting'E_ALL E_STRICT);
    ini_set('display_errors''On');
    error_reporting(E_ALL);

    #ini_set('log_errors', 'On');
    #ini_set('error_log', 'errors.log');

    if (isset($_GET['ajax'])) {
        
    $input['ajax'] = $_GET['ajax'];
    } else {
        
    $input['ajax'] = "";
    }
    if (
    $input['ajax']=="1") {

        if (isset(
    $global['dbname'])) {
        } else {
            if (
    $global['dbname']=="") {
                exit;
            }
        }

        
    $field['ajax_calendar_username'] = $_GET['u'];
        
    $field['ajax_calendar_date'] = $_GET['d'];

        if (
    $field['ajax_calendar_date']!="") {

            
    $field['ajax_calendar_status'] = $_GET['s'];
            
    $field['ajax_calendar_colour'] = $_GET['dsc'];

            if (
    $field['ajax_calendar_status'] >= "1") {
                
    $query "INSERT INTO oc_calendar (start_date, end_date, username, datestatus) VALUES ('$field[ajax_calendar_date] 00:01', '$field[ajax_calendar_date] 23:59', '$field[ajax_calendar_username]', '$field[ajax_calendar_colour]');";
                
                
    $response "Event ADDED = $field[ajax_calendar_date] - date_calendar_status = $field[ajax_calendar_colour]";
            
            } else {
    //if ($field['ajax_calendar_colour'] == "0")
                
    $query "DELETE FROM oc_calendar WHERE start_date ='$field[ajax_calendar_date] 00:01:00' AND username = '$field[ajax_calendar_username]';";
                
                
    $response "Event REMOVED - $field[ajax_calendar_date] - date_calendar_status = $field[ajax_calendar_status];
            }

            
    $stmt sqlsrv_query$global['$conn'], $query);
            
    print_r($field['ajax_calendar_colour']);

        } 
    //  end bracket for: " if $field['ajax_calendar_date']!="""

        
    print "<span class=\"text\">".$response."</span>";  // rem this line
        
    exit;

    //  end bracket for: "if ajax input ==1"

    function calendar($year ""$month ""$username "0"$small "0"$calendar_owner "0") {

    global 
    $global;
    global 
    $field;
    global 
    $input;
    global 
    $text;

    if (isset(
    $global['timezone'])) {
    } else {
        
    $global['timezone'] = "";
    }
    if (
    $global['timezone']=="") {
        
    $global['timezone'] = "America/Los_Angeles";
    }

    if (
    function_exists('date_default_timezone_set')) {
        
    date_default_timezone_set($global['timezone']);
    }

    if (
    "$month"=="") {
        
    $month date("n");
    }
    if (
    "$year"=="") {
        
    $year date("Y");
    }

    if (isset(
    $_GET['m'])) {
        
    $month $_GET['m'];
    }
    if (isset(
    $_GET['y'])) {
        
    $year $_GET['y'];
    }



    $last_year $year;
    $last_month $month;
    $last_month--;
    if (
    "$last_month"=="0") {
    $last_year--;
    $last_month "12";
    }

    $next_year $year;
    $next_month $month;
    $next_month++;
    if (
    "$next_month"=="13") {
    $next_year++;
    $next_month "1";
    }

    $timestamp mktime (000$month1$year);

    $time date("H:i:s");

    $monthname date("F"$timestamp);

    if (
    $calendar_owner=="1") {
        print<<<END

    <script type="text/javascript" src="functions.js"></script>
    <script type="text/javascript" src="ajax_queue.js"></script>
    <script type="text/javascript">

    ////////////////////////////////////
    ////////////////////////////////////
    //var colpicker = "2";  // This works  
    var colpicker = "<?php echo 
    $global['$var_date_color'] ?> ";  // this does not 
    ////////////////////////////////////
    ////////////////////////////////////


    //document.write(colpicker);

    var calendar_status = new Array();


    function calendar_date(id,status,datecolour,username,default_color) {



        var dateid = document.getElementById(id);

        //var calcol = calendar_status[id]

        if (calendar_status[id]) {

        } else {
            calendar_status[id] = status;
        }
        
        if (calendar_status[id]==="0") {
            calendar_status[id] = colpicker;
    datecolour = colpicker;
            alert("alert 1: datecolour="+datecolour+" calendar_status"+calendar_status[id]);
        
        } else {
            calendar_status[id] = "0";
    datecolour = colpicker;  // this controls the display after click
            alert("alert 2: calendar_status"+calendar_status[id]);
        }

        SimpleAJAXCall('calendar.php?ajax=1&u=' + username + '&dsc=' + datecolour + '&d=' + id + '&s=' + calendar_status[id],SimpleAJAXCallback, '', 'response');


        
        if (calendar_status[id]=="0") {
            dateid.style.background = "#" + default_color;
        } else {

            if (calendar_status[id]=="1") {
                
            if (datecolour="2") {
            dateid.style.background = "#1BE059"; // Green
            alert("dc 2 Green  datecolour"+datecolour+" status"+calendar_status[id] ); 
        }
             else if (datecolour="3") {
            dateid.style.background = "#E0D91B"; // Yellow
            alert("dc 3 Yellow datecolour"+datecolour+" status"+calendar_status[id] );
        }

        

        
        } else if (calendar_status[id]=="1") {  // dynamic number
            dateid.style.background = "#E01B5D"; // Red E01B5D
            alert("calendar_status status 1 Red datecolour "+datecolour+" status"+calendar_status[id] );

        } else if (calendar_status[id]=="2") {  // dynamic number
            dateid.style.background = "#1BE059"; // Green 1BE059
            alert("calendar_status - status 2 Green datecolour "+datecolour+" status"+calendar_status[id] );

        } else if (calendar_status[id]=="3") {  // dynamic number
            dateid.style.background = "#E0D91B"; // Yellow   Yellow E0D91B
            alert("calendar_status - status 3 Yellow datecolour "+datecolour+" status"+calendar_status[id] );
        }
        
        

        }
    }

    </script>

    END;
    }
    ?>
    Last edited by dwair; September 11th, 2013 at 07:20 AM.
  10. #6
  11. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by dwair
    I have just been fiddling on a test page...
    That's not a good idea. Always give us the actual code, not something you made up as some kind of representative. In your example, there wasn't even a syntax error.

    The actual code is completely different. You have a large heredoc, which has some PHP code with array variables in it. Since heredoc behave like double quoted strings, the parser tries to make sense of these variables. And that's where it fails. You have something similar to this:

    PHP Code:
    echo "$global['$var_date_color']"
    PHP cannot handle the single quoted string index inside the double quoted string. And it would yield a nonsense result, anyway, because it would evaluate $var_date_color instead of leaving it alone.

    There's two ways around this: Either use a nowdoc instead of a heredoc. Then you get the behaviour of a single quoted string.

    Or do what PHP is made for: Output the HTML stuff as HTML and not code.

    PHP Code:
    <?php

    ...

    if (
    $calendar_owner=="1"):
    ?>
        <!-- this is the HTML part -->
        <script type="text/javascript" src="functions.js"></script> 
        <script type="text/javascript" src="ajax_queue.js"></script> 
        <script type="text/javascript"> 
        ...
    <?php endif;
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    65
    Rep Power
    9
    Thanks for the reply and all your help

    After a quick read around this, I think nowdoc will be the way forward.
  14. #8
  15. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by dwair
    After a quick read around this, I think nowdoc will be the way forward.
    I don't see why you'd use that instead of PHP tags, but OK.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo