我有这段代码:
$allowed_extension = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$errors = array();
$output = array();
if(!empty($_FILES['image']['tmp_name'])){
foreach($_FILES['image']['name'] as $key => $array_value){
if(!in_array(pathinfo($_FILES['image']['name'][$key], PATHINFO_EXTENSION), $allowed_extension)){
die("Die!");
}
}
foreach($_FILES['image']['name'] as $key => $array_value){
$file_name = $_FILES['image']['name'][$key];
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
if (!in_array($file_extension, $allowed_extension)){
$errors[$file_name][] = "format $file_extension in image $file_name is not accepted";
continue;
}
if ($file_size > 2097152){
$errors[$file_name][] = "maxsize of 2MB on $file_name has reached";
}
if (count($errors) == 0){
$dir = "a/b/c";
if (is_dir($dir)){
mkdir("a/b/c/tmp_images", 0755);
}else{
mkdir("a/b/c", 0755);
mkdir("a/b/c/tmp_images", 0755);
}
$path = "a/b/c/tmp_images";
$prifix = basename($file_name, "." . $file_extension);
//var_dump ($prifix);
$uploadfile = $path . "/" . $file_name;
$x = 0;
while (file_exists($uploadfile)){
$x ++;
$uploadfile = "{$path}/{$prifix}-{$x}.{$file_extension}";
}
if (move_uploaded_file($file_tmp, $uploadfile)){
$file_name = basename($uploadfile);
$output [$file_name] = "OK";
}else{
$output[$file_name] = "Failure while Uploading!";
$errors[$file_name][] = "Failure: Can't move uploaded pictures!";
}//else...
}//if(count($errors))...
}//foreach($_FILES['image']['name']...
}//if(!empty($_FILES['image']['tmp_name'])...
我的问题是,我不知道如何显示应该显示的错误消息,当数组
$errors
给出。到目前为止,它只会显示:
array
而不是:
maxsize of 2MB on abc.jpg has reached
在html中我有这段代码:
<?php if(isset($errors)):?>
<div class="form-error-message" id="signup-error-message" style="display": none;">
<div class="arrow-wrapper">
<div class="border-wrapper">
<?php foreach($errors as $error):?>
<p class="layer-content">
<?php echo $error;?>
</p>
<?php endforeach;?>
</div>
</div>
</div>
如果有人可以友好并帮助我,我真的很感激。非常感谢。
答案 0 :(得分:9)
也许保存每个错误:
$errors = array();
$errors[] = $file_name . ": this is the error message.";
并显示如下:
if(count($errors) > 0){
foreach($errors as $e){
echo $e . "<br />";
}
}
答案 1 :(得分:3)
你必须print_r
一个数组,而不是echo
它:
print_r($errors);
或者,您可以单独显示每个错误,如下所示:
foreach( $errors as $innerErrors )
{
foreach( $innerErrors as $anError )
{
echo $anError ."\n";
}
}
答案 2 :(得分:3)
怎么样?
echo implode(', ', $errors[$filename]);
答案 3 :(得分:3)
您已将$errors
写为二维数组:
$errors[$file_name][] = 'your message';
因此要正确显示它,请使用两个foreach
而不是一个:
<?php foreach($errors as $errorsOnFile):?>
<?php foreach($errorsOnFile as $error):?>
<p class="layer-content">
<?php echo $error;?>
</p>
<?php endforeach;?>
<?php endforeach;?>
答案 4 :(得分:2)
你不能只回显一个数组。但是,您可以循环遍历数组的元素。
foreach($errors[file_name] as $error_message) {
echo $error_message."<br>";
}
此代码一次回答错误。