2010-02-18 17 views
6

¿Cómo comprobar si un archivo existe en un servidor externo? Tengo una url "http://logs.com/logs/log.csv" y tengo una secuencia de comandos en otro servidor para comprobar si este archivo existe. ProbéCómo comprobar si existe un archivo en un servidor externo

$handle = fopen("http://logs.com/logs/log.csv","r"); 
if($handle === true){ 
return true; 
}else{ 
return false; 
} 

y

if(file_exists("http://logs.com/logs/log.csv")){ 
return true; 
}else{ 
return false; 
} 

Estos methos simplemente no funcionan

+1

tratar 'si ($ gestor)'. '$ handle' no será un booleano, por lo que no tiene sentido compararlo con uno. – Skilldrick

+0

Pregunta similar: http://stackoverflow.com/questions/2280394 – Gordon

Respuesta

1
<?php 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, 4file dir); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10); 

    $data = curl_exec($ch); 
    curl_close($ch); 

    preg_match_all("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches); //check for HTTP headers 

    $code = end($matches[1]); 

    if(!$data) 
    { 
     echo "file could not be found"; 
    } 
    else 
    { 
     if($code == 200) 
     { 
      echo "file found"; 
     } 
     elseif($code == 404) 
     { 
      echo "file not found"; 
     } 
    } 
    ?> 
+0

¿Hay alguna manera de obtener definitivamente los datos de las URL que pueden llamarse una vez cuando se comprueba que funcionan? – My1

3

Esto debería funcionar:

$contents = file_get_contents("http://logs.com/logs/log.csv"); 

if (strlen($contents)) 
{ 
    return true; // yes it does exist 
} 
else 
{ 
    return false; // oops 
} 

Nota: Esto supone que el archivo no está vacío

+1

¿Qué sucede si el archivo existe pero está vacío? – Skilldrick

+0

@Skilldrick: tienes razón, respuesta modificada. – Sarfraz

+0

Esto va a ser interesante si el archivo es bastante grande – eithed

8
function checkExternalFile($url) 
{ 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    curl_exec($ch); 
    $retCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 

    return $retCode; 
} 

$fileExists = checkExternalFile("http://example.com/your/url/here.jpg"); 

// $fileExists > 400 = not found 
// $fileExists = 200 = found. 
Cuestiones relacionadas