skip to Main Content

I want to get random number and passing it between function I tried to tag $randId in user_edit.php?session= but when I tag the same variable $randId into ‘user_add.php?session=’. I cannot get the same random number, I just get nothing. I need a way of passing the same random number value between functions into user_add.php?session=

<?php 

function get_user_edit_link() {
        $url = "http://". $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $x = pathinfo($url);

        $MIN_SESSION_ID = 1000000000;
        $MAX_SESSION_ID = 9999999999;
        $randId = mt_rand($MIN_SESSION_ID, $MAX_SESSION_ID);
        $randId = mt_rand($MIN_SESSION_ID, $MAX_SESSION_ID);

        return $ee = $x['dirname'] . 'user_edit.php?session='. $randId;
}

function get_user_add_link() {
        $url = "http://". $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $x = pathinfo($url);
        return $ee = $x['dirname'] . 'user_add.php?session='. $randId;
}

2

Answers


  1. You can try to create global variable and access it in each function. For example –

    $MIN_SESSION_ID = 1000000000;
    $MAX_SESSION_ID = 9999999999;
    $randId = mt_rand($MIN_SESSION_ID, $MAX_SESSION_ID);
    
    function get_user_edit_link() {
        global $randId;
    }
    

    this way it becomes accessible in both functions, allowing you to share the same random number between them.

    Login or Signup to reply.
  2. Using global variables is generally considered bad practice. Better to pass the values into the functions that need them as an argument:

    <?php 
    
    // declare functions.
    function get_user_edit_link($randId) {
            $url = "http://". $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $x = pathinfo($url);
            return $ee = $x['dirname'] . 'user_edit.php?session='. $randId;
    }
    
    function get_user_add_link($randId) {
            $url = "http://". $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $x = pathinfo($url);
            return $ee = $x['dirname'] . 'user_add.php?session='. $randId;
    }
    
    // Create random ID
    $MIN_SESSION_ID = 1000000000;
    $MAX_SESSION_ID = 9999999999;
    $randId = mt_rand($MIN_SESSION_ID, $MAX_SESSION_ID);
    
    // Call your functions
    
    $link = get_user_add_link($randId);
    // or
    $link = get_user_edit_link($randId);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search