Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php symfony4:csrf令牌无效。请尝试重新提交表单_Php_Forms_Controller_Twig_Symfony4 - Fatal编程技术网

Php symfony4:csrf令牌无效。请尝试重新提交表单

Php symfony4:csrf令牌无效。请尝试重新提交表单,php,forms,controller,twig,symfony4,Php,Forms,Controller,Twig,Symfony4,我在提交表单时在Symfony4中遇到此错误:csrf令牌无效。请尝试重新提交表单。 我尝试实现CSRF保护,因为我希望我的表单输入使用引导设置样式 这是我的表格: <?php // src/Form/NewsType.php namespace App\Form; use App\Entity\News; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface;

我在提交表单时在Symfony4中遇到此错误:
csrf令牌无效。请尝试重新提交表单
。 我尝试实现CSRF保护,因为我希望我的表单输入使用引导设置样式

这是我的表格:

<?php

// src/Form/NewsType.php
namespace App\Form;

use App\Entity\News;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class NewsType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('image', NewsImageType::class, array('required' => false))
            ->add('content', TextareaType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => News::class,
            // enable/disable CSRF protection for this form
            'csrf_protection' => true,
            // the name of the hidden HTML field that stores the token
            'csrf_field_name' => '_token',
            // an arbitrary string used to generate the value of the token
            // using a different string for each form improves its security
            'csrf_token_id'   => 'publish-news',
        ));
    }
}
我的控制器:

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Filesystem\Filesystem;
use App\Entity\News;
use App\Form\NewsType;
use App\Form\NewsType2;

/**
 * @Route("/{_locale}/news", requirements={"_locale" = "fr|en"})
 */
