Unable to create text file through PHP script

<?php
    if(isset($_GET["server_url"]))
    {
    	file_put_contents("server.txt", $_GET["server_url"]);
    }
?>

I have tried other solutions on the forums and nothing seems to work. Any help would be appreciated.

What error are you getting? Enable error logs in the control panel if you have not already.

4 Likes

Thats the problem there aren’t any errors

You’re probably already aware of this, but server_url isn’t something that’s set automatically most the time (not on any of my php environments anyway, never tried on InfinityFree).

If you’re using this in the body of a page, then you’d need to set it either as a variable or through the url https://example.com/?server_url=hello

or in an environment variable
$_SERVER['REQUEST_URI']
or $_SERVER['HTTP_HOST']
or $server_url = "https://my-fixed-server.com";

or set via a form

<form method="get">
    <input name="server_url" placeholder="Enter server URL">
    <button>Save</button>
</form>

If one of these options isn’t done that the script won’t do anything because “server_url” isn’t set.

6 Likes

Even when piping in the variable manually through the browser it doesn’t work which has got me totally baffled to be honest with you because everything I’ve looked up says it should be working.

Potentially a really stupid idea… because I really don’t think this should make a difference, maybe try changing server.txt to ./server.txt

I dont think its required, but it will force the the script to save the file right next to the script so guarantees that there wont be any permission issues

4 Likes

The code seems dead simple so I don’t understand why it doesn’t work.

Still, despite it only being effectively one line, you can still debug it. You could add print statements to determine if the condition is matched, what the detected value is, what the output is of the file_put_contents function (it returns false if it couldn’t write the data and a number of bytes that it read if successful), maybe the output of realpath("server.txt") to verify where exactly this file is stored, or maybe read the file after writing to see if that all works.

That’s a lot of debugging for a very small piece of code so I hope you won’t need most of it. But you can still dig down and figure out what exactly is going on.

5 Likes

This fixed it why it didn’t work beforehand I have no idea

My guess, is that like in Linux, just saving to “server.txt” is trying to put it in the root of your account, and doesn’t have access. by putting ./ on the beginning it forced it into the current directory that the script is called from.

this is purely a guess though, because I agree that the original script should have worked.

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.