如何在此方案中使用“If empty”或“if(isset)”

时间:2013-05-29 15:53:56

标签: php url if-statement

在我的网站中,我允许我的用户上传头像。以下代码用于打印URL:

$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);

这将为我们提供示例/wp-content/uploads/userphoto/2.thumbnail.png

问题是,如果用户尚未上传头像,则该URL当然为/wp-content/uploads/userphoto/。所以这将是一个破碎的形象。

我想为没有头像的用户显示自定义图片,例如no-image.png。我是猜测这是通过在那里添加if (isset)语句来完成的吗?我似乎无法弄清楚如何解决这个问题。

5 个答案:

答案 0 :(得分:3)

您可以使用empty

$image_id = get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . (empty($image_id) ? 'no-image.png' : $image_id);

答案 1 :(得分:0)

这样的事情应该有效,具体取决于get_user_meta实际上是否返回Null。

if (is_null(get_user_meta($user_info->ID, 'userphoto_thumb_file', true))) {
    $r = $r . $photoUrl = '/wp-content/uploads/userphoto/customimage.png';
} else {
    $r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
}

答案 2 :(得分:0)

你可以做到

if(!empty(get_user_meta($user_info->ID, 'userphoto_thumb_file', true)))
{
    $r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
}
else
{
        $r = $r . $photoUrl = '/wp-content/uploads/userphoto/no-image.png';   
}

答案 3 :(得分:0)

您应该测试该文件是否存在:

if(!file_exists( $_SERVER['DOCUMENT_ROOT'] . $r))  { 
   $r = '/path/to/default/image.jpg';
}

使用这种方法,即使用户上传了头像,但由于某种原因图像不在服务器上,它也会显示默认头像。

答案 4 :(得分:0)

实际上,您可以检查函数是否返回评估为false的内容。空字符串在php中评估为false

$img = get_user_meta($user_info->ID, 'userphoto_thumb_file', true);

if(!$img) {
    $img = 'no-image.png';
}

$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . $img;