Output of wget command when executed using shell_exec()

Discussion in 'PHP' started by abhishek198, May 31, 2010.

  1. #1
    Am using the following statements to fetch an image from a remote location from a PHP script .. however even if the image gets successfully downloaded .. it always goes to the else condition .. any clue what is it that am doing wrong ..

    $url = "http://mydomain.com/images/temp.jpg";

    $command = "wget $url -nv -O /home/abhishek/temp/".basename($url);

    if(shell_exec($command)){
    echo "success";
    }else{
    echo "fail";
    }
     
    abhishek198, May 31, 2010 IP
  2. Qc4

    Qc4 Peon

    Messages:
    44
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    On UNIX-like operating systems, no output generally means that the command was successful (unless you were expecting something to be returned like cat or ls). Since PHP considers an empty string to be false, you should actually switch those echo statements, or write it like this:

    $output = shell_exec($command);
    if (!$output) {
      echo "success";
    } else {
     echo "fail: " . $output;
    }
    PHP:
     
    Last edited: May 31, 2010
    Qc4, May 31, 2010 IP
  3. adamsinfo

    adamsinfo Greenhorn

    Messages:
    60
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    18
    #3
    Why not use php-curl instead.

    Anyway, you don't want to check for the output in your if() condition, you want to check for the shell return code of $command instead.

    Use proc_open and proc_close instead of shell_exec (http://php.net/manual/en/function.proc-open.php) and then check for the return code of proc_close. wget like most functions returns 1 on failure and 0 on success.

    $return_code = pclose($handle);
    if ($return_code)
    {
    //failed
    } else {
    //succeed
    }
     
    Last edited: May 31, 2010
    adamsinfo, May 31, 2010 IP
  4. abhishek198

    abhishek198 Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Hi,
    Thanks for the reply ..

    I tried curl and it worked perfectly fine ..

    
    $img = "http://yourdomain.com/temp.jpg";
            $fullpath = basename($img);
    
            $ch = curl_init ($img);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
            $rawdata=curl_exec($ch);
            if(strpos($rawdata,"Not Found") === false) {
                if(file_exists($fullpath)) {
                    unlink($fullpath);
                }
                $fp = fopen($fullpath,'x');
                fwrite($fp, $rawdata);
                fclose($fp);
                echo "success";
    
            }else {
                echo "fail";
            }
            curl_close ($ch);
    
    PHP:
     
    abhishek198, May 31, 2010 IP