Converting Ruby to PHP

I’m not a PHP guy and I need to convert this code from Ruby to PHP which I’ll insert into a WordPress website:

#controller

def action1
  @value1 =
    if @current_user
      @current_user.value1
    else
      if cookies[:value1].blank?
        value1 = SecureRandom.hex(6)
        cookies[:value1] = {
          :value => value1,
          :expires => 5.years.from_now.utc
        }

        value1
      else
        cookies[:value1]
      end
    end
end

#view
<script>
  someMethod({'key1': <%= @value1 %> })
</script>

where @current_user is an instance of a model User. Here’s my attemps:

Read More
# 123.php (view)
<?php
  $user = get_current_user();
  if ($user) {
    $value1 = $user.value1();
  } else {
    if(!isset($_COOKIE["value1"])) {
      $retVal = "????"; // how to generate 12 random digitst the way SecureRandom.hex(6) does?
      setcookie("value1", $retVal, time() + (86400 * 30) * 365 * 5, "/");
      $value1 = $retVal;
    } else {
      $value1 = $_COOKIE["value1"];
    }
  }
?>

<script>
  someMethod({'key1': <?php echo $value1 ?> })
</script>

I’m not sure get_current_user() is what I’m looking for, though.

Other mistakes?

Related posts

Leave a Reply

1 comment

  1. I’m not a Ruby guy, but at least the following should be valid PHP.

    <?php
      $user = get_current_user();
      if ($user) {
        $value1 = $user->value1(); ///// need to use -> not .
      } else {
        if(!isset($_COOKIE["value1"])) {
          $retVal = openssl_random_pseudo_bytes(6); ////// 
          setcookie("value1", $retVal, time() + (86400 * 30) * 365 * 5, "/");
          $value1 = $retVal;
        } else {
          $value1 = $_COOKIE["value1"];
        }
      }
    ?>
    
    <script>
      someMethod({'key1': <?php echo $value1 ?> })
    </script>
    

    See manual for more info.