• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP CSRF类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中CSRF的典型用法代码示例。如果您正苦于以下问题:PHP CSRF类的具体用法?PHP CSRF怎么用?PHP CSRF使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了CSRF类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
 }
开发者ID:gymadarasz,项目名称:website,代码行数:8,代码来源:Page.php


示例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);
     }
 }
开发者ID:aliyubash23,项目名称:SwiftRiver,代码行数:28,代码来源:Base.php


示例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);
 }
开发者ID:Furt,项目名称:WebAuctionPlus,代码行数:26,代码来源:html.class.php


示例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/");
    }
}
开发者ID:itillawarra,项目名称:cmfive,代码行数:31,代码来源:createtask.php


示例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;
 }
开发者ID:paragonie,项目名称:airship,代码行数:44,代码来源:Landing.php


示例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;
 }
开发者ID:rukku,项目名称:SwiftRiver,代码行数:44,代码来源:form.php


示例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;
     }
 }
开发者ID:LobbyOS,项目名称:server,代码行数:34,代码来源:Install.php


示例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);
}
开发者ID:Furt,项目名称:WebAuctionPlus,代码行数:28,代码来源:login.php


示例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));
 }
开发者ID:crodas,项目名称:CSRFToken,代码行数:8,代码来源:SimpleTest.php


示例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");
     });
 }
开发者ID:LobbyOS,项目名称:server,代码行数:61,代码来源:Router.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;
}
开发者ID:uwitec,项目名称:mgoa,代码行数:9,代码来源:forms.php


示例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;
 }
开发者ID:abinoda,项目名称:Hacker-Tees,代码行数:10,代码来源:application.php


示例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();
 }
开发者ID:limitium,项目名称:uberlov,代码行数:10,代码来源:actions.class.php


示例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;
 }
开发者ID:kertkulp,项目名称:php-ruhmatoo-projekt,代码行数:10,代码来源:Request.php


示例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');
 }
开发者ID:Wildboard,项目名称:WbWebApp,代码行数:54,代码来源:auth.php


示例16: Render

 public static function Render($template_name, $localized_strings, $data)
 {
     global $template_global_vars, $cphp_debug_enabled;
     $data = array_merge($data, $template_global_vars);
     $templater = new NewTemplater();
     $templater->Load($template_name);
     $templater->Localize($localized_strings);
     $templater->Parse();
     if ($cphp_debug_enabled === true) {
         echo $templater->root->PrintDebug(0, true);
     }
     $result = $templater->Evaluate($localized_strings, $data);
     $result = CSRF::InsertTokens($result);
     return $result;
 }
开发者ID:deanet,项目名称:Neon,代码行数:15,代码来源:class.templater.php


示例17: execute

 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @return  Response
  * @throws  Request_Exception
  * @throws  HTTP_Exception_404
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute()
 {
     if (!$this->_route instanceof Route) {
         throw new HTTP_Exception_404('Unable to find a route to match the URI: :uri', array(':uri' => $this->_uri));
     }
     if (!$this->_client instanceof Request_Client) {
         throw new Request_Exception('Unable to execute :uri without a Kohana_Request_Client', array(':uri' => $this->_uri));
     }
     // Add custom header for CSRF protection where an Ajax
     // request is made via HTTP POST
     if ($this->method() === 'POST' and $this->is_ajax()) {
         $this->headers('X-CSRF-Token', CSRF::token());
     }
     return $this->_client->execute($this);
 }
开发者ID:rukku,项目名称:SwiftRiver,代码行数:36,代码来源:request.php


示例18: configwidget_POST

function configwidget_POST(Web $w)
{
    $p = $w->pathMatch("origin", "id");
    // "origin", "source", "widget");
    // $widget = $w->Widget->getWidget($p["origin"], $p["source"], $p["widget"]);
    $widget = $w->Widget->getWidgetById($p["id"]);
    // $widgetname = $p["widget"];
    if (empty($widget->id)) {
        $w->error("Widget not found", "/{$p['origin']}");
    }
    $vars = $_POST;
    unset($vars[CSRF::getTokenID()]);
    $widget->custom_config = json_encode($vars);
    $widget->update();
    $w->msg("Widget updated", "/{$p['origin']}");
}
开发者ID:itillawarra,项目名称:cmfive,代码行数:16,代码来源:configwidget.php


示例19: processLoginForm

 /**
  * Processa o formulário de login
  */
 protected static function processLoginForm()
 {
     // proteção contra CSRF
     \CSRF::Check();
     $email = isset($_POST['email']) ? $_POST['email'] : null;
     $password = isset($_POST['password']) ? $_POST['password'] : null;
     $hashedPassword = \Hash::password($password);
     $errors = [];
     if (empty($email)) {
         $errors[] = 'Informe seu email';
     }
     if (empty($password)) {
         $errors[] = 'Informe sua senha';
     }
     if (count($errors) > 0) {
         return \View::make('login', compact('errors'));
     }
     $DB = new \DB();
     $sql = "SELECT id, password, status FROM users WHERE email = :email";
     $stmt = $DB->prepare($sql);
     $stmt->bindParam(':email', $email);
     $stmt->execute();
     $rows = $stmt->fetchAll(\PDO::FETCH_OBJ);
     if (count($rows) <= 0) {
         $errors[] = 'Usuário não encontrado';
     } else {
         $user = $rows[0];
         if ($hashedPassword != $user->password) {
             $errors[] = 'Senha incorreta';
         } elseif ($user->status != \Models\User::STATUS_ACTIVE) {
             $errors[] = 'Ative sua conta antes de fazer login';
         } else {
             // busca os dados do usuário para criar os dados no cookie
             $objUser = new \Models\User();
             $objUser->find($user->id);
             // gera um token de acesso
             $token = $objUser->generateToken();
             // salva o cookie com os dados do usuário
             self::saveSessionCookieForUser($objUser);
             // redireciona para a página inicial
             redirect(getBaseURL());
         }
     }
     if (count($errors) > 0) {
         return \View::make('login', compact('errors'));
     }
 }
开发者ID:beingsane,项目名称:UltimatePHPerguntas,代码行数:50,代码来源:SessionsController.php


示例20: action_index

 /**
  * Create a New River
  * Step 1
  * @return	void
  */
 public function action_index()
 {
     $this->step_content = View::factory('pages/river/create/name')->bind('post', $post)->bind('errors', $errors);
     // Check for form submission
     if ($_POST and CSRF::valid($_POST['form_auth_id'])) {
         $post = Arr::extract($_POST, array('river_name', 'river_public'));
         try {
             $river = Model_River::create_new($post['river_name'], $post['river_public'], $this->user->account);
             // Redirect to the /create/open/<id> to open channels
             $this->request->redirect(URL::site() . $this->account_path . '/river/create/open/' . $river->id);
         } catch (ORM_Validation_Exception $e) {
             $errors = $e->errors('validation');
         } catch (Database_Exception $e) {
             $errors = array(__("A river with the name ':name' already exists", array(':name' => $post['river_name'])));
         }
     }
 }
开发者ID:rukku,项目名称:SwiftRiver,代码行数:22,代码来源:create.php



注:本文中的CSRF类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP CSRFProtection类代码示例发布时间:2022-05-20
下一篇:
PHP CSQLWhere类代码示例发布时间:2022-05-20
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap