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"; }
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:
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 }
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: