php cookie防篡改

I use this code on my website:

<?php
$pass = "61e7680d2ac47e5b9e3c82118fae6e3cfcddff285ac75bb82872bb01f24ac657";
function valCookie(){
    if (isset($_COOKIE['session'])){
        $cookie = json_decode(hex2bin($_COOKIE['session']), true);
        global $pass;
        $hash = hash('sha256', $_SERVER['REMOTE_ADDR'] . $cookie['uid'] . 
        $cookie['expiry'] . $pass);
        $uid = $cookie['uid'];
        if ((hash_unique($hash, $cookie['hash'])) && ($cookie['expiry'] > time())){
            return $uid; //return user id.
            }
        }
    }
function hashCookie($uid, $expiry){
    global $pass;
    $cookie['uid'] = $uid;
    $cookie['expiry'] = $expiry;
    $cookie['hash'] = hash('sha256', $_SERVER['REMOTE_ADDR'] . $cookie['uid'] . 
    $cookie['expiry'] . $pass);
    $hexCookie = bin2hex(json_encode($cookie));
    setcookie("session", $hexCookie, $expiry);
    if(strlen($uid)){
        return true;
        }
    }
?>

Is it safe to use this to tamper-proof my cookies? I include the time in the hashing to expire the cookie. is this a secure way of doing it?

It's generally a bad idea to roll your own crypto.

Is it safe to use this to tamper-proof my cookies? I include the time in the hashing to expire the cookie. is this a secure way of doing it?

No, you're using a SHA256 hash of values that can largely be provided by attackers instead of HMAC-SHA256. Without HMAC, SHA256 is vulnerable to length-extension attacks.

Instead, consider (in order of preference):

  1. PASETO, which provides tamper-resistant tokens with a high security margin. The only downside is that they're not immune to replay attacks.
  2. JWT, with HS256. The linked library will allow you to securely only ever allow HS256, thereby side-stepping 99.9% of JWT security fails.
  3. Halite's Cookie class. Halite is a usability wrapper for libsodium, a modern cryptography library that now ships with PHP 7.2.