class NewsController extends BackController
{
    /**
     * @Route("/", name="news")
     */
    public function index(Request $request)
    {
        $this->initialize();

        $repository = $this->getDoctrine()->getRepository(News::class);
        $nbNews = $repository->getNbNews();

        $news = new News();
        $form = $this->createForm(NewsType::class, $news)
            ->add('save', SubmitType::class, array('label' => 'Publier'));

        $form->handleRequest($request);

        if ($form->isSubmitted() AND $form->isValid()) {
            $submittedToken = $request->request->get('token');

            // 'publish-news' is the same value used in the template to generate the token
            if ($this->isCsrfTokenValid('publish-news', $submittedToken)) {
                $news->setUser($this->getUser());
                $news->setSharingUser($this->getUser());

                $image = $news->getImage();

                $em = $this->getDoctrine()->getManager();

                if ($image != NULL) {
                    $em->persist($image);
                }
                $em->persist($news);
                $em->flush();

                return $this->redirectToRoute('news');
            }
        }

        $this->addToTemplateArray(array(
            'form' => $form->createView(),
            'nb_news' => $nbNews,
            'nav' => "news",
        ));

        return $this->render('news/news.html.twig', $this->templateArray);
    }
我的模板:

{# templates/blog/index.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}{{ parent() }} | News{% endblock %}

{% block body %}
    {% if is_granted('IS_AUTHENTICATED_FULLY') %}
        <div class="news-form">
            {{ form_start(form) }}

            {#{{ form_label(form.content) }}#}
            {{ form_errors(form.content) }}
            {#{{ form_widget(form.content) }}#}

            {{ form_errors(form.image) }}
            {{ form_widget(form.image.image) }}

            {#Joindre <a href="javascript:void(0);">une photo</a> |
            <a href="javascript:void(0);">un album</a>#}

            <div class="form-group">
                <textarea class="form-control" id="news_content" name="news[content]" required="required"></textarea>
                <button type="submit" id="news_save" name="news[save]">Publier</button>
            </div>

            <input type="hidden" name="_token" value="{{ csrf_token('publish-news') }}" />

            {#{{ form_end(form) }}#}
        </div>
    {% else %}
        <a href="{{ path('login') }}">{{ 'action.sign_in'|trans }}</a> pour pouvoir publier.
    {% endif %}

    <h3>{{ 'advert.nombre'|transchoice(nb_news) }} du monde</h3>

    <div>
        <a id="sort-date" href="javascript:void(0);">Sort by date</a> |
        <a id="sort-sharings" href="javascript:void(0);">Sort by sharings</a> |
        <a id="sort-comments" href="javascript:void(0);">Sort by comments</a>
    </div>

    <div id="news-list" style="text-align: center;">
        <img src="{{ asset('images/ajax-loader.gif') }}"></img>
    </div>
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script src="{{ asset('build/js/news.js') }}"></script>
    <script src="{{ asset('build/js/news_ready.js') }}"></script>
{% endblock %}
{#templates/blog/index.html.twig}
{%extends'base.html.twig%}
{%block title%}{{parent()}}新闻{%endblock%}
{%block body%}
{%if'is'u AUTHENTICATED'u FULLY')%}
{{form_start(form)}}
{{{form_标签(form.content)}}}}
{{form_errors(form.content)}}
{{{form_小部件(form.content)}}}}
{{form_errors(form.image)}}
{{form_小部件(form.image.image)}
{#Joindre|
#}
公开者
{{{form_end(form)}}}
{%else%}
倒酒。
{%endif%}
{{‘广告名称’| transchoice(NBU新闻)}世界报
|
|
{%endblock%}
{%block javascripts%}
{{parent()}}
{%endblock%}
我不想使用
{{form\u end(form)}
。如何解决这个问题


我试图重现Symfony文档的
如何实现CSRF保护
。但是我不明白为什么CSRF令牌会出现错误。

以及为什么您不想使用
form\u end
?我不知道我在
form\u end
中遇到了相同的错误。只需用令牌删除隐藏的
输入
form_end
将自动呈现令牌字段。我将
allow_extra_fields=>true
放入,因为我有
此表单不应包含额外字段
错误,但现在我得到
在执行“插入新闻(标题、内容、添加时间、更改时间、用户id、共享用户id、来源新闻、图像)”值时发生异常(?、?、?、?、?、?、?、?、?、?)”带参数[“News”,null,“2018-09-23 09:16:24”,“2018-09-23 09:16:24”,4,4,null,null]:
因为即使在输入中输入一些文本,内容也是空的。因此,csrf的问题得到了解决。
{# templates/blog/index.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}{{ parent() }} | News{% endblock %}

{% block body %}
    {% if is_granted('IS_AUTHENTICATED_FULLY') %}
        <div class="news-form">
            {{ form_start(form) }}

            {#{{ form_label(form.content) }}#}
            {{ form_errors(form.content) }}
            {#{{ form_widget(form.content) }}#}

            {{ form_errors(form.image) }}
            {{ form_widget(form.image.image) }}

            {#Joindre <a href="javascript:void(0);">une photo</a> |
            <a href="javascript:void(0);">un album</a>#}

            <div class="form-group">
                <textarea class="form-control" id="news_content" name="news[content]" required="required"></textarea>
                <button type="submit" id="news_save" name="news[save]">Publier</button>
            </div>

            <input type="hidden" name="_token" value="{{ csrf_token('publish-news') }}" />

            {#{{ form_end(form) }}#}
        </div>
    {% else %}
        <a href="{{ path('login') }}">{{ 'action.sign_in'|trans }}</a> pour pouvoir publier.
    {% endif %}

    <h3>{{ 'advert.nombre'|transchoice(nb_news) }} du monde</h3>

    <div>
        <a id="sort-date" href="javascript:void(0);">Sort by date</a> |
        <a id="sort-sharings" href="javascript:void(0);">Sort by sharings</a> |
        <a id="sort-comments" href="javascript:void(0);">Sort by comments</a>
    </div>

    <div id="news-list" style="text-align: center;">
        <img src="{{ asset('images/ajax-loader.gif') }}"></img>
    </div>
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script src="{{ asset('build/js/news.js') }}"></script>
    <script src="{{ asset('build/js/news_ready.js') }}"></script>
{% endblock %}