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: 172
Last edited:

TILogistic

Expert
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
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
The cookie name for the PHP session is PHPSESSID . Technically, that name can also be used in an URL argument, in case cookies are not allowed.

Here is the code framework to read the cookies and write them using httpjob https://www.b4x.com/android/forum/t...in-the-subsequent-request.128882/#post-808897

You still have to write code to parse / create a proper cookie header. You'll have to find out how JavaFX handles cookies to see how you could fetch / create them.

This is a lot of work just to use the same php generated session id across libraries. Might as well generate your own unique id and pass it along in the url via get or in the body of the http request.
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
Ok gotta read in your latest posts, but here's v0.2 of my B4XSessions library. I or someone else are free to add whatever you like to it, so it can work to set a session using Poststring. This library should also be able to handle custom session cookies. The sky is the limit here. Many of you can much likely do this better but it's a start.
Don't feel shy to modify the code and update it. I'm not the best programmer in here, but my visions makes up for it ;)👍

Take your time to read through everything and you will be able to try it. It's really simple once you know how I did this. I appreciate if you help me improve this, OK? :)
 

Attachments

  • B4X Sessions v0.2.zip
    269.9 KB · Views: 142
Upvote 0

OliverA

Expert
Licensed User
Longtime User
And it is easy to implement.
This. Technically this is a solved problem. I think there is a total misunderstanding about session handling. And my solution is going down a rabbit hole; that's what I get when working on a phone.
That should work, but seems complicated since the whole idea with PHP $_SESSIONS is supposed to be secure.
Note: Sessions use security through obscurity. Not really bullet proof.

Try this
set.php
PHP:
<?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
PHP:
<?php
    session_id($_GET["session"])
    // Start the session
    SESSION_START();

    echo $_SESSION["test"] . "<br><br><br>";
    echo "<br><br><br>";
    print_r($_SESSION);
?>
B4X:
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
        'the modified PHP script should return the session id
        response = sendjob1.GetString
        fx.ShowExternalDocument($"https://www.domain.com/get.php?session=${response}"$)
    Else
        response = sendjob1.ErrorMessage
    End If

    sendjob1.Release
End Sub
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@OliverA Just got home so I'll give it a try. I should perhaps bake in your solution in B4X Sessions Library as a default Poststring method. I assume that you have tried it yourself to confirm that it works even though we should never question your lazy-coding-from-phone-habits ;)
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@OliverA I tried your solution and the get.php page shows this. Does it work for you guys?

Parse error: syntax error, unexpected identifier "SESSION_START" in /customers/b/4/6/duologic.se/httpd.www/get.php on line 4

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);
?>
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
I forgot the semicolon behind the session_id line. I don’t do PHP, so any code of mine is suspect to errors and omissions

Note: using a phone to post on this forum also introduces errors and omissions on my part
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
Ah I see it now. You're excused. DO NOT FAIL ME AGAIN. There's a disturbance in the force Lord @OliverA 😂
I will try it and let you know what happened. If my computer explodes after a whole day with B4X Sessions it's your fault 😁
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@OliverA I tested your solution with the new default Poststring method and ShowExternalDocument loads the webpage data in the log.
Please confirm it on your computer. I have updated my B4XSessions library in post #1. Play around with it and see what you can achieve. Thanks!
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@OliverA I just tested your Poststring solution by loading get.php manually in Google Chrome and the session is set :)👍

B4X:
 ' Default Poststring POST request (pass a string)
    B4XSessions.SendPostRequest("Hello B4X!")

1628017360385.png
 
Upvote 0

ThRuST

Well-Known Member
Licensed User
Longtime User
@oparra Thanks, it's really useful to know about sessions lifecycle. Especially when there's both cookies and sessions. I got inspiration to investigate it and I ended up writing the B4XSessions library. It was great fun and good to learn from. It can be a good starting point for further explorations. Let me know if there's any methods to add if there's an interest to improve it further. I have only tried it with B4J myself but it would be cool to know if this works for all other B4X compilers.
 
Upvote 0
Top