I am trying to POST data to my database in Unity and it doesn't seem to be working. I know it is probably a very stupid mistake as I do have little knowledge in this field.
The C# script I have:
void logIn(string test) {
WWWForm form = new WWWForm();
form.AddField("action","send");
form.AddField("var1",test);
string url = "http://www.prizechief.com/unitycon.php";
WWW w = new WWW(url, form);
}
void Start() {
string sample = "Works";
logIn(sample);
}
My PHP code
<?php
$con = #mysqli_connect("server","un","pass", "db") or die("Could not connect " . mysqli_connect_error() . "Please try again later.");
$var1 = $_GET['var1'];
echo $var1;
mysqli_Query($con,"INSERT INTO test (var) VALUE ('$var1')");
?>
Also, a hint on how to use GET to receive information would be greatly appreciated!
Try this. That should do the WWW request and set $_GET['var1'] = to value1 in your PHP script. Now of course you will have to change that to your variable down the road. But just to test for now. If this doesn't work let me know what the debug logs print out.
void Start () {
string url = "http://www.prizechief.com/unitycon.php?var1=value1";
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
EDIT
Remember to go into Edit > Player Settings > Editor and change the URL to your domain.
Related
I want to allow the user to use a local image from his machine and upload it to the server.
What I did is use UnityWebRequest in-game, load the image, send it to a PHP file on the server, and wait for the reply to remember the URL where the file si saved(to save it in Playfab later).
This is the code I made so far:
private readonly string setAvatarUrl = "http://myurl.com/setavatar.php";
private readonly string playerIdField = "playfabid";
private readonly string imageField = "img_avatar";
public IEnumerator SaveImageToDB(Texture2D image)
{
byte[] bytes = image.EncodeToPNG();
WWWForm form = new WWWForm();
form.AddField(playerIdField, player.playerId);
form.AddBinaryData(imageField, bytes, "avatar.png", "image/png");
UnityWebRequest www = new UnityWebRequest();
www = UnityWebRequest.Post(setAvatarUrl, form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
}
else
{
string jsonFromDB = www.downloadHandler.text; // Return empty string
string imageUrl = JsonUtility.FromJson<string>(jsonFromDB);
Debug.Log($"JSON returned: {jsonFromDB}");
if (!string.IsNullOrEmpty(imageUrl))
{
// Save the url
}
Debug.Log("Image upload complete!");
}
}
And this is the PHP file:
<?php
ini_set('display_errors',1);
$idplayfab = $_POST['playfabid'];
$path = 'avatar/'.$idplayfab;
if(file_exists($path)) {
//dir exist
$files = glob($path.'/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
} else {
//not exist
mkdir($path);
}
$uploadfile = $path ."/". basename($_FILES['img_avatar']['name']);
if (move_uploaded_file($_FILES['img_avatar']['tmp_name'], $uploadfile)) {
$array = array('result' => 'ok', 'url' => 'http://myurl.com/'.$uploadfile);
$json = json_encode($array);
return $json;
} else {
$array = array('result' => 'ko');
$json = json_encode($array);
return $json;
}
?>
The image is saved on the server but the problem is when I try to get the JSON to get the URL, the string is empty and I don't understand why.
I tried tons of solutions like this one or this one but I cannot figure it out.
I also tried to use the deprecated WWW instead, but still, it doesn't work.
I'm kinda new to PHP so maybe it could be the PHP part the problem I believe.
Not an PHP expert but:
Afaik return is only used to evaluate certain functions e.g. for success or in order to further handle the result of something before responding to the client on server side.
What you want to do is rather sending your content as the http result to the client
=> You should rather use echo or print which is used to generate the http output.
I'm familiar with Unity but new to trying to communicate with servers. I'm trying to set up a login screen but I'm having troubling Posting to the server properly. The strange part is the Get is working fine, but the Post turns up the following Error :
Cannot connect to destination host Network
UnityEngine.Debug:Log(Object)
LoginHandler:CheckForNetworkErrors(UnityWebRequest) (at
Assets/Scripts/LoginHandler.cs:120)
<LoginUser>c__Iterator2:MoveNext() (at Assets/Scripts/LoginHandler.cs:92)
.UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
I'm using a test URL to make sure it was't an issue with the original. Both return the same error. The following code is sent once the player hits a login button. Any ideas on what im doing wrong here?
public IEnumerator LoginUser()
{
string testURL = "https://www.google.com/";
using (UnityWebRequest get = UnityWebRequest.Get(testURL))
{
yield return get.Send();
ParseCSRF(get.downloadHandler.text);
CheckForNetworkErrors(get);
}
WWWForm form = new WWWForm();
form.AddField("username", username.text);
form.AddField("password", password.text);
form.AddField("_csrf", csrf);
using (UnityWebRequest post = UnityWebRequest.Post(WWW.EscapeURL(testURL), form))
{
yield return post.SendWebRequest();
CheckForNetworkErrors(post);
}
}
public void CheckForNetworkErrors(UnityWebRequest www)
{
if(www.isNetworkError)
{
Debug.Log(www.error + " Network");
}
else if (www.isHttpError)
{
Debug.Log(www.error + " http");
}
else
{
Debug.Log("Form upload complete!" + www.downloadHandler.text);
}
}
I have tested with the code I wrote below:
void Start()
{
StartCoroutine(GetCrt());
}
IEnumerator GetCrt()
{
string testURL = "https://www.google.com/";
using (UnityWebRequest www = UnityWebRequest.Get(testURL))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Get Request Completed!");
}
}
}
It's working fine.
For the post request you need a real form data, you can't send a post request to google.com.
Hope this help you.
Happy Coding!
I'm getting the following exception when I build my game for android
WWW download had an error: java.lang.IllegalArgumentException: uri ==
null
Now I haven o idea why this is happening because it works fine in the editor. Here is the relevant code :
assetLoader.BundleURL = "ftp://user:pass#81.161.248.122/Unity-Uri/AssetBundles/seasonalcontent/christmas";
assetLoader.version = 1;
assetLoader.StartDownload();
and the actual download code :
IEnumerator DownloadAndCache()
{
// Wait for the Caching system to be ready
while (!Caching.ready)
yield return null;
// Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version))
{
yield return www;
if (www.error != null)
throw new Exception("WWW download had an error:" + www.error);
AssetBundle bundle = www.assetBundle;
SeasonManager.assets = bundle.LoadAllAssets();
Debug.Log("Stop");
OnContentLoaded();
} // memory is freed from the web stream (www.Dispose() gets called implicitly)
}
Edit: I got this from the documentation : ftp:// protocol support is limited to anonymous downloads only. Is ftp not supported on android ?
Edit 2: As suggest in the comments I tried this and it results in a Login failed error :
IEnumerator makeRequest()
{
string authorization = authenticate("username", "pass");
string url = "ftp://ipgoeshere";
UnityWebRequest www = UnityWebRequest.Get(url);
www.SetRequestHeader("AUTHORIZATION", authorization);
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;
SeasonManager.assets = bundle.LoadAllAssets();
}
}
string authenticate(string username, string password)
{
string auth = username + ":" + password;
auth = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
auth = "Basic " + auth;
return auth;
}
To clarify I've made sure that the username password and the server address are correct. I have simply removed them from the code here for obvious reasons.
Hi I am making a game in unity and I need to post information to my python flask server I think that the best method is to use the WWWForms in Unity C# but I can't seem to make it post. Here is my C# Unity Code:
IEnumerator Upload() {
WWWForm form = new WWWForm();
form.AddField("Username", "Stan");
form.AddField("Password", "123456");
using(UnityWebRequest www = UnityWebRequest.Post("http://myserver.com/newuser/", form)) {
yield return www.Send();
if(www.isError) {
Debug.Log(www.error);
}
else {
Debug.Log("Form upload complete!");
}
}
}
It alsways says "From upload complete" and I don't get any errors but when I check my SQL Database it hasn't received the information.
I am pretty sure that my server side code is right because I can post successfully to it through the Form but here is the code anyway:
Python Flask:
class Users(db.Model):
__tablename__ = "userstable"
userid = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(4096))
password = db.Column(db.String(4096))
#app.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
#app.route("/newuser", methods=["GET", "POST"])
def NewUser():
if request.method == "GET":
return render_template("NewUser.html")
new_user = Users(username=request.form["Username"], password=request.form["Password"])
db.session.add(new_user)
db.session.commit()
return redirect(url_for('NewUser'))
Please Help, and if possible it would be nice to know how to do get requests as well, Thanks!
Stan.
I have a website and I want to use it as a place where I can store data (like username, password etc.) for my multiplayer game that I'm making in Unity3D.
Now I want to register someone (add the username and password to the MySQL database) using C# and Unity3D. I use the WWW class to communicate to the website. In my point of view the code I made in Unity3D is working fine, but when I visit phpMyAdmin and search for the new registered user, I can't find it. So I figured, the problem must be in the PHP script, but I can't find it.
Once again the problem is that the username and the password are not added to the MySQL table.
I'll post both scripts, although I think the script in Unity3D is working OK. Please note that I'm PHP absolute beginner.
<?php
$mysql_host = "example.host.com";
$mysql_database = "example_database";
$mysql_user = "exampleuser";
$mysql_password = "toomanysecrets";
try
{
$toQuery = 'SELECT name,
password
FROM basicUserInfo
ORDER BY name';
if ($_POST["name"] || $_POST["password"])
{
$conn = new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
echo "Connected to $mysql_database at $mysql_host successfully!";
$forQuery = 'INSERT INTO `a1936371_userinf`.`basicUserInfo` (
`name` ,`password`
)
VALUES (
\'$_POST[\'name\']\', \'$_POST[\'password\']\'
)';
if (!$conn->query($forQuery))
{
echo "Failed to add data!";
}
else
{
echo "Added data sucessfully";
}
//Close the connection
$conn = null;
}
} catch (PDOException $pe)
{
die("Could not connect to the database $mysql_database:" . $pe->getMessage());
}
Unity3D:
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
Register("testt", "test1");
}
}
public void Register(string playername, string password)
{
StartCoroutine(RegisterOnServer(playername, password));
}
IEnumerator RegisterOnServer(string playerName, string password)
{
string url = "http://deathrunserv.net16.net/index.php";
WWWForm form = new WWWForm();
form.AddField("name", playerName);
form.AddField("password", password);
WWW www = new WWW(url);
yield return www;
Debug.Log("Done!");
}
In your C# code, you're not using WWWForm anywhere. Try:
WWWForm form = new WWWForm();
form.AddField("name", playerName);
form.AddField("password", password);
WWW www = new WWW(url, form);
yield return www;
Debug.Log("Done!");