B4J Question Poststring with PHP session variables

ThRuST

Well-Known Member
Licensed User
Longtime User
Original Post
Hi all!
I'm trying to set a PHP $_SESSION["test"] variable by using Poststring from B4J, and then view the session on the webpage.
However the session remains empty. It is not set, even though the log displays the string in B4J.
To sum this up, the string Hello B4X! is sent to the php webpage set.php to set a session variable. At success I open the webpage from B4J to view the changes online (in this case the session variable remains to be empty as it is never set).
Somehow jOkhttpUtils2 v2.96 Poststring don't set the session variable. Any ideas for a solution to this?

Here's my example code

B4X:
Sub SendPostRequest

    Dim sendjob1 As HttpJob
    Dim var1 As String = "Hello B4X!"
       Dim response As String

    ' Init okHttpUtils2
    sendjob1.Initialize("", Me)

    'Send a POST request
    sendjob1.PostString("https://www.domain.com/set.php", "var1=" & var1)

    Wait For (sendjob1) JobDone(sendjob1 As HttpJob)

    If sendjob1.Success Then
        'xui.MsgboxAsync("Data was successfully sent to server.", "")

        response = sendjob1.GetString
        Log("Log Start -----------------------------------------------------------")
        Log(response & " " & CRLF)
        Log("Log End -------------------------------------------------------------")

    Else
        response = sendjob1.ErrorMessage
    End If
    'WebView1.LoadHtml(response)

    ' Open external browser to view session variable
    fx.ShowExternalDocument("https://www.domain.com/get.php")

    sendjob1.Release

End Sub

set.php

B4X:
<?php

    // Start the session
    SESSION_START();

    // Get incoming POST variable
    $_SESSION["test"] = $_POST["var1"];

    //$_SESSION["test"] = "Hey!";

    echo "Incoming POST variable is : " . $_SESSION["test"] . "<br><br>";
    echo "<br><br>Log session variables : <br>";
    echo json_encode($_SESSION);

?>

get.php

B4X:
<?php

    // Start the session
    SESSION_START();

    echo $_SESSION["test"] . "<br><br><br>";
    echo "<br><br><br>";
    print_r($_SESSION);
?>

Log

Log Start -----------------------------------------------------------
Incoming POST variable is : Hello B4X!<br><br><br><br>Log session variables : <br>{"test":"Hello B4X!"}
Log End -------------------------------------------------------------

get.php webpage (opened from B4J at success)

1627838283321.png


EDIT

I wrote a B4XSessions Library to at least have a starting point from B4X to work with cookies and make own sessions. I've updated it to v0.5.
You can play around with it, modify it to your on liking. Hopefully improve it and post your contributions here. Let me know so I can put it in this first post.
Here's what you need. A domain server space to store PHP files on. For simplicity I will post them in code format. I hope you find this useful for whatever usage you might find. These PHP script templates is also baken into the library source code.

Do not store sensitive data like privacy information this way. If that is the case encrypt the data and store it in a database with security.
Anyway, this opens up for alot of uses. You can write network applications, pass gaming data for positioning, values, temporary information, verifications, you name it.
It's a lightweight way of storing information without using a database. It's an alternative to standard cookies. This gives you direct control from B4X, that can be useful.

B4XSessions Alternative methods:

Methods:

B4XSessions.GenerateUID
Generates a random UID (user identification number) This can be stored as a file in a cookie folder on your domain.

B4XSessions.Domain(DestinationString)
Returns the default path to your domain. Make sure you change the domain variable in the B4XSessions module for code to work.

B4XSessions.CookieFolder
Returns the domain cookie folder. Subfolder to store the cookie files on your server.
Make sure you change the cookie folder variable in the B4XSessions module for code to work.

B4XSessions.SETSession
Stores the generated UID cookie file on the server.

B4XSessions.UNSETSession
Removes the generated UID cookie file on the server.

B4XSessions.CHECKSession
Opens webpage (check.php) to search if a specific UID cookie file exists on the server.
Note this had to be hardcoded since POST data are lost whenever ShowExternalDocument is called.
(Needs to be solved).

Dependencies:

create.php

B4X:
<?php

    // Recieve POST string to create Cookies subfolder
    $CookieFolder     = $_POST['CookieFolder'];
    $CreateUID         = $_POST['CreateUID'];

    // Create Cookies folder
    mkdir($CookieFolder);

    // Change directory to Cookies folder
    chdir($CookieFolder);

    // Create Cookie File
    $CookieCreate = fopen($CreateUID, "w")

?>

remove.php
B4X:
<?php

    // Recieve POST string to create Cookies subfolder
    $CookieFolder     = $_POST['CookieFolder'];
    $RemoveUID     = $_POST['RemoveUID'];

    // Remove files in Cookie folder
    $dir = $CookieFolder . "/";
    array_map('unlink', glob("{$dir}" . $RemoveUID));

?>

