本文整理汇总了PHP中CSRF类的典型用法代码示例。如果您正苦于以下问题:PHP CSRF类的具体用法?PHP CSRF怎么用?PHP CSRF使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CSRF类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: forms
public function forms(Post $post, CSRF $csrf)
{
foreach ($post as $key => $value) {
$this->tpl->{$key} = $value;
}
$this->tpl->csrf = $csrf->generate()->input();
$this->tpl->verror = $post->verror;
}
示例2: action_share
/**
* REST endpoint for sharing droplets via email
*/
public function action_share()
{
$this->template = '';
$this->auto_render = FALSE;
if ($this->request->method() != "POST") {
throw HTTP_Exception::factory(405)->allowed('POST');
}
// Extract the input data to be used for sending the email
$post = Arr::extract($_POST, array('recipient', 'drop_title', 'drop_url', 'security_code'));
$csrf_token = $this->request->headers('x-csrf-token');
// Setup validation
$validation = Validation::factory($post)->rule('recipient', 'not_empty')->rule('recipient', 'email')->rule('security_code', 'Captcha::valid')->rule('drop_title', 'not_empty')->rule('drop_url', 'url');
// Validate
if (!CSRF::valid($csrf_token) or !$validation->check()) {
Kohana::$log->add(Log::DEBUG, "CSRF token or form validation failure");
throw HTTP_Exception::factory(400);
} else {
list($recipient, $subject) = array($post['recipient'], $post['drop_title']);
// Modify the mail body to include the email address of the
// use sharing content
$mail_body = __(":user has shared a drop with you via SwiftRiver\n\n:url", array(':user' => $this->user['owner']['username'], ':url' => $post['drop_url']));
// Send the email
Swiftriver_Mail::send($recipient, $subject, $mail_body);
}
}
示例3: Display
public function Display()
{
global $config, $lpaths;
// render header/footer
$this->outputs['header'] = RenderHTML::LoadHTML('header.php');
$this->outputs['footer'] = RenderHTML::LoadHTML('footer.php');
$this->outputs['header'] = str_replace('{AddToHeader}', $this->tempHeader, $this->outputs['header']);
// insert css
$this->outputs['css'] = trim($this->outputs['css']);
if (!empty($this->outputs['css'])) {
$this->outputs['css'] = "\n" . $this->outputs['css'] . "\n";
}
$this->outputs['header'] = str_replace('{css}', $this->outputs['css'], $this->outputs['header']);
// common tags
$this->tags['site title'] = $config['site title'];
$this->tags['page title'] = $config['title'];
$this->tags['lastpage'] = getLastPage();
$this->tags['sitepage title'] = $config['site title'] . (empty($config['title']) ? '' : ' - ' . $config['title']);
$this->tags['token'] = CSRF::getTokenURL();
$this->tags['token form'] = CSRF::getTokenForm();
// finish rendering page
$output = $this->outputs['header'] . "\n" . $this->outputs['body'] . "\n" . $this->outputs['footer'] . "\n";
RenderHTML::RenderTags($output, $this->tags);
echo $output;
unset($output, $this->outputs);
}
示例4: createtask_POST
function createtask_POST(Web &$w)
{
$w->Task->navigation($w, "Create Task");
// unserialise input from step I and store in array: arr_req
$arr_req = unserialize($w->request('formone'));
// set relevant dt variables with: Today.
$arr_req['dt_assigned'] = Date('c');
$arr_req['dt_first_assigned'] = Date('c');
// insert Task into database
$task = new Task($w);
$task->fill($arr_req);
$task->insert();
// if insert is successful, store additional fields as task data
// we do not want to store data from step I, the task_id (as a key=>value pair) nor the FLOW_SID
if ($task->id) {
foreach ($_POST as $name => $value) {
if ($name != "formone" && $name != "FLOW_SID" && $name != "task_id" && $name !== CSRF::getTokenID()) {
$tdata = new TaskData($w);
$arr = array("task_id" => $task->id, "key" => $name, "value" => $value);
$tdata->fill($arr);
$tdata->insert();
unset($arr);
}
}
// return to task dashboard
$w->msg("Task " . $task->title . " added", "/task/viewtask/" . $task->id);
} else {
// if task insert was unsuccessful, say as much
$w->msg("The Task could not be created. Please inform the IT Group", "/task/index/");
}
}
示例5: post
/**
* Grab post data, but only if the CSRF token is valid
*
* @param InputFilterContainer $filterContainer - Type filter for POST data
* @param bool $ignoreCSRFToken - Don't validate CSRF tokens
*
* @return array|bool
* @throws SecurityAlert
*/
protected function post(InputFilterContainer $filterContainer = null, bool $ignoreCSRFToken = false)
{
if ($this->airship_http_method !== 'POST' || empty($_POST)) {
return false;
}
if ($ignoreCSRFToken) {
if ($filterContainer) {
try {
return $filterContainer($_POST);
} catch (\TypeError $ex) {
$this->log('Input validation threw a TypeError', LogLevel::ALERT, \Airship\throwableToArray($ex));
return false;
}
}
return $_POST;
}
if ($this->airship_csrf->check()) {
if ($filterContainer) {
try {
return $filterContainer($_POST);
} catch (\TypeError $ex) {
$this->log('Input validation threw a TypeError', LogLevel::ALERT, \Airship\throwableToArray($ex));
return false;
}
}
return $_POST;
}
$state = State::instance();
if ($state->universal['debug']) {
// This is only thrown during development, to be noisy.
throw new SecurityAlert(\__('CSRF validation failed'));
}
$this->log('CSRF validation failed', LogLevel::ALERT);
return false;
}
示例6: open
/**
* Generates an opening HTML form tag.
*
* // Form will submit back to the current page using POST
* echo Form::open();
*
* // Form will submit to 'search' using GET
* echo Form::open('search', array('method' => 'get'));
*
* // When "file" inputs are present, you must include the "enctype"
* echo Form::open(NULL, array('enctype' => 'multipart/form-data'));
*
* @param mixed form action, defaults to the current request URI, or [Request] class to use
* @param array html attributes
* @return string
* @uses Request::instance
* @uses URL::site
* @uses HTML::attributes
*/
public static function open($action = NULL, array $attributes = NULL)
{
if ($action instanceof Request) {
// Use the current URI
$action = $action->uri();
}
if (!$action) {
// Allow empty form actions (submits back to the current url).
$action = '';
} elseif (strpos($action, '://') === FALSE) {
// Make the URI absolute
$action = URL::site($action);
}
// Add the form action to the attributes
$attributes['action'] = $action;
// Only accept the default character set
$attributes['accept-charset'] = Kohana::$charset;
if (!isset($attributes['method'])) {
// Use POST method
$attributes['method'] = 'post';
}
// Only render the CSRF field when the POST method is used
$hidden_csrf_field = $attributes['method'] == 'post' ? self::hidden('form_auth_id', CSRF::token()) : '';
return '<form' . HTML::attributes($attributes) . '>' . $hidden_csrf_field;
}
示例7: checkDatabaseConnection
/**
* Check if the credentials given can be used to establish a
* connection with the DB server
*/
public static function checkDatabaseConnection()
{
try {
$db = new \PDO("mysql:host=" . self::$database['host'] . ";port=" . self::$database['port'], self::$database['username'], self::$database['password'], array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION));
self::$dbh = $db;
self::$dbh->exec("CREATE DATABASE IF NOT EXISTS `" . self::$database['dbname'] . "`");
self::$dbh->query("USE `" . self::$database['dbname'] . "`");
$notable = false;
$tables = array("options", "data");
// The Tables of Lobby
foreach ($tables as $tableName) {
$results = self::$dbh->prepare("SHOW TABLES LIKE ?");
$results->execute(array(self::$database['prefix'] . $tableName));
if (!$results || $results->rowCount() == 0) {
$notable = true;
}
}
if (!$notable) {
/**
* Database tables exist
*/
echo ser("Error", "Lobby Tables with prefix <b>" . self::$database['prefix'] . "</b> exists. Delete (DROP) those tables and <cl/><a class='btn orange' href='install.php?step=3&db_type=mysql" . \CSRF::getParam() . "'>Try Again</a>");
return false;
}
} catch (\PDOException $Exception) {
self::log("Database Connection Failed : " . $Exception->getMessage());
echo ser("Error", "Unable to connect. Make sure that the settings you entered are correct. <cl/><a class='btn orange' href='install.php?step=3&db_type=mysql" . \CSRF::getParam() . "'>Try Again</a>");
return false;
}
}
示例8: doCheckLogin
function doCheckLogin()
{
global $config;
if (!isset($_POST[LOGIN_FORM_USERNAME]) || !isset($_POST[LOGIN_FORM_PASSWORD])) {
return;
}
$username = trim(stripslashes(@$_POST[LOGIN_FORM_USERNAME]));
$password = stripslashes(@$_POST[LOGIN_FORM_PASSWORD]);
session_init();
if (CSRF::isEnabled() && !isset($_SESSION[CSRF::SESSION_KEY])) {
echo '<p style="color: red;">PHP Session seems to have failed!</p>';
CSRF::ValidateToken();
exit;
}
CSRF::ValidateToken();
$password = md5($password);
$config['user']->doLogin($username, $password);
if ($config['user']->isOk() && getVar('error') == '') {
// success
$lastpage = getLastPage();
if (strpos($lastpage, 'login') !== FALSE) {
$lastpage = './';
}
ForwardTo($lastpage);
exit;
}
unset($username, $password);
}
示例9: testInvalidCodeWrongIP
public function testInvalidCodeWrongIP()
{
CSRF::setSecret(uniqid(true));
$_SERVER['REMOTE_ADDR'] = '8.8.8.8';
$code = CSRF::generate();
$_SERVER['REMOTE_ADDR'] = '8.8.4.4';
$this->assertFalse(CSRF::verify($code));
}
示例10: defaults
/**
* Define some pages by default
*/
public static function defaults()
{
/**
* Route App Pages (/app/{appname}/{page}) to according apps
*/
self::route("/app/[:appID]?/[**:page]?", function ($request) {
$AppID = $request->appID;
$page = $request->page != "" ? "/{$request->page}" : "/";
/**
* Check if App exists
*/
$App = new \Lobby\Apps($AppID);
if ($App->exists && $App->enabled) {
$class = $App->run();
$AppInfo = $App->info;
/**
* Set the title
*/
Response::setTitle($AppInfo['name']);
/**
* Add the App item to the navbar
*/
\Lobby\UI\Panel::addTopItem("lobbyApp{$AppID}", array("text" => $AppInfo['name'], "href" => $AppInfo['url'], "subItems" => array("app_admin" => array("text" => "Admin", "href" => "/admin/apps.php?app={$AppID}"), "app_disable" => array("text" => "Disable", "href" => "/admin/apps.php?action=disable&app={$AppID}" . \CSRF::getParam()), "app_remove" => array("text" => "Remove", "href" => "/admin/apps.php?action=remove&app={$AppID}" . \CSRF::getParam())), "position" => "left"));
$pageResponse = $class->page($page);
if ($pageResponse === "auto") {
if ($page === "/") {
$page = "/index";
}
if (is_dir($class->fs->loc("src/page{$page}"))) {
$page = "{$page}/index";
}
$html = $class->inc("/src/page{$page}.php");
if ($html) {
Response::setPage($html);
} else {
ser();
}
} else {
if ($pageResponse === null) {
ser();
} else {
Response::setPage($pageResponse);
}
}
} else {
echo ser();
}
});
/**
* Dashboard Page
* The main Page. Add CSS & JS accordingly
*/
self::route("/", function () {
Response::setTitle("Dashboard");
\Lobby\UI\Themes::loadDashboard("head");
Response::loadPage("/includes/lib/lobby/inc/dashboard.php");
});
}
示例11: smarty_function_csrf_protected
function smarty_function_csrf_protected($params, $smarty)
{
import('system/share/security/csrf');
$name = $params['name'] ? $params['name'] : 'CSRF_TOKEN';
$csrf_token = CSRF::generate($name);
return <<<EOF
<input type="hidden" name="{$name}" value="{$csrf_token}" />
EOF;
}
示例12: before
public function before()
{
parent::before();
if (!CSRF::check()) {
throw new ApplicationException("Cross site request forgery.", 403);
}
// Set base title
$this->template->title = array('Hacker Tees');
$this->template->section = NULL;
}
示例13: executeShow
public function executeShow(sfWebRequest $request)
{
$this->forward404Unless($this->inbox = Doctrine::getTable('Inbox')->find(array($request->getParameter('id'))), sprintf('Object inbox does not exist (%s).', $request->getParameter('id')));
$this->comments = Comment::getFor($this->inbox);
$this->form = new CommentInboxForm();
$this->form->setCommented($this->inbox);
$this->form->setDefault('noVote', 1);
$this->inboxed = Doctrine_Query::create()->select()->from('sfGuardUserProfile p')->leftJoin('p.Inboxed i')->where('i.inbox_id = ?', $this->inbox->getId())->execute();
$this->csrf = CSRF::getToken();
}
示例14: valid
public static function valid($token)
{
if (!CSRF::valid($token)) {
$css_files = array();
$view = "access_denied";
\CODOF\Smarty\Layout::load($view, $css_files);
return false;
}
return true;
}
示例15: action_register
/**
* Simple register for user
*
*/
public function action_register()
{
$this->template->content = View::factory('pages/auth/register');
$this->template->content->msg = '';
//if user loged in redirect home
if (Auth::instance()->logged_in()) {
$this->request->redirect(Route::get('oc-panel')->uri());
} elseif (core::post('email') and CSRF::valid('register')) {
$email = core::post('email');
if (Valid::email($email, TRUE)) {
if (core::post('password1') == core::post('password2')) {
//check we have this email in the DB
$user = new Model_User();
$user = $user->where('email', '=', $email)->limit(1)->find();
if ($user->loaded()) {
Form::set_errors(array(__('User already exists')));
} else {
//create user
$user->email = $email;
$user->name = core::post('name');
$user->status = Model_User::STATUS_ACTIVE;
$user->id_role = 1;
//normal user
$user->password = core::post('password1');
$user->seoname = $user->gen_seo_title(core::post('name'));
try {
$user->save();
} catch (ORM_Validation_Exception $e) {
//Form::errors($content->errors);
} catch (Exception $e) {
throw new HTTP_Exception_500($e->getMessage());
}
//login the user
Auth::instance()->login(core::post('email'), core::post('password1'));
//send email
$user->email('auth.register', array('[USER.PWD]' => core::post('password1'), '[URL.QL]' => $user->ql('default', NULL, TRUE)));
Alert::set(Alert::SUCCESS, __('Welcome!'));
//login the user
$this->request->redirect(Core::post('auth_redirect', Route::url('oc-panel')));
}
} else {
Form::set_errors(array(__('Passwords do not match')));
}
} else {
Form::set_errors(array(__('Invalid Email')));
}
}
//template header
$this->template->title = __('Register new user');
}