We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Ajax request - access only from local domain

How make this code in phalcon?

$domain = parse_url($_SERVER['HTTP_REFERER']);\n
$domain = $domain['host'];
if($domain != $_SERVER['SERVER_NAME'])
    die();

I want to Ajax requests were only available with the local domain...but code not work:

class AjaxController extends AjaxResponse
{
    public function initialize()
    {
        $request = new Phalcon\Http\Request();
        $host = $request->getHttpHost();
        // return string(10) "localhost3"

        $referer = $request->getHTTPReferer();
        // return string(0) ""

        die(var_dump($referer));
    }

    public function indexAction()
    {
        $this->view->disable();
        die("0");
    }

    public function authenticationAction() 
    {
        $this->setJsonResponse();
        return array("ajax" => false, "details" => "test" );
    }

    public function dAction() 
    {
        $this->setJsonResponse();
        return array("ajax" => false, "details" => "test" );
    }
}

Maybe there are other ways to improve the security of ajax requests?



12.2k

Three backticks + language for highlight. '''php // like this ''' (where ' means backtick)

// like this


13.8k

Viktoras, thx! Maybe there are other ways to improve the security of ajax requests?



12.2k

Try

if ($request->getClientAddress() != "127.0.0.1") {
    die("Only local requests allowed");
}


13.8k

Sorry for the incorrect...with this code users can not make requests, because they ClientAdress different. I want to ajax request to be available only to those users who have made it to the my site. (exp. domain.com), but i can not get user referrers



12.2k

Oh, I see now. Yeah, for this purpose you need to check HTTP_REFERER, however keep in mind, that this header is sent by browser/client. It can be disabled. So this is not a reliable method.

Also, you can do this in your .htaccess, @see https://altlab.com/htaccess_tutorial.html

Also you can google on "Disable hotlinking" for more examples.



13.8k

BIG thx!!!