Do someting if user does not interact after some time - PHP - php

I`m building a whatsapp bot, the bot is fully operational, but I want to do a API call if user does not interact with the api after some time. I tryed to do with session, but is not working, I tryed the following code.
session_start();
//**my bot code**
$minutesBeforeSessionExpire=30;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > (2))) {
$data2 = [
'phone' => $_SESSION['phone'],
'body' => 'Hello, Andrew!',
];
$json2 = json_encode($data2);
$options2 = stream_context_create(['http' => [
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $json2
]
]);
$result2 = file_get_contents('api_call', false, $options2);
session_unset(); // unset $_SESSION
session_destroy(); // destroy session data
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity

Unfortunately for you, "any API" is purely "server side." Therefore, it cannot "react" when anyone "fails to reply." The only thing that it can do is, when presented with [any ...] subsequent request, to say: "So sorry, too late!"
The key point being that the response is reactive, not proactive.

In order to “do something” when a user doesn’t interact, there must be something that interacts with the user. This is typically either a client side script, websockets, signal R. It doesn’t just happen naturally, in fact quite the opposite, naturally the server totally forgets about an incoming request as soon as it is done with it.

For those who find this question, I solved my issue by storing the user last interaction on my db.
After that I created a cron on my cpanel to run the update code, and everything ran as expected.

Related

Login with Guzzle on form - Post request on test.de

I would like to use my PHP script and Guzzle to login on this website: https://www.test.de/meintest/login/
However, I already tried many solutions and also read this article, I still fail on logging in.. mostly cause the request is build very complicated.. I have used firefox to log the requests the website is doing when I press "Einloggen" (means login). There is a XHR request done before actually logging in. I think this has to do something with the login and parameters..
This is my code so far:
$loginURL = "https://test.de/meintest/login";
$guzzle = new \GuzzleHttp\Client();
$cookieJar = new \GuzzleHttp\Cookie\CookieJar();
$response = $guzzle->request('POST', $loginURL, [
'form_params' => [
'username' => "0000000000",
'password' => "0000000000",
'action' => 'login'
],
'cookies' => $cookieJar,
'debug' => true
]
);
var_dump($response->getBody()->getContents());
var_dump($guzzle->getConfig('cookies'));
There are also some hidden inputs which get filled with the XHR request I think..
Could you guys may help me and tell me where my failure is..?
EDIT
But I also could assume that the reason why it isn't working is the fact that this line var_dump($guzzle->getConfig('cookies')); always prints bool(false) instead of the cookies.. Does the cookies get even saved?
Kind regards and Thank You!
I've noticed there are 2 hidden inputs "source" and "hash", obviously you are missing those fields.
Nowadays most websites do have CSRF protection. You cannot just post formData to log in.

Log in to an external website and redirect it as a logged-in user

great pleasure someone helps me with the following question, you will see I want to create a site that stores the accounts of the external pages, so that when they enter the user and the password in my application, this one realizes the login in the external web and then redirect the page how logged in users. My question is this, is it possible to do that? I wanted to try it with guzzle, but it could not, then I tried goutte, but I got an error that did not detect the fields, what could I do? Thank you
So users will need to share their username and password with you and you'll be storing that in your DB, and it'll need to be plain text or in a way that is easily converted back into plain text. This is a BIG RED FLAG.
If there is some legitimate reason why you'd be doing this, I'd suggest working with a CookieJar in Guzzle. You could POST a login with the user credentials, and store the resultant cookie, then send that in the headers with any subsequent request for that user.
Some rough code to give you an idea:
$client = new GuzzleHttp\Client;
$filename = $somePath . '/cookies.json';
$jar = new GuzzleHttp\Cookie\FileCookieJar($filename);
// Login
$url = 'http://some_login_url';
$body = [
'user' => $someUser,
'pass' => $somePassword
];
$response = $client->post($url, ['cookies' => $jar, 'body' => $body]);
// Make sure the response is valid here
$jar->save($filename);
// Retrieve a private page for a user
$url = 'http://private_page_url';
$response = $client->get($url, ['cookies' => $jar]);
// Make sure the response is valid here
$html = (string) $response->getBody();
// Do scrapy stuff with HTML
Clearly, this would need a bit of work to make it useful.

GET works but POST doesn't for silent login

We have 2 systems one in PHP and one in asp.net which currently require separate logins even though both use the same username/password information.
As a quick (and temporary) fix I thought I might be able to amend the PHP login page to pass the login details to the asp.net page behind the scenes so the user could be logged in automatically to both systems rather than having to enter their credentials again when navigating to a different page.
This works fine when I use a GET to pass the parameters but of course the GET parameters including the password get stored in the server log which is not a good idea.
So I would like to use POST instead, but I can't get it to work. I used the CURL-less method in How do I send a POST request with PHP? (code below) and it appears to work but the asp.net login process creates secure cookies and while they are stored if I GET the page they are not being stored when I POST to it instead.
$url = 'https://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
I have tried something similar with CURL in the past so I know that CURL creates it's own browser context but I thought a straight POST request would work, however it seems to be behaving much the same as CURL.
Is there some way to get this to work or do I have a fundamental misunderstanding of how POST works? If so could somebody point me at a good explanation.

Facebook App Notifcations PHP

I've been reading through the facebook developer docs and i'm a little confused, I want to re-engage a load of users that have gone a little stale really by giving them a little nudge regarding their inactivity on our app...
What is the current "best practice/latest way" of doing this, it seems to be via the notifications API?
https://developers.facebook.com/docs/app_notifications/#imp
If i'm correct can someone give me a couple of pointers for a PHP implementation of this, essentially it would be a cron running once a month/every two weeks wizzing through users who haven't logged in for a while and prodding them.
Thanks
Marc
Well since nobody responded to this heres a simple working solution that I figured out from the docs. To notify a user they have to authorised your app.
$book = new Facebook((array(
'appId' => 'XXXXXX',
'secret' => 'XXXXXX',
'grant_type' => 'client_credentials')
));
$vars = array(
"access_token" => $book->getAppId().'|'.$book->getApiSecret(),
"href" => "index.php",
"template" => "Some text to send up to 180 characters",
"ref" => "This is what shows up in insights so you can track responses"
);
$post = $book->api('/' . $userid . '/notifications/', 'post', $vars);
You can insert user names into template by surrounding the facebook user id with {} ie:
"{12345} would like to play some game with you." . It will throw an exception though if the uid refers to a user that hasn't authed your app.
Href automatically gets your canvas url inserted infront of it so no need to full domain/path.
ref is used in the insights interface so you can see which notifications are generating traffic!
Thats it, very simple to re-engage those users who seem to have disappeared!
Cheers
Marc

How to post from php with cookies?

How can I make a post request using cookies from php.
My php code:
<?php
$time_start = microtime(true);
$id=$_GET[id];
$data = http_build_query( array ('act' => 'load_friends_silent', 'al' => '1', 'gid'=>'0' ,'id'=>$id) );
$opts = array(
'http'=>array(
'header'=>"Cookie: something=asdaefefe",
'method'=>"POST",
'content' => $data
)
);
$context = stream_context_create($opts);
print $context;
$contents = file_get_contents('http://vkontakte.ru/al_friends.php', false, $context);
$fil=fopen("./".$id."ne.txt","w");
echo '<br><br>'.$contents;
fputs($fil,$contents);
fclose($fil);
chmod("./".$id."ne.txt", 0777);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<br><br>execute time $time seconds\n";
?>
But this code won't work on the server; cookie not sent.
[EDIT]
To use PHP to post to a page that the user will NOT navigate to, you can use CURL:
http://davidwalsh.name/execute-http-post-php-curl
Where in the example, you set $fields to your cookie values:
$fields = array(
'lname' => urlencode($_COOKIE['last_name'] ),
'fname' => urlencode($_COOKIE['first_name'] ),
...
);
[EDIT AGAIN]
By your newly posted code it looks like you are trying to create a cookie on the page that you are posting to. First of all, creating cookies for other websites would seem to be a big security risk, so I'm 99.9% certain that this has never been nor ever will be possible. Secondly, PHP is not a browser and can't store cookies for other sites...so even if your post created a cookie, the user's browser would not have that cookie. All you can do is post 'something'=> urlencode('value'), and then the page you are posting to will have to create the cookie on their end. However, since PHP can't hold cookies since it's not a browser, this would be pointless.
If you want the user's browser to have a cookie, then you need to use something like jQuery's $.post. Using jQuery's post() method will use the user's browser to go to the page and post data. The page that gets the posted data can then create a cookie on the user's browser.
[Read These] they may contain some info for you. Is this what you're trying to do?
Simulating a cookie-enabled browser in PHP
Simulating a POST with PHP & cURL
It does sound like CURL should be able to mimic a browser's cookie capabilities...so you might be able to send cookie data, though, as I said, you woudln't be able to set the user to those cookies or anything...since I'm not sure of your purpose, that makes an answer harder:
http://php.net/manual/en/function.curl-setopt.php
Read this, maybe it will help. http://www.w3schools.com/PHP/php_cookies.asp

Categories