[Agavi-Users] How to validate JSON Post Request?

83 views
Skip to first unread message

André Fiedler / ö_konzept Zwickau

unread,
Feb 20, 2012, 4:00:30 AM2/20/12
to Agavi Users Mailing List

Jannis Moßhammer

unread,
Feb 20, 2012, 4:10:18 AM2/20/12
to Agavi Users Mailing List
Hi,

first, this looks like a GET request and isn't very readable, why not send the correctly formatted json ;) ?

Afaik Agavi has no generic JSON validator, so you should write a custom validator for that.

I once wrote a generic json validator class, but this isn't tested and I found that most of the time, validating JSON is better done 'custom':


Perhaps it helps.

Regards,

Jannis

_______________________________________________
users mailing list
us...@lists.agavi.org
http://lists.agavi.org/mailman/listinfo/users

--
Jannis Moßhammer
Software Developer

NETWAYS GmbH | Deutschherrnstr. 15-19 | D-90429 Nürnberg
Tel: +49 911 92885-0 | Fax: +49 911 92885-77
GF: Julian Hein, Bernd Erk | AG Nürnberg HRB18461

http://www.netways.de | jannis.m...@netways.de




Niklas Närhinen

unread,
Feb 20, 2012, 4:16:32 AM2/20/12
to Agavi Users Mailing List
Hi,
you definitely should not put your request body in the url.

If you have the POST content in the right place (in request body) you have two alternatives:

1) Use a file validator like <validator class="file"><argument>post_file</argument></validator>. Then you can access the raw json string with $rd->getFile('post_file')->getContents()

2) Subclass AgaviWebRequest and do something like this:

    public function initialize(AgaviContext $context, array $parameters = array()) {
        parent::initialize($context, $parameters);
        $rd = $this->getRequestData();
        $jsonData = null;
        if (($this->getMethod() == "write" || $this->getMethod() == "update") && isset($_SERVER['CONTENT_TYPE'])
                && preg_match('#^application/json(;[^;]+)*?$#', $_SERVER['CONTENT_TYPE'])) {
            $jsonStr = "";
            if ($this->getMethod() == "update") {
                $file = $rd->getFile('put_file'); /* @var $file AgaviUploadedFile */
                $jsonStr = $file->getContents();
            }
            else {
                $jsonStr = file_get_contents('php://input');
            }
            if (!strlen($jsonStr)) {
                throw new Exception('Empty request body');
            }
           $jsonData = json_decode($jsonStr, true);
        }
       
        if ($jsonData) {
            $rd->setParameters($jsonData);
        }
    }

Niklas
Reply all
Reply to author
Forward
0 new messages