WordPress fopen getting directory link

I’m using fwrite to create an html file in a folder within my plugin. The following code now allows me to write to the folder, but the link it tries to open is the full system path.

function buildFrameFile($html, $filename){
    $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
    $filename= $DOCUMENT_ROOT. '/wp-content/plugins/my-plugin/html/' . $filename . ".html";
 $fh = fopen($filename, 'a');//open file and create if does not exist
 fwrite($fh, $html);//write data
 fclose($fh);//close file

 return $filename;
 }

The path it now opens is:

Read More
/var/chroot/home/content/##/########/html/wp-content/plugins/my-plugin/html/79dda339bad8e65c425e580d62f41fa1.html

I need it to open from here:

/wp-content/plugins/my-plugin/html/79dda339bad8e65c425e580d62f41fa1.html

I’m not sure how to go about this.

Related posts

Leave a Reply

3 comments

  1. I solved my problem. I ended up changing the code from:

    function buildFrameFile($html, $filename){
        $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
        $filename= $DOCUMENT_ROOT. '/wp-content/plugins/my-plugin/html/' . $filename . ".html";
     $fh = fopen($filename, 'a');//open file and create if does not exist
     fwrite($fh, $html);//write data
     fclose($fh);//close file
    
     return $filename;
     }
    

    To:

        function buildFrameFile($html, $filename){
        $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
        $filename2= $DOCUMENT_ROOT. '/wp-content/plugins/my-plugin/html/' . $filename . ".html";
     $fh = fopen($filename2, 'a');//open file and create if does not exist
     fwrite($fh, $html);//write data
     fclose($fh);//close file
    
     return $filename;
     }
    

    This way the file gets saved to the folder and only returns the actual name of the file not the whole link to the file.

    Then in my header I changed the code from:

    header("Location: /confirm" . $nvp_str . "&filename=" . $filename);
    

    To:

    header("Location: /confirm?" . $nvp_str . "&filename=" . '/wp-content/plugins/my-plugin/html/' . $filename . ".html");
    

    and the iframe in my page calls the value of &filename which then returns the proper link to my file created and it loads perfectly!

  2. First of all, you can rely on WordPress’ defines (or functions) to determinate the paths without any dirty hacks:

    Then again you can check things using PHP functions like file_exists(), is_dir(), is_writable():

    To avoid complex fopen, fwrite, fclose handlers, you can go for file_put_contents() function there too. Either in appending or overwriting mode:

    Not sure how relevant, but keep in mind if this is written by the webserver, you need to make sure the directory has write permissions there. Easiest way would be chmod 777 directory from shell, or SITE CHMOD 777 directory from FTP.