How to redirect to other image If the URL is not valid?

时间:2017-12-18 07:07:46

标签: php

I need the code to check if the URL is valid or not,

And if not, to refer the URL to another image URL.

<?php
$url = "https://scontent.ftlv2-1.fna.fbcdn.net/v/t1.0-0/p240x240/12140762_1159067420823544_4471328164031495581_n.jpg";
header('Location: $url);

Backup Image:

http://www.qygjxz.com/data/out/114/5095827-image.jpg

3 个答案:

答案 0 :(得分:1)

you have image path then you should check image like this. for more details about file_exists read PHP Manual

also i mention that error in header function missing quotes. i fixed this error

if(file_exists('https://scontent.ftlv2-1.fna.fbcdn.net/v/t1.0-0/p240x240/12140762_1159067420823544_4471328164031495581_n.jpg')) {
    header('Location: '.$url);
    }else{
      .........
    }

答案 1 :(得分:0)

Did you use this snippet?

<?php 
    if(isset($url) && filter_var($url, FILTER_VALIDATE_URL)){
      //show image
    }else{
       // header($other url); //redirect back
    }
 ?>

答案 2 :(得分:0)

It seems like your are checking image exist or not! you can use getimagesize.

Example:

$url = "https://scontent.ftlv2-1.fna.fbcdn.net/v/t1.0-0/p240x240/12140762_1159067420823544_4471328164031495581_n.jpg";
$url2 = "http://www.qygjxz.com/data/out/114/5095827-image.jpg"
if (@getimagesize($url)) {
   header('Location:'. $url);
} else {
  header('Location:'. $url2);
}