Search code examples
phpfopenfile-handling

Unable to open file while writing php file


I am trying to use fopen and fwrite

$book="http://bittotb.com/synthesis_study_material/student_admin/include/uploaded/epub/923960_hotel (1).epub";
$path=$book.".php";
$myfile =fopen($path, "w");
$txt = "<?php include('hello.php'); ?>";
fwrite($myfile, $txt);
fclose($myfile);

when I just write the file name in fopen like

$myfile =fopen("abc.php", "w");

then it's making a file in the same directory but I want to make that file in another directory. while using path it's not working if I echo the $path then I am getting

http://bittotb.com/synthesis_study_material/student_admin/include/uploaded/epub/923960_hotel (1).epub.php

this is correct file name and path but still, it's giving me Unable to open the file and my folder permission shows 0777


Solution

  • You have to use path on the server, not the URL of page.

    For example, you page can have URL http://example.org/index.php. The file can be on the server known as /var/www/example.org/index.php.

    Use this code to determine your directory:

    <?php
    echo getcwd();
    

    If the code above shows /var/www/example.org/, file http://example.org/test.php has file path /var/www/example.org/test.php. But it is better to use relative paths. (see below)


    If you have page http://example.org/index.php and you want create http://example.org/test.php, use this:

    $file = fopen("test.php", "w");
    fwrite($file, "<?php echo 'Hello World'; ?>");
    fflush($file);
    fclose($file);
    

    If you want to write to file http://bittotb.com/synthesis_study_material/student_admin/include/uploaded/epub/file.php from script http://bittotb.com/synthesis_study_material/student_admin/module/corses/file.php, use relative path:

    $file = fopen("../../include/uploaded/epub/file.php", "w");
    // ...