Use PostAsync to post to a PHP file that appends data

Hello, I’m writing a script that sends data to a Website which should append data to a JSON File.

In the script I got:

local postdomain = "domainhere/file.php"
local sendtable = {
	["placeid"] = "15";
}
local send = HttpService:JSONEncode(sendtable)

print(send)
local res = HttpService:PostAsync(postdomain,send)
print(res)

In the PHP File I’ve got:

<?php  
 $message = '';  
 $error = '';  
 if(isset($_POST))  
 {  
      if(empty($_POST["placeid"]))  
      {  
           $error = "<label class='text-danger'>Place ID missing!</label>";  
      }  
      else  
      {  
           if(file_exists('licenses.json'))  
           {  
                $current_data = file_get_contents('licenses.json');  
                $array_data = json_decode($current_data, true);  
                $extra = array(  
                     'placeid'               =>     $_POST['placeid'],
                );  
                $array_data[] = $extra;  
                $final_data = json_encode($array_data);  
                if(file_put_contents('licenses.json', $final_data))  
                {  
                     $message = "<label class='text-success'>Successfully gave the place a license!</p>";  
                }  
           }  
           else  
           {  
                $error = 'JSON File does not exist!';  
           }  
      }  
 }  
 ?>  

It only returns the website, and didn’t append it to the data.

POST requests aren’t meant for retrieving data from a server, which is probably why res isn’t returning anything. You should use a GET request if you want to do that. As for it not appending, this depends on your server setup but it is probably because many configurations have file_puts_contents and similar functions disabled by default as they’re not secure. If you want to store and manipulate data, you should set up a MySQL database. Also, you may want to check your web server error logs to see if you can find additional info in there.

1 Like

I don’t want to retrieve data, I want to send data.

try passing the placeid through the url.
lua:

game:GetService("HttpService"):GetAsync("domain/file.php?placeid="..game.PlaceId)

php:

$key = $_GET("placeid");
if isset($key){
    // Do stuff here
}

Edit: If you have issues with appending let me know.

In your Lua code, you are JSON Encoding the Data. A PHP Server cannot handle incoming JSON data, instead, it needs a URL Encoded Query:

local sendtable = {
	["placeid"] = "15";
}

local data = ""
for k, v in pairs(sendtable) do
	data = data .. ("&%s=%s"):format(
		HttpService:UrlEncode(k),
		HttpService:UrlEncode(v)
	)
end
data = data:sub(2)

local response = HttpService:PostAsync(postdomain , data, Enum.HttpContentType.ApplicationUrlEncoded, false)

Thanks for the help & time writing the response! It has helped me and works now.

1 Like