title: PHP copy image from url to server and echo the final url
body: <p>I am trying to write a code that will copy an image from URL to a relative path on my server with a random file name and echo back the final url.
  I have 2 problems:</p>
  
  <ol>
  <li>It doesn't work with relative path. If I don't declare the path, the function works but the image is being saved on the same folder of the PHP file. If I do specify the folder, it doesn't return any error but I don't see the image on my server.</li>
  <li>The echo function always return an empty string.</li>
  </ol>
  
  <p>I am a client side programer so PHP is not my thing... I would appreciate any help.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>&lt;?php
  
  $url = $_POST['url'];
  $dir = 'facebook/';
  $newUrl;
  
  copy($url, $dir . get_file_name($url));
  
  echo $dir . $newUrl;
  
  function get_file_name($copyurl) {
      $ext = pathinfo($copyurl, PATHINFO_EXTENSION);
      $newName = substr(md5(rand()), 0, 10) . '.' . $ext;
      $newUrl = $newName;
      return $newName;
  }
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Here is the fixed code if anyone is interested:</p>
  
  <pre><code>&lt;?php
  
  $url = $_POST['url'];
  $dir = 'facebook/';
  $newUrl = "";
  
  $newUrl = $dir . generate_file_name($url);
  
  $content = file_get_contents($url);
  $fp = fopen($newUrl, "w");
  fwrite($fp, $content);
  fclose($fp);
  
  echo $newUrl;
  
  function generate_file_name($copyurl) {
      $ext = pathinfo($copyurl, PATHINFO_EXTENSION);
      $newName = substr(md5(rand()), 0, 10) . '.' . $ext;
      return $newName;
  }
  </code></pre>