Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.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
在自定义jQuery、AJAX和PHP表单(SilverStripe)中验证图像文件_Php_Jquery_Ajax_Forms_Silverstripe - Fatal编程技术网

在自定义jQuery、AJAX和PHP表单(SilverStripe)中验证图像文件

在自定义jQuery、AJAX和PHP表单(SilverStripe)中验证图像文件,php,jquery,ajax,forms,silverstripe,Php,Jquery,Ajax,Forms,Silverstripe,我正在完成一个简单的参赛表格。通常我们会使用userforms SilverStripe扩展(),但这是一种页面类型,该表单需要是页面类型中的一个部分。我有一些设置现在可能不是完美的,但已经做过的工作。然而,包含图像上传字段让我很反感 通常,在CMS之外,如果没有插件,我会使用$_文件['upload\u field\u name']['type或name或size']来验证上传字段。但我不确定我是否能够在这里使用它,因为我在CMS中工作 这就是我到目前为止所做的: jQuery+AJAX代码:

我正在完成一个简单的参赛表格。通常我们会使用userforms SilverStripe扩展(),但这是一种页面类型,该表单需要是页面类型中的一个部分。我有一些设置现在可能不是完美的,但已经做过的工作。然而,包含图像上传字段让我很反感

通常,在CMS之外,如果没有插件,我会使用$_文件['upload\u field\u name']['type或name或size']来验证上传字段。但我不确定我是否能够在这里使用它,因为我在CMS中工作

这就是我到目前为止所做的:

jQuery+AJAX代码:

 (function ($) {
    $(document).ready(function () {
        var SubmitBtn = $('.SubmitEntry');
        var FirstName = $('.FirstNameTxt');
        var LastName = $('.LastNameTxt');
        var EmailAddress = $('.EmailTxt');
        var Image = $('.UploadImage');

        SubmitBtn.on('click', function (e) {
            var required = [FirstName, LastName, EmailAddress, Image];
            var containsError = false;
            e.preventDefault();
            for (i = 0; i < required.length; i++) {
                var input = required[i];
                if ((input.val() == "")) {
                    containsError = true;
                    input.addClass('error-field');
                    $('.Error-Msg').show();
                } else {
                    input.removeClass('error-field');
                }
            }
            if (containsError == false) {
                $('.Error-Msg').hide();
                ajax_script();
            }
        });

        function ajax_script() {
            var form_data = {
                firstname: FirstName.val(),
                lastname: LastName.val(),
                useremail: EmailAddress.val(),
                image: Image.val()
            };
            $.ajax({
                type: "POST",
                url: "/home/ContestSubmission",
                data: form_data,
                dataType: "json"
            }).done(function (response) {
                for (var i = 0; i < response.length; i++) {
                    var status = response[i].status;
                    if (status == "error") {
                        var errorMessage = response[i].message;
                        if (response[i].field == "email") {
                            $('.Error-Msg').show();
                            $('.Error-Msg').html("<br />" + errorMessage.message);
                            EmailAddress.addClass("error-field");
                        }
                        /* else if image is not valid, show error message */
                    }
                    else if (status == "success") {
                        $('#contest-submissions')[0].reset();
                        alert("Thank you for your entry!");
                    }
                }
            });
        }
    });
}(jQuery));

$ = jQuery.noConflict();
(函数($){
$(文档).ready(函数(){
变量SubmitBtn=$('.submittery');
var FirstName=$('.FirstNameTxt');
var LastName=$('.LastNameTxt');
var EmailAddress=$('.EmailTxt');
var Image=$('.UploadImage');
在('click',函数(e)上提交{
var required=[FirstName,LastName,EmailAddress,Image];
var containsError=错误;
e、 预防默认值();
对于(i=0;i”+errorMessage.message);
EmailAddress.addClass(“错误字段”);
}
/*否则,如果图像无效,则显示错误消息*/
}
否则如果(状态=“成功”){
$(“#竞赛提交”)[0]。重置();
提醒(“谢谢您的参与!”);
}
}
});
}
});
}(jQuery));
$=jQuery.noConflict();
这是位于Page.php中的CompetingSubmisson函数:

public function ContestSubmission()
{
    $fname = $this->getRequest()->postVar('firstname');
    $lname = $this->getRequest()->postVar('lastname');
    $useremail = $this->getRequest()->postVar('useremail');
    $image = $this->getRequest()->postVar('image');

    $errorField = "";
    $return = array();

    if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) {
        $validatonStatus = "error";
        $errorField = "email";
        $errorList = "The email is not in the correct format. Please re-enter it.";
    } /* else if $image is not valid i.e. size or file type */
    else {

        $contestEntry = new ContestEntrySubmission();

        $contestEntry->FirstName = $fname;
        $contestEntry->LastName = $lname;
        $contestEntry->EmailAddress = $useremail;
        $contestEntry->UploadedImage = $image;

        $contestEntry->write();

        $validatonStatus = "success";
        $errorField = "";
        $errorList = "";

        $from = 'secret@secret.com';
        $to = '[testing email address]';
        $subject = 'Contest Entry Submission';

        $body = "Below is the contest entry submission information:" . "<br /><br />";
        $body .= "<strong>First Name:</strong> " . $fname . "<br/>" . "<strong>Last Name:</strong> " . $lname . "<br/>" . "<strong>Email:</strong> " . $useremail . "<br />" . "Image File: " . $image;

        $email = new Email($from, $to, $subject, $body);
        $email->replyTo($useremail);

        $email->send();
    }

    $return[] = array(
        "status" => $validatonStatus,
        "field" => $errorField,
        "message" => $errorList
    );

    return json_encode($return);
}
公共功能提交()
{
$fname=$this->getRequest()->postVar('firstname');
$lname=$this->getRequest()->postVar('lastname');
$useremail=$this->getRequest()->postVar('useremail');
$image=$this->getRequest()->postVar('image');
$errorField=“”;
$return=array();
如果(!filter\u var($useremail,filter\u VALIDATE\u EMAIL)){
$validationstatus=“错误”;
$errorField=“电子邮件”;
$errorList=“电子邮件格式不正确。请重新输入。”;
}/*如果$image无效,则为else,即大小或文件类型*/
否则{
$contestientry=新的contestientrysubmission();
$contestEntry->FirstName=$fname;
$contentry->LastName=$lname;
$contestEntry->EmailAddress=$useremail;
$ConferenceEntry->UploadeImage=$image;
$contentry->write();
$validationstatus=“成功”;
$errorField=“”;
$errorList=“”;
$fromsecret@secret.com';
$to=“[测试电子邮件地址]”;
$subject='参赛作品提交';
$body=“以下是参赛作品提交信息:”。“

”; $body.=“名字:”$fname.
姓氏:”$lname.
电子邮件:”$useremail.
““图像文件:”.$Image; $email=新邮件($from,$to,$subject,$body); $email->replyTo($useremail); $email->send(); } $return[]=数组( “状态”=>$ValidationStatus, “字段”=>$errorField, “消息”=>$errorList ); 返回json_encode($return); }
让我恼火的是,当图像到达上面显示的Page.php函数时,该如何处理它。通常,上面的设置在SilverStripe中运行良好,但现在添加了一个图像上载字段,我不知道要更改/添加/编辑什么来验证文件大小和类型。我发现的示例倾向于在页面模板类型中创建或使用上载字段,这不是我在这里要找的


任何建议都很好。我只是习惯于不在CMS中构建这些东西。我可能使这比需要的困难得多,因此…有什么建议吗

我的首要技巧是用PHP检查图像的MIME类型。这将检查实际的文件组成,以验证它实际上是一个图像,而不仅仅是一个已重命名为具有图像扩展名的随机文件

下面是一些您可以包含的示例代码

 // Check for valid upload
  if (($_FILES["picture"]["error"]) == "4") //no file detected
// error codes explained at http://php.net/manual/en/features.file-upload.errors.php
    {
        echo "<h3>No file has been detected. Please select a file to upload.</h3>";
        exit();
    }  


if ($_FILES['picture']['error'] == "1" || $_FILES['picture']['error'] == "2" || ($_FILES['picture']['size'] > 71680))  //define your max_file_size 71680 is 70KB - not very big
//file too big
    {
        echo("<h3>Upload unsuccessful: File exceeds maximum allowed size</h3>");
        echo("<p>Try compressing your photo or upload a different photo</p>");
        exit();
    }


//if file present and of acceptable size 
if ($_FILES['picture']['error'] != "1" && $_FILES['picture']['error'] != "2" && $_FILES['picture']['error'] != "4" && $_FILES['picture']['size'] < 71680) {
//then check to see if the type of file is an image file
//check for mimetype as at http://php.net/manual/en/features.file-upload.php    
    $fileinfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
     $fileinfo->file($_FILES['picture']['tmp_name']),
        array(
            'png' => 'image/png','gif' => 'image/gif','jpg' => 'image/jpeg',
        ),
        true
    )) 
    {
    echo('<h3>The file chosen is not an acceptable image file (.jpg/.png or .gif)</h3>');
    echo("Please upload a .jpg/.png or .gif image"); 
    exit();
    }

}
//检查上传是否有效
如果($_FILES[“picture”][“error”])==“4”)//未检测到任何文件
//错误代码已在中解释http://php.net/manual/en/features.file-upload.errors.php
{
echo“未检测到任何文件。请选择要上载的文件。”;
退出();
}  
如果($\u F
public function contestSubmission() {
  return Form::create(
    $this,
    __FUNCTION__,
    FieldList::create(
      TextField::create('firstname', 'First Name'),
      TextField::create('lastname', 'Last Name'),
      EmailField::create('useremail', 'Email'),
      FileField::create('image', 'Image')
    ),
    FieldList::create(
      FormAction::create('emailValidEntry', 'Submit Entry')
    ),
    RequiredFields::create(array('firstname', 'lastname', 'useremail', 'image'))
  );
} 
public function emailValidEntry($data, $form) {
  $contestEntry = ContestEntrySubmission::create();
  $form->saveInto($contestEntry);
  $contestEntry->write();

  $data['ImageEmail'] = base64_encode(file_get_contents($data['UploadedImage']['tmp_name']));

  Email::create(
    'from@address', //from
    'testing@address', //to
    'Contest Entry Submission' //subject
  )->setTemplate('ContestEntryEmail')
  ->populateTemplate(ArrayData::create($data))
  ->replyTo($data['EmailAddress'])
  ->attach($contestEntry->UploadedImage()->Filename)
  ->send();

  $form->setMessage('Thank you for your submission!', 'good');

  $this->redirectBack();
}
Below is the contest entry submission information: <br /><br />
<strong>First Name:</strong> $FirstName<br />
<strong>Last Name:</strong> $LastName<br />
<strong>Email:</strong> $EmailAddress<br />
<strong>Image File (see attached if not shown here):</strong><img src="$ImageEmail" alt="Submitted Image" />