0

I am trying to test if multiple files exist by the URL in PHP with a foreach loop.

For some reason i am only appending the last URL to the array and I cannot find out why.

It should print out like:

TEST.COM/sky.jpg exists.
TEST.COM/water.jpg doesnt exist
TEST.COM/trees.jpg exists.

But the last url only appends, which is trees.jpg.

Here is my code, I'm not too well at PHP. Maybe a little misunderstanding of the foreach function.

Where have I gone wrong?

$neg = 'doesnt exist';
$exists = 'exists.';
$file = $_POST['URL'];
$terms = array('sky.jpg','water.jpg','trees.jpg');
reset($terms);
$list = array();
foreach ($terms as &$i){
    $fullurl = $file.$i;
    $file_headers = @get_headers($fullurl);}
    if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
        array_push($list,$fullurl." ".$neg);}
    else {array_push($list,$fullurl." ".$exists);}
foreach ($list as &$x){echo $x;}
?>
  • your use of foreach is okay, but doesnt require the &. does TEST.com/water.jpg really exists? try printing out your $neg too. – David Chan Apr 04 '13 at 15:10
  • This might help: http://stackoverflow.com/questions/12781795/get-headers-inconsistency – Baba Apr 04 '13 at 15:12
  • Thanks baba, it seems this was also an underlying problem. –  Apr 04 '13 at 15:14
  • so are you saying get_headers is unreliable to check for a 404 page? –  Apr 04 '13 at 15:25

1 Answers1

0

The error lies in this line:

$file_headers = @get_headers($fullurl);}

Remove the trailing } and put it here:

else {array_push($list,$fullurl." ".$exists);}}

Otherwise, array_push only gets called once in total with the result of getting trees.jpg.

You might put closing braces on a line by themselves and correct the indentation for more code readability.

Marcellus
  • 1,277
  • 8
  • 7
  • Thankyou for that. I didn't even realise. –  Apr 04 '13 at 15:18
  • another problem. Its saying my .jpg exists when it doesnt. is this because get_headers() is unreliable? –  Apr 04 '13 at 15:32
  • I'd print out $file_headers[0] or even var_dump($file_headers) to check. I think not all browsers return the exact string 'HTTP/1.1 404 Not Found' when the file isn't found. – Marcellus Apr 04 '13 at 15:35
  • They differ, but this one is the same and it still gives an error. –  Apr 04 '13 at 15:52
  • Thats ok.I figured out what it was. i only had www not http://www. cheers for all your help. –  Apr 04 '13 at 16:16