views:

53

answers:

1

Hi Everyone,

http://en.wikipedia.org/wiki/Special_Folders

I am having a problem with accessing a special folder in a fopen stream in php.

Example

$fp = fopen("%USERPROFILE%/Desktop/text.txt", 'wb');
fwrite($fp, $data);
fclose($fp);

I try this with sysinternals process monitor running to try and see what is actually happening and it looks something like this.

C:/xampp/htdocs/test/%USERPROFILE%/Desktop/text.txt  PATH NOT FOUND

Well apparently two thing are going wrong, PHP is treating the path as a relative path and the special folder is not being evaluated.

+2  A: 
$fp = fopen("{$_ENV['USERPROFILE']}\\Desktop\\text.txt", 'wb');

See $_ENV on the manual and also getenv().

As Johannes Rössel said, this will only work in limited circumstances. You can use this internal function instead:

#include<Shlobj.h>

PHP_FUNCTION(win_get_desktop_folder)
{
    char szPath[MAX_PATH];

    if (zend_parse_parameters_none() == FAILURE)
        RETURN_NULL();

    if (SUCCEEDED(SHGetSpecialFolderPathA(NULL, szPath,
        CSIDL_DESKTOP, FALSE))) {
        RETURN_STRING(szPath, 1);
    } else {
        RETURN_FALSE;
    }
}
Artefacto
And it still would be partially wrong since it's not guaranteed that the Desktop folder is located there :-). Though I have no idea whether you can call [SHGetKnownFolderPath](http://msdn.microsoft.com/en-us/library/bb762188.aspx) from PHP somehow.
Joey
@Johan Right... I guess, he'll need to write an extension.
Artefacto
ok $_env['USERPROFILE'] works. But what about the %temp% equivalent? $_env['TEMP'] and $_env['TMP'] are equal to C:\Windows\TEMP while %temp% is equal to C:\Users\Admin\AppData\Local\Temp
Neddy
@Needy That's probably because you're running PHP under an Apache process running as the system account, for each the temp directory is another one.
Artefacto