storing php objects on html form element and passing php objects through GET method?

前端 未结 3 1963
独厮守ぢ
独厮守ぢ 2020-12-29 00:43

I might sound a bit weird but, is there a way? For example, I have a PHP object $foo.

Is there a way to store this object in an HTML form (hidden input)

相关标签:
3条回答
  • 2020-12-29 00:54

    Like pointed out elsewhere already, you can use serialize to turn the object into a string.

    $foo = (object) array(
        'foo' => 'foo & bär',
        'bar' => new StdClass
    );
    
    $serialized = serialize($foo);
    

    This gives:

    O:8:"stdClass":2:{s:3:"foo";s:10:"foo & bär";s:3:"bar";O:8:"stdClass":0:{}}
    

    As you can see there is quotes in that string, so you cannot insert that into a link without risking breaking your markup:

    <a href="http://example.com?s=O:8:" <-- quote closes href
    

    So at the very least you'd have to htmlspecialchars or urlencode that output. However, that would still leave the content easily readable. You could make use of PHP's MCrypt library to put some strong encryption on the string. But if the data really is that sensitive, you should probably find another means of transferal, away from the public facing portion of your site.

    If the data is less sensitive, then you can probably safe some CPU cycles by just obfuscating the string. The easiest way to do that is to run it through gzdeflate:

    echo gzdeflate(serialize($foo));
    

    gives something like

                                                                        
    0 讨论(0)
  • 2020-12-29 00:55

    If it doesn't contain sensitive data you could serialize() it (or even optionally encrypt the serialized data), for example:

    <input type="hidden" name="foo" value="<?php echo htmlspecialchars(serialize($foo), ENT_QUOTES); ?>" />
    

    In the receiving script, unseralize() the POST data to get back the object:

    $foo = unserialize($_POST['foo']);
    
    0 讨论(0)
  • 2020-12-29 01:08

    You can use the serialize and unserialize methods:

    $serialized = serialize($foo);
    

    Now you can store $serialized in your hidden input field. Later, you can read it back and convert to object with unserialize method. For example:

    $foo = unserialize($_POST['my_hidden_field']); // back to object
    
    0 讨论(0)
提交回复
热议问题