Search code examples
phphtmlvariablesecho

Having variables in a function that I can't echo in HTML


I have a form wih an "submit" button, when clicked it calls a display() function.

display() is a function that includes another .php file in where I have the funtcions to do different conversions to the ids.

My problem now is, I want to "echo" the converted ids to my html, which I can't since the variables of the conversions are inside function(s).

Currently I am doing the following, I have the function of the conversion (with the variables I want to echo to my HTML) in one part "php tags" and then I include "php tags, echo" in my HTML.

But sadly, I tried so many things, setting the variables to global, trying to define them elsewhere but the variables will stay undefined.

Basically I am asking, wheter I am doing something wrong, or if there are better/more logical ways of doing this, so I'll be able to call those variables. (remember I need them everytime, since a URL is being submitted when form is submitted.)

Here is my code (index.php)

            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <meta http-equiv="X-UA-Compatible" content="ie=edge">
                <title>STEAM CONV</title>
                <link rel="stylesheet" href="style.css">
            </head>

            <body>
                <form method="post">
                    <input type="text" name="profile_url">
                    <input type="submit" value="click" name="submit">
                </form>

                <h1><?php echo $userid;   ?></h1>

               <img onerror="this.style.display='none'" src="<?php

                    require_once 'steamid.class.php';
                    $input = $_POST["profile_url"];
                    $api_key = "XXXXXXXXXXXXXXXXXXXX";
                    $id = new SteamID($input,$api_key);

                    if ($id->resolveVanity()) {
                        $avatar = $id->toAvatar();
                        echo $avatar;
                    }

               ?>">

            </body>


    <?php

    require_once 'steamid.class.php';


    function urlCheck() {
        $input = $_POST["profile_url"];
        if(substr_count($input, ' ') === strlen($input)) {
          echo "Enter URL";

          return false;
        } else {
          return true;
        }

    }

    if(isset($_POST['submit']))
    {
       display();
    }

    function display() {

        require_once 'steamid.class.php';
        $input = $_POST["profile_url"];
        $api_key = "XXXXXXXXXXXX";
        $id = new SteamID($input,$api_key);

        if(urlCheck()) {

            if ($id->resolveVanity()) {



            $communityid = $id->toCommunityID();
            echo $communityid . ", " . " ";

            $steamid = $id->toSteamID();
            echo $steamid . ", " . " ";

            global $userid;

            $userid = '[U:1:'.$id->toUserID().']';
            echo $userid . ", " . " ";



            } else {
                echo "Profile wasnt found!";
            }

        }
    }


    ?>

steamid.class.php

<?php

        class SteamID {

          protected $id;
          protected $key;

          public function __construct($id,$api_key = '') {
            $this->id = $id;
            $this->key = $api_key;
            return $this;
          }

          public function isID32() {
            if(preg_match('/^STEAM_0:[01]:[0-9]{8,9}$/', $this->id)) {
                return true;
            }
            return false;
          }

          public function isID64() {
            if(preg_match('/7656119[0-9]{10}/i', $this->id)) {
              $this->id = $this->cleanOutput(str_replace('https://steamcommunity.com/profiles/', '', $this->id));
              return true;
            }
            return false;
          }

          public function resolveVanity() {
            $search = $this->cleanOutput(str_replace('https://steamcommunity.com/id/', '', $this->id));
            $api = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key='.$this->key.'&vanityurl='.$search;
            $vanity = $this->getCURL($api);
            if ($vanity['response']['success'] === 1) {
              $this->id = $vanity['response']['steamid'];
              return true;
            }
            else {
              return false;
            }
          }

          public function toAvatar() {
            if ($this->isID32() || $this->isID64() || $this->resolveVanity()) {
              $key = $this->toCommunityID();
              $api = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.$this->key.'&steamids='.$key;
              $data = $this->getCURL($api);
              $image = $data['response']['players'][0]['avatarfull'];
              return $image;
            }
            else {
              return false;
            }
          }

          public function toCommunityID() {
              if (preg_match('/^STEAM_/', $this->id)) {
                  $parts = explode(':', $this->id);
                  return bcadd(bcadd(bcmul($parts[2], '2'), '76561197960265728'), $parts[1]);
              } elseif (is_numeric($this->id) && strlen($this->id) < 16) {
                  return bcadd($this->id, '76561197960265728');
              } else {
                  return $this->id;
              }
          }

          public function toSteamID() {
              if (is_numeric($this->id) && strlen($this->id) >= 16) {
                        $this->id = bcsub($this->id, '76561197960265728');
                        //If subtraction goes negative, shift value up
                        if ($this->id < 0) {
                            $this->id += 4294967296;
                        }
                  $z = bcdiv($this->id, '2');
              } elseif (is_numeric($this->id)) {
                  $z = bcdiv($this->id, '2');
              } else {
                  return $this->id;
              }
              $y = bcmod($this->id, '2');
              return 'STEAM_0:' . $y . ':' . floor($z);
          }

          public function toUserID() {
              if (preg_match('/^STEAM_/', $this->id)) {
                  $split = explode(':', $this->id);
                  echo $split;
                  return $split[2] * 2 + $split[1];
              } elseif (preg_match('/^765/', $this->id) && strlen($this->id) > 15) {

                        $uid = bcsub($this->id, '76561197960265728');
                        if ($uid < 0) {

                            $uid += 4294967296;
                        }
                        return  $uid;

              } else {
                  return $this->id;

              }
          }

          //Function to sent request to SteamAPI
          private function getCURL($url) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
            curl_setopt($ch, CURLOPT_TIMEOUT, 2);
            $request = curl_exec($ch);
            curl_close($ch);
            $json = json_decode($request, true);
            return $json;
          }

          //Remove end slash if present as well as trailing whitespace
          private function cleanOutput($input) {
            $specialInput = htmlspecialchars(str_replace('/', '', $input));
            $cleanInput = preg_replace('/\s/', '', $specialInput);
            return $cleanInput;
          }

        }

Regards :)


Solution

  • The proper way to do this, is to return the object from your function and use it as needed. Please note that I am using PHP shorthand echo (<?=). An even better way to do this would be to have another function to format your variables with the expected strings so you don't need to do it in the HTML.

    function urlCheck() {
        $input = $_POST["profile_url"];
        if(substr_count($input, ' ') === strlen($input)) {
          echo "Enter URL";
    
          return false;
        } else {
          return $input;
        }
    }
    
    function display() {
        $input = urlCheck();
        if($input) {
          require_once 'steamid.class.php';
          $api_key = "XXXXXXXXXXXX";
          $id = new SteamID($input,$api_key);
            if ($id->resolveVanity()) {
                return $id;
            } else {
                echo "Profile wasn't found!";
    
                return false;
            }
        }
    }
    
    if(isset($_POST['submit']))
    {
      $id = display();
    }
    ...
    <h1><?= (isset($id)) ? "[U:1:".$id->toUserID()."], " : "" ?></h1>
    ...
    <img onerror="this.style.display='none'" src="<?= (isset($id)) ? {$id->toAvatar()} : "" ?>">