check.php
B4X:
<?php


    $CookieFolder     = "Cookies";
    $CheckUID         = "1627580073964893881104629331612202613825855710527480866101217920394995325";

    if (is_file($CookieFolder . "/" . $CheckUID))
    {
        echo "File exists";
    } else

    {
        echo "File not found";
    }

?>




Default B4XSessions methods:

Credits to OliverA for updating this method.
B4XSessions.SendPostRequest(String)
Sends a POST request to the server. You need to pass a string with this call.

Dependencies:

set.php

B4X:
<?php
    // Start the session
    SESSION_START();
    // Get incoming POST variable
    $_SESSION["test"] = $_POST["var1"];
    //Let's return our session ID
    echo session_id();
?>

get.php
B4X:
<?php
    session_id($_GET["session"]);
    // Start the session
    SESSION_START();

    echo $_SESSION["test"] . "<br><br><br>";
    echo "<br><br><br>";
    print_r($_SESSION);
?>

unsetvar.php (called manually)
B4X:
<?php

// Start the session
    SESSION_START();

    unset($_SESSION["test"]);
    echo "Session was successfully destroyed!";

?>

First thing to do is to go into B4XSessions module and change the variables for domain and cookie folder for your domain.
You can test the methods from the buttons in the GUI. I wish you a great time to explore this library and the many uses you might find.

The PHP scrips are part of the code so you can get it from there. v0.6 is the latest version which is well documented and should be very easy to dive into/use.

Special notes about v0.6:
You can now choose between two types of ID generators. My own and also Erel's GUID generator.
SendPostRequest (Default method) should now work to set session on your domain and open the ShowExternalDocument.
Corrections made from the previous versions. Cleaner GUI, easier to generate User ID's and change type of generator.

Check B4XSession module, run the code and read the log. Follow the instructions and you'll pick it up easily.

/Yours,
{ ThRuST }
 

Attachments

  • B4X Sessions v0.6.zip
    316.2 KB · Views: 68
Last edited:

DonManfred

Expert
Licensed User
Longtime User
$_SESSION["test"] = $_POST["var1"];
var1 is not part of the $_POST Array when using poststring.

$json = retrieveJsonPostData();
$_SESSION["test"] = $json["var1"];

function retrieveJsonPostData(){
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
return json_decode($rawData,true);
}
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
Thanks @DonManfred. If I understand correctly the Poststring uses JSON and thereby needs to be handled accordingly from PHP?
I'm new to json so I will have to look this up further. I've searched allover this forum for a solution but run stuck completely how this is done.
I was hoping that a string being sent could just be fetched in PHP using incoming POST request and all would be fine and well, but it's back to the drawingboard (again)!!

I changed set.php to this

B4X:
<?php

    // Start the session
    SESSION_START();

    // Get incoming POST variable
    //$_SESSION["test"] = $_POST["var1"];

    $json = retrieveJsonPostData();
    $_SESSION["test"] = $json["var1"];

    function retrieveJsonPostData()
    {
        // get the raw POST data
        $rawData = file_get_contents("php://input");
        // this returns null if not valid json
        return json_decode($rawData,true);
    }

    //$_SESSION["test"] = "Hey!";

    echo "Incoming POST variable is : " . $_SESSION["test"] . "<br><br>";
    echo "<br><br>Log session variables : <br>";
    echo json_encode($_SESSION);

?>

Log showed

Log Start -----------------------------------------------------------
Warning: Trying to access array offset on value of type null in (domain............................................................)set.php on line 10
Incoming POST variable is : <br><br><br><br>Log session variables : <br>{"test":null}
Log End -------------------------------------------------------------
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@oparra Hi! I want to set a session on the server from B4J. Set.php is just a test to set the session and Get.php to view the state. This can be useful for alot of things.
 
Upvote 0

Omar Parra A.

Expert
Licensed User
Longtime User
a simple example

scripts 1
PHP:
<?php
session_start();
$_SESSION["test"] = "hello";
echo session_id();
?>

scripts 2
PHP:
<?php
session_id(YOUR_SESSION_ID);
session_start();
echo $_SESSION["test"];
?>
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@oparra Thanks, but I prefer not to use cookies, only sessions. As @DonManfred pointed out, the Poststring needs to deliver the data by using JSON (as he recommended)
so I prefer to go from there. The whole point in my example is that the session can easily be set in Set.php by using $_SESSION["test"] = "Hello B4X!";
and my example will work. However the bottleneck here is that Poststring won't set the session and that's what I am announcing to find a solution to.

To point out this even more in detail, this might be the clue to a solution.
1627855557437.png


Anyway, thanks for your contribution. The one who provide a working solution might get an itunes or amazon gift card someday 😂
As I posted my project on social media the past month has attracted quite a number of scammers. Check out my page at www.facebook.com/Duologic.se
Users should be able to create an account from the app and visit the webportal from a click at mouse button #3. For this to work sessions must be stored on the server.
 
Upvote 0

OliverA

Expert
Licensed User
Ok, I’m on my phone and I’m lazy, but sessions do use cookies, actually one cookie. And no, the post string does not use JSON. According to the first PHP script it does seem to be a post variable, otherwise how do you explain the result? What it looks like is that the cookie that is holding the session ID is last between calls. The reason seems to be that you are using HttpJob for one call and a FX method for the second call. Cookies do not carry across libraries. If you would do the get with HttpJob, then I’m pretty sure things would work as expected. Think about it, if you would do the first call with Firefox and the second call with Chrome, you would get the same failing results, since the cookies would not transfer from Firefox to Chrome. Hope this is making sense…

edit: there was a huge autocorrect snafu that totally changed carry to vary. That makes a huge difference in the meaning of that sentence. Fixed.
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@OliverA The great, you made my day :)👍
Your comments make sense and I came up with a workaround that will revolutionize server side of programming lol
Ladies and gentlemen let me introduce B4X Sessions, the new invention that makes sessions crossplatform and webbrowser independent, yay 🙃
Ok so here's how the library is supposed to work. By storing a file which is a generated UID (User Identification number) and stored on the domain
let's say in a cookies folder, this can be called from any B4X development tool. Oliver, don't be lazy so we leave this honorably task up to you to write this awesome library!!

This will get you started, as I share my code for generating a unique user identification which can be used as a session cookie.
The B4X library should be able to make calls to a domain and subfolder, so the names easily can be changed in the module.
There should be functions to store the cookie file and checked it it exists and as long as it exists the user is logged in.
It should be possible to make a call to delete the cookie which will work both from B4X and from PHP. I hope this inspire to this community to work together on such a lib.
Post your changes in this thread and possibly provide a source code example that users can update. I am sure this will be greatly appreciated by the community.

The UserID number is extremely powerful. The filename can be the same as the number to make it easy to identify the user both locally and for network solutions.
Let me add for this to work both a B4X library and PHP scripts will be needed. I feel encouraged to write it myself but I leave this open for you experts to have some fun.
To spice up this concept even further, the session cookie can even hold information of choise. Anything you come up with which will make it better than current cookies.
Let me add that this could be a great usage for writing network games with B4X, by storing positioning and useful variables, so please take this further.

B4X:
public Sub GenerateUID

    Dim Tal1, Tal2, Tal3, Tal4, Tal5, Tal6, Tal7, Tal8 As Int

    Tal1  = Rnd(10000, 99999999999)
    Tal2  = Rnd(10000, 99999999999)
    Tal3  = Rnd(10000, 99999999999)
    Tal4  = Rnd(10000, 99999999999)
    Tal5  = Rnd(10000, 99999999999)
    Tal6  = Rnd(10000, 99999999999)
    Tal7  = Rnd(10000, 99999999999)
    Tal8  = Rnd(10000, 99999999999)
 
    UID = Tal1 & Tal2 & Tal3 & Tal4 & Tal5 & Tal6 & Tal7 & Tal8
 
    Log(UID)
 
End Sub
 
Last edited:
Upvote 0

OliverA

Expert
Licensed User
PHP does not store any session values in cookies.
Correct. But PHP does store an ID in a cookie that is used to identify the session. This is is then used to access the appropriate session variables on the server
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@DonManfred Indeed I am aware that PHP sessions and cookies is two different mechanics. I'm still looking for how to set a session from Poststring.
I am working on a B4X Sessions library that I will share later today. As an alternative solution because B4X will prove to bridge current technologies anyway.
So B4X Sessions could be useful. Poststring should be able to create a PHP session yes? no? Erel to the rescue 👍
 
Upvote 0

OliverA

Expert
Licensed User
Poststring should be able to create a PHP session yes?
Actually, if Poststring is the first call to the server, that creates the new session. You would then have to extract the session cookie after that call and then figure out how to inject it so that your ShowExternalDocument sends it to the server.
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
Here's the library I started. B4XSessions v0.1. Welcome to add whatever you want in this. Preferably to add those empty subs where I left off for now.
This is a good starting point. I'd appreciate if you experts out there want to add something to this. As Jeff Bezos said, Anything big starts small :)
 

Attachments

  • B4X Sessions v0.1.zip
    208.1 KB · Views: 59
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@OliverA
You would then have to extract the session cookie

That should work, but seems complicated since the whole idea with PHP $_SESSIONS is supposed to be secure.
If you know of a way to fetch the cookie, then please share it in here. I'm working on the B4XSessions lib. It's a great fun side project :)
 
Upvote 0

Omar Parra A.

Expert
Licensed User
Longtime User
@OliverA

That should work, but seems complicated since the whole idea with PHP $_SESSIONS is supposed to be secure.
If you know of a way to fetch the cookie, then please share it in here. I'm working on the B4XSessions lib. It's a great fun side project :)
if it could work read the posts i have posted
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@oparra Nice :)👍 But it might be tricky, like finding the needle in the anthill. Anyway,a step closer to a solution. Great work, oh great wizards of ✨B4X⚡🧙‍♂️
 
Upvote 0
Top