最近在学习PHP,因为是新手,所以选了一本《Head First PHP & MySQL》但是在第七章的部分却遇到了一个文件上传报错,截图如下:
,我回到了源码D:\www\...\editprofile.php中查看,发现60行附近的代码是这样的
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
//60 if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
// The new picture file move was successful, now make sure any old picture is deleted
if (!empty($old_picture) && ($old_picture != $new_picture)) {
@unlink(MM_UPLOADPATH . $old_picture);
}
}
进源代码查看,正是$_FILES['file']['error'] == 0这句话报了错,网上有人说是php.ini文件的配置出了问题,可是我检查我的文件并没有发现任何问题,于是我就检查了下代码,这段代码的意思就是判断图片上传格式大小是否正确,如果正确并且上传无误,就把上传的图片从临时位置移动到特定的目标位置并保存,并且删除临时位置的图片。而报错也是说索引未定义(Undefined index:)但是文件上传成功,所以不是配置问题,发现原来是索引名称用了一个示例的'file',而没有使用上传的图片的名称‘new_picture’,所以才有了上面的报错,修改代码为:
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
//60 if ($_FILES['new_picture']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
// The new picture file move was successful, now make sure any old picture is deleted
if (!empty($old_picture) && ($old_picture != $new_picture)) {
@unlink(MM_UPLOADPATH . $old_picture);
}
}
else {
// The new picture file move failed, so delete the temporary file and set the error flag
@unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
}
}
}
else {
// The new picture file is not valid, so delete the temporary file and set the error flag
@unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
}
}
修改之后再次刷新尝试:
哈!报错消失了,呱唧呱唧。
第一次写博客,还不是很有经验,希望能帮到大家,如果写的不好,也请大家多多指正,我一定努力去改,嗯嗯,就这些。