'PHP Script Won't Create File on XAMPP

I am trying to get a PHP script to take input from an html form to create a csv file. My PHP script is below:

<?php
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $email = $_POST['email'];
    $row = [$fname, $lname, $email];
    $file = fopen("mini4.csv", 'w');
    for ($i=0; $i<3; $i++){
        fwrite($file, $row[$i]);
        if($i!=2){
            fwrite($file, ", ");
        }
    }
    fclose($file);
    $file = fopen("mini4.csv", "r");
    $data = fgetcsv($file);
    echo file_get_contents( "data.csv" );
    fclose($file);
    ?>

My PHP file has the following permissions : -rw-r--r--. The directory the PHP file is held in has the following permissions: drwxr-xr-x.

From everything I've read, issues like this are due to permissions, although, looking at other posts my permissions on the PHP file and directory above it are correct.

I saw some answers suggesting chmod -R 777 to the directory, but I am worried about potential security issues this might cause.

When I look at the access log on XAMPP, i see the following:

::1 - - [27/Feb/2022:17:23:14 -0500] "POST /mini4/mini4.php HTTP/1.1" 500 -

I turned on screen reporting and I am getting this:

Warning: fopen(mini4.csv): Failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/mini4/mini4.php on line 12.

Although, I do not see how this can be given the permissions my file and directory have.



Solution 1:[1]

The permissions assigned to your PHP file are irrelevant. The permissions assigned to the folder your PHP script is trying to write to are important because they must grant read/write access to the user that Apache is using. Typically, that's the user/group apache:apache and that's different from the user you'll be logged in as.

Mostly it's enough to chmod g+rw <myFolder>, but this depends on the existing setup.

FWIW, your code is inordinately convoluted. You could just do this:

$file = fopen("mini4.csv", 'w');
fputcsv($file, [$_POST['fname'], $_POST['lname'], $_POST['email']]);
fclose($file);
readfile("mini4.csv");

Be aware that this need additional validation before using it in anger.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tangentially Perpendicular