使用twig和Slim框架(版本2)上传文件 – PHP

前端之家收集整理的这篇文章主要介绍了使用twig和Slim框架(版本2)上传文件 – PHP前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用UserFrosting一个用户管理系统,我在通过表单发布文件时遇到一些麻烦,这就是我试过的

这就是我的twig文件的样子.

  1. <form name="eveniment" method="post" action="{{form_action}}" enctype="multipart/form-data">
  2. ...
  3. <input type="file" class="form-control" name="poza" id="poza">
  4. ...
  5. </form>`

这就是我的控制器的样子

  1. $target_dir = "uploads/";
  2. $target_file = $target_dir . basename($_FILES["poza"]["name"]);
  3. $uploadOk = 1;
  4. $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
  5.  
  6. // Check if image file is a actual image or fake image
  7. $check = getimagesize($_FILES);
  8. if($check !== false) {
  9. $ms->addMessage("success","File is an image - " . $check["mime"] . ".");
  10. $uploadOk = 1;
  11. } else {
  12. $ms->addMessage("danger","File is not an image.");
  13. $uploadOk = 0;
  14. }
  15. $ms->addMessage("success",$target_file);
  16. // Check if file already exists
  17. if (file_exists($target_file)) {
  18. $ms->addMessage("danger","Sorry,file already exists.");
  19. $uploadOk = 0;
  20. }
  21. // Check file size
  22. if ($_FILES["poza"]["size"] > 500000) {
  23. $ms->addMessage("danger",your file is too large.");
  24. $uploadOk = 0;
  25. }
  26. // Check if $uploadOk is set to 0 by an error
  27. if ($uploadOk == 0) {
  28. $ms->addMessage("danger",your file was not uploaded.");
  29. // if everything is ok,try to upload file
  30. } else {
  31. if (move_uploaded_file($_FILES["poza"]["name"],$target_file)) {
  32. $ms->addMessage("success","The file ". basename( $_FILES["poza"]["name"]). " has been uploaded.");
  33. } else {
  34. $ms->addMessage("danger",there was an error uploading your file.");
  35. }
  36. }

路线

  1. $app->post('/evenimente/?',function () use ($app) {
  2. $controller = new UF\EvenimentController($app);
  3. return $controller->createEveniment();
  4. });

PHP配置

file_uploads开

upload_max_filesize 128M

除了具有type =“file”的输入外,其他每个输入都会成功发布.

我没有任何错误,我尝试了不同的方法,但没有成功.此外,如果我打印$_FILES [“poza”] [“name”]它将为空.

这个答案假设你正在使用UserFrosting,因为你在UserFrosting Gitter聊天中链接了这个问题.

UserFrosting包括CSRFGuard中间件,以确保所有POST请求都在本地发起.您需要包含CSRF令牌以确保中间件不会阻止POST请求.

由于令牌已经在Twig全局变量中,最简单的方法是使用带有CSRF令牌的隐藏表单字段:

  1. <input type="hidden" name="{{csrf_key}}" value="{{csrf_token}}">

猜你在找的PHP相关文章