stream_wrapper_unregister / stream_wrapper_restore în PHP

Stream-uri PHP 5.1+

Dezactivează un protocol (de exemplu http) pentru funcțiile de fișier și, cu stream_wrapper_restore, îl readuce.

Sintaxă
stream_wrapper_unregister(string $protocol): bool

Ce face stream_wrapper_unregister / stream_wrapper_restore

stream_wrapper_unregister scoate un wrapper din listă. După stream_wrapper_unregister("http"), file_get_contents("http://...") nu mai funcționează. Se folosește ca să blochezi un protocol sau ca să îl înlocuiești cu propria clasă prin stream_wrapper_register.

stream_wrapper_restore readuce un wrapper încorporat în PHP la varianta lui originală, după ce l-ai scos sau înlocuit.

Parametri

Parametru Descriere
$protocol Numele protocolului, fără ://.

Ce returnează

true la succes, false la eroare.

Exemple

Exemplul 1: Scoate și readu http

<?php
var_dump(stream_wrapper_unregister("http"));
var_dump(in_array("http", stream_get_wrappers()));

var_dump(stream_wrapper_restore("http"));
var_dump(in_array("http", stream_get_wrappers()));

Rezultat

bool(true)
bool(false)
bool(true)
bool(true)

Exemplul 2: Înlocuiește temporar un wrapper

Wrapperul data este înlocuit cu o clasă care refuză orice deschidere. După stream_wrapper_restore funcționează din nou normal.

<?php
class Blocat
{
    public $context;

    public function stream_open(string $path, string $mode, int $options, ?string &$opened_path): bool
    {
        echo "Blocat: $path\n";
        return false;
    }
}

stream_wrapper_unregister("data");
stream_wrapper_register("data", "Blocat");
var_dump(@file_get_contents("data://text/plain,Salut"));

stream_wrapper_restore("data");
var_dump(file_get_contents("data://text/plain,Salut"));

Rezultat

Blocat: data://text/plain,Salut
bool(false)
string(5) "Salut"

Greșeli frecvente

  • Apelezi stream_wrapper_restore pentru un wrapper pe care nu l-ai schimbat. Returnează true, dar afișează Notice: ... was never changed, nothing to restore.

Comenzi înrudite

  • stream_wrapper_register: Înregistrează un protocol propriu (de exemplu mem://), implementat de o clasă, pentru fopen, file_get_contents și celelalte.
  • stream_get_wrappers: Returnează lista protocoalelor pe care funcțiile de fișier le înțeleg (file, http, https, php, data, phar…).