title: Copy a file and create a directory if it doesn't exist in PHP
body: <p>I need simple PHP code to copy a file and create the directory if it doesn't exist (PHP).</p>
  <p>Example:</p>
  <pre><code>$f1 = &quot;x.txt&quot;;
  $f2 = &quot;a/b.txt&quot;;
  mycopy($f1, $f2);
  </code></pre>
  <p>My copy should make sure the folder exists (i.e., create it if necessary) and copy the file.</p>
  <p>My attempt:</p>
  <pre><code>function mycopy($s1, $s2) {
      $path = pathinfo($s2);
      if (!file_exists($path['dirname'])) {
          mkdir($path['dirname'], 0777, true);
      }
      if (!copy($s1, $s2)) {
          echo &quot;copy failed \n&quot;;
      }
  }
  </code></pre>