How to Set Up Expiration to Sessions using PHP

PHP CURL — Session expired

I’m trying to make an voip call with PHP CURL and MEGAVOIP. The problem is i can’t manage the session to access the page protected by a password. I looked which variables are posted to the login page to post it with Curl. But my code doesn’t work. Following Colin Morelli and Waygood’s advices, I just added those lines in both commands:

curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies_file); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies_file); 
]+>/i',$content, $result); preg_match_all('/(id|value)=("[^"]*")/i',$result[0][5], $img); $img1=str_replace('"', '', $img[0][0]); $img2=str_replace('"', '', $img[0][1]); $img1=substr($img1,3); $img2=substr($img1,6); $postdata = "login%5Busername%5D=".$username."&login%5Bpassword%5D=".$password."&page_referrer=login&".$img1." mt24 mb12">
    phpsessioncurl
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
)">edited Mar 18, 2013 at 13:21
asked Mar 18, 2013 at 13:04
4
    2
    You need to set COOKIEFILE and COOKIEJAR in your second request as well. Your first request (to the login page) will cause cookies to be written to those files. Your second request needs to be able to read those cookies and then send them to the server.
    – Colin M
    Mar 18, 2013 at 13:14
    1
    too quick lol +1 curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies_file); is missing from the top one too
    – Waygood
    Mar 18, 2013 at 13:15
    @Waygood For the sake of full coverage, yeah. I just checked up though and technically speakingCOOKIEJAR is where cookies are written to, and COOKIEFILE is where they are read from. But yes, I would say there's no harm in doing it to be safe, +1.
    – Colin M
    Mar 18, 2013 at 13:19
    Thank you a lot. I fixed it this way but it still doesn't work.
    – Voip Calls
    Mar 18, 2013 at 13:28
Add a comment|

1 Answer 1

Reset to default
0

Ok you need to forward the cookie/session after login,

you need to first extract the cookie from Header after login like following

// HERE I GET THE TOKEN $ch = curl_init($url); curl_setopt($ch, CURLOPT_COOKIESESSION, true); . . . . $content = curl_exec($ch); preg_match('/^Set-Cookie:\s*([^;]*)/mi', $content, $m); parse_str($m[1], $cookies); $cookie = $cookies['NAMEOFCOOKIEUNEEDHERE'];
// HERE I SEND THE VARIABLES $ch = curl_init($url); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_COOKIE, 'NAMEOFCOOKIEUNEEDHERE='.$cookie); 

Источник

How to expire PHP sessions.

This is a simple guide on how to expire user sessions in PHP after a set amount of time.

In this example, we are going to assume that you want to expire a user’s session after 30 minutes of inactivity.

Unfortunately, with PHP, you will need to manually expire a user’s session. We will explain why later on. For now, let’s just take a look at the example code.

= $expireAfterSeconds) < //User has been inactive for too long. //Kill their session. session_unset(); session_destroy(); >> //Assign the current timestamp as the user's //latest activity $_SESSION['last_action'] = time();

A quick drill-down of the session expiry code above.

  1. We start our session with session_start(), like always! Remember: You cannot access session variables until the session has been started.
  2. For this example, we set the expiry limit to 30 minutes. You can change this number to 40 minutes or 60 minutes if you wish.
  3. Using the function isset, we check to see if a session variable called “last_action” exists. It is important to verify that this variable exists before we attempt to carry out any calculations on it.
  4. Inside the IF statement, we calculate the number of seconds that have passed since the user was last active. To do this, we subtract the “last_action” timestamp from the current timestamp.
  5. We then convert our $expireAfter variable into seconds by multiplying it by 60. This is important as it allows us to compare the seconds that have passed against the maximum amount of seconds that are allowed to pass before the session should be expired.
  6. We then compare the two values. If $secondsInactive is larger than or equal to $expireAfterSeconds, the user has been inactive for too long and we need to take action.
  7. IF the user has been inactive for too long, we destroy the current session. We do this by calling the functions session_unset and session_destroy.
  8. Finally, we reset the last activity variable by assigning the current timestamp to it.

session.gc_maxlifetime doesn’t work.

Some of you are probably wondering why we didn’t recommend using session.gc_maxlifetime, which is a configuration option that exists inside the php.ini file.

You see, the problem with session.gc_maxlifetime is that it doesn’t do what most PHP developers “expect” it to do.

A lot of developers presume that it’s an easy way of getting PHP to automatically expire sessions after a set period of time. For example, setting it to…

;1800 seconds = 30 minutes session.gc_maxlifetime = 1800

…should automatically expire all PHP sessions after 30 minutes, right?

Unfortunately, this isn’t the case. This option relies on PHP’s garbage collection (that’s what the gc in gc_maxlifetime stands for). The problem is, PHP’s garbage collection has a 1% chance of being called, per request (default values).

This means that you can never rely on it to automatically expire user sessions.

To put that into perspective, if you have 100 users that have been inactive for longer than 30 minutes, then only one of them will have their session expired.

Источник

[Solved]: PHP sessions expiring too soon

PHP sessions are an essential part of web development as they enable developers to store and access information across multiple pages.

Some of the common applications of PHP sessions include:

However, sometimes PHP sessions expire too soon, causing users to lose their data and forcing them to log in or add items to the cart again. This can be frustrating for users and can negatively impact the user experience.

In this article, we will cover some of the causes of PHP sessions expiring too soon and provide solutions to fix the issue.

What causes PHP sessions to expire too soon?

Below are some of the reasons why the sessions may seem to expire too soon:

  • Session Timeout Configuration: By default, PHP sessions are set to expire after 1440 seconds (24 mins) of inactivity. This duration can be changed in the php.ini, .htaccess, or PHP files. If this value is set too low, the sessions will expire too soon before the users are done with their activities.
  • Inactivity of Users: If users do not actively participate in the session for a timeframe longer than the session timeout duration, that can also lead to session expiration before they have finished their activity.
  • Server Load: If the server is under heavy load or has too many active sessions, it may not be able to keep all the sessions active, leading to some expiring too soon.
  • Expired Cookies: Though the user information in PHP sessions is stored on the server, the session ID is stored in a cookie on the user's computer, so that the server can identify the user in subsequent requests. If the browser is configured to delete cookies when it is closed or after a certain period of time, the session will expire prematurely.
  • Network Interruptions: Another reason why PHP sessions can expire too soon is due to network interruptions. If the connection between the client and the server is lost or interrupted, the session can be lost, leading to expiration.
  • Shared Session Directory: Session files on the server are cleaned up by the garbage collector based on the value in the session.gc_maxlifetime directive. If different websites have different values of this directive but share the same directory for storing the session data, then the garbage collector uses the minimum value to clean the data. Since by default PHP stores all session files in the same directory, other PHP processes running on the same server can set a shorter expiration time and cause their session data to be removed together with yours.

How to fix PHP sessions expiring too soon

Below are several ways you can fix this issue.

Increasing duration in session timeout settings

You can increase the session timeout settings via the php.ini file or directly in PHP files.

Below is how you can increase the session timeout to 1 hour from the default 24 minutes by adding these lines at the very beginning of all PHP files that use sessions.

If the pages are many, you can just create a file, add these lines and then add it at the top of the files using the include() function. This will enable easy editing if you want to change the session duration.

Alternatively, you can adjust the session timeout in the php.ini file as below.

Reduce the frequency of garbage collection

Every time a new session is started, there's a chance that garbage collection will happen. When garbage collection happens, it expires/trashes any session files that haven't been accessed in more than the session.gc_maxlifetime.

You can reduce the probability of garbage collection happening on every session initialization by configuring the session.gc_probability and session.gc_divisor directives. The default value for session.gc_probability is 1, while that of session.gc_maxlifetime is 100.

The probability is calculated using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the garbage collection process starts on each request.

You can check and change these values in the php.ini file like in the example below to have a low probability.

To prevent premature expiration of sessions due to cookies, set the cookie expiration time to a longer period. This period should be greater than, or at least equal to your session.gc_maxlifetime directive. You can set the cookie expiration time to one week as follows:

Setting session.cookie_lifetime value to 0 will keep the session active until the browser is closed.

Setting a custom session directory

To prevent other sites/scripts running on the same machine as yours from setting a shorter session expiration time, you need to set your own session directory.

Create a new folder in your user home directory (outside of your webroot) that PHP has read/write access to. Then set the session.save_path directive to this new directory.

For instance, if your site resides in the "/home/username/public_html" directory in the cPanel file manager, you can create a folder like "/home/username/sessions" and ensure it has (or set) proper permissions (ie 755).

Make sure you set this path along with the session.gc_maxlifetime with each and every request before calling the session_start() function.

Then have these lines at the top of your PHP scripts

Alternatively, you can set this in your php.ini file. In cPanel, specify the full path via the MultiPHP INI Editor or directly in the php.ini file in the File Manager.

Remember to replace "username" in the path with your actual username in the file manager.

Conclusion

PHP sessions essential in web development and expiring too soon can be frustrating and inconvenient for users. In this article, we have covered several ways in which you can fix this issue.

Источник

How to Set Up Expiration to Sessions using PHP

session expire in php

In this tutorial, I’m going to show you how to set up expiration on PHP sessions. This tutorial will not give you a good design but will provide you with an idea in setting up session and expiry in PHP.

Creating a Login Form and Login Script

First, we create our login form with the login script. We have set up the session and expiry on the login script upon user submission if username and password are correct. We name this as “index.php”.

     My username: neovic 
My password: devierte

Login Form

Username: Password:
else < echo "Username or Password did not match!"; >> ?>

Creating a Goto Page

Next step is to create our goto page if the login input matches. We have included in this page a Logout link that will destroy our session. We name this as “goto.php”.

"; ?> Login Here elseif ($now > $_SESSION['expiry']) < session_destroy(); echo "Your session has expired! Login again"."
"; ?> Login Here else < ?> Welcome - Logout ?>

Creating a Logout Script

Lastly, we create our logout script. This script will destroy our current session and will redirect us back to our login page. We name this script as “logout.php”.

Источник

Читайте также:  Title property in css
Оцените статью