Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

SOLVED! PHP Sessions and Perl

by bajangerry (Sexton)
on Mar 16, 2021 at 16:08 UTC ( [id://11129767]=perlquestion: print w/replies, xml ) Need Help??

bajangerry has asked for the wisdom of the Perl Monks concerning the following question:

Guys,

I am having a hard time wrapping my head around how to get Session info from a PHP webpage into my Perl scripts although it seems quite simple. The website uses a index.html form to login which then redirects to another page that carries out the authentication process and sets the session parameters that I need to maintain within my Perl scripts.

Perl Script which logs in correctly and prints the index.html form as directed.
strict; use Carp; use WWW::Mechanize; use PHP::Session; use CGI::Lite; use strict; my $webaddress = 'http://192.168.133.137/simplsmdr/index.html'; my $user_id = 'user'; my $passwd = 'pass'; my $session_name = 'PHPSESSID'; my $mech = WWW::Mechanize->new( cookie_jar => {}, autocheck => 0, onerror => \&Carp::croak, ); # Login Form my $response = $mech->get($webaddress); if (!$response->is_success) { die "Login page unreachable $webaddress: ", $response->status_lin +e, "\n"; } # Login $mech->form_name("login"); $mech->field('username', $user_id); $mech->field('passwd', $passwd); my $response = $mech->click(); if ($response->is_success) { print $mech-> content(); } else { die "Login failed: ", $response->status_line, "\n"; } my $cgi = new CGI::Lite; my $cookies = $cgi->parse_cookies; if ($cookies->{$session_name}) { my $session = PHP::Session->new($cookies->{$session_name}); # now, try to dump _s_pod variable from session print "uid:",Dumper($session->get('uid')); } else { print "can't find session cookie $session_name"; }
Index.html file:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Login</title> <link rel="stylesheet" href="https://use.fontawesome.com/relea +ses/v5.7.1/css/all.css"> <link href="lib/style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="login"> <h1>Login</h1> <form action="authenticate.php" name="login" method="post" +> <label for="username"> <i class="fas fa-user"></i> </label> <input type="text" name="username" placeholder="Userna +me" id="username" required> <label for="password"> <i class="fas fa-lock"></i> </label> <input type="password" name="password" placeholder="Pa +ssword" id="password" required> <input type="submit" value="Login" name="login"> </form> </div> <div class="login"> <h2>If you don't have an account, please click to <A HREF="reg +ister.html">register</A></h2> </div> </body> </html>
Authentication.php webpages with session info:
<?php session_start(); require_once "lib/config.php"; // Now we check if the data from the login form was submitted, isset() + will check if the data exists. if ( !isset($_POST['username'], $_POST['password']) ) { // Could not get the data that should have been sent. die ('Please fill both the username and password field!'); } // Prepare our SQL, preparing the SQL statement will prevent SQL injec +tion. if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE use +rname = ?')) { // Bind parameters (s = string, i = int, b = blob, etc), in our ca +se the username is a string so we use "s" $stmt->bind_param('s', $_POST['username']); $stmt->execute(); // Store the result so we can check if the account exists in the d +atabase. $stmt->store_result(); } if ($stmt->num_rows > 0) { $stmt->bind_result($id, $password); $stmt->fetch(); // Account exists, now we verify the password. // Note: remember to use password_hash in your registration file t +o store the hashed passwords. if (password_verify($_POST['password'], $password)) { // Verification success! User has loggedin! // Create sessions so we know the user is logged in, they basi +cally act like cookies but remember the data on the server. session_regenerate_id(); $_SESSION['loggedin'] = TRUE; $_SESSION['name'] = $_POST['username']; $_SESSION['id'] = $id; header('Location: index.php'); } else { header('Location: index.html'); } } else { header('Location: index.html'); } $stmt->close();
The output when I run the script is below: c:\perl site.pl
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Login</title> <link rel="stylesheet" href="https://use.fontawesome.c +om/releases/v5.7.1/css/all.css"> <link href="lib/style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="login"> <h1>Login</h1> <form action="authenticate.php" name="login" m +ethod="post"> <label for="username"> <i class="fas fa-user"></i> </label> <input type="text" name="username" pla +ceholder="Username" id="username" required> <label for="password"> <i class="fas fa-lock"></i> </label> <input type="password" name="password" + placeholder="Password" id="password" required> <input type="submit" value="Login" nam +e="login"> </form> </div> <div class="login"> <h2>If you don't have an account, please click to <A HREF="reg +ister.html">register</A></h2> </div> </body> </html> can't find session cookie PHPSESSID
What do I need to do in the Perl script to access the session data from the PHP webpage?

Thanks!

Gerry

Replies are listed 'Best First'.
Re: PHP Sessions and Perl
by hippo (Bishop) on Mar 16, 2021 at 17:02 UTC
    my $cgi = new CGI::Lite; my $cookies = $cgi->parse_cookies;

    That will happily parse any cookies in the request from the browser to your CGI script. You are not calling your CGI script from a browser so there won't be any cookies.

    Inspect the responses to your $mech object to extract the cookies from there instead.

    PS. Don't use indirect object notation. my $cgi = CGI::Lite->new; is preferred.


    🦛

      Hi Hippo,

      When I print the content of my $mech I get the below only, nothing relating the session or cookies. Is this maybe because the login page calls a different page to authenticate and assign the session info?
      <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Login</title> <link rel="stylesheet" href="https://use.fontawesome.c +om/releases/v5.7.1/css/all.css"> <link href="lib/style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="login"> <h1>Login</h1> <form action="authenticate.php" name="login" m +ethod="post"> <label for="username"> <i class="fas fa-user"></i> </label> <input type="text" name="username" pla +ceholder="Username" id="username" required> <label for="password"> <i class="fas fa-lock"></i> </label> <input type="password" name="password" + placeholder="Password" id="password" required> <input type="submit" value="Login" nam +e="login"> </form> </div> <div class="login"> <h2>If you don't have an account, please click to <A HREF="reg +ister.html">register</A></h2> </div> </body> </html>
        When I print the content of my $mech I get the below only, nothing relating the session or cookies.

        Set cookies are not returned in the content. They are returned in the response headers.

        use strict; use warnings; use WWW::Mechanize; use Data::Dumper; my $mech = WWW::Mechanize->new; my $response = $mech->get ('http://your.url.here/'); print Dumper ($response->headers->{'set-cookie'});

        🦛

Re: PHP Sessions and Perl
by marto (Cardinal) on Mar 16, 2021 at 17:12 UTC

    This isn't a use case for CGI::Lite, you aren't running a CGI script here. Consider the following:

    #!/usr/bin/perl use WWW::Mechanize; use strict; use warnings; my $browser = WWW::Mechanize->new(); my $response = $browser->get('https://archive.org'); my $cookie_jar = $browser->cookie_jar(HTTP::Cookies->new()); $cookie_jar->extract_cookies( $response ); my $cookie_content = $cookie_jar->as_string; print $cookie_content;

    Prints:

    Set-Cookie3: PHPSESSID=ls6vbb4cqpeord3o1g96hmacg6; path="/"; domain=ar +chive.org; path_spec; discard; version=0 Set-Cookie3: abtest-identifier=ba42ec4d4af62f23e1645b2597f22eec; path= +"/"; domain=archive.org; path_spec; expires="2022-03-16 16:35:57Z"; v +ersion=0 Set-Cookie3: donation-identifier=d3bd1e3bebfa0105babd7b9ca4a9b5c4; pat +h="/"; domain=archive.org; path_spec; expires="2022-03-16 16:35:57Z"; + version=0
      Hi Marto, I may be getting confused with the difference between sessions and cookies, can you confirm for me that I will have access to ALL of the session parameters by using a cookie? What I mean is, the session information in the webpage provide information such as username and session ID to following webpages if you are browsing with Chrome etc, are these accessible to Perl scripts in the same way using the cookies?

        You're confusion server side sessions and cookies. I think you need to read the comments of your php code:

        // Create sessions so we know the user is logged in, they basically ac +t like cookies but remember the data on the server.
A reply falls below the community's threshold of quality. You may see it by logging in.
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11129767]
Approved by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (2)
As of 2024-04-26 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found