Handler session error

[Found solution by Ember Nava] However, this is just for capturing the session errors. A better way would be to create a general error handler that creates exceptions from err

Answer by Ember Nava

However, this is just for capturing the session errors. A better way would be to create a general error handler that creates exceptions from errors and surround code parts that may throw errors with try … catch blocks. ,The regular PHP session functions don’t throw exceptions but trigger errors. Try writing an error handler function and setting the error handler before calling session_start.,I’m looking for a general way to handle session_start errors, not a way to handle one specific error. There are numerous errors which can happen, such as the session directory being full, which cause a fatal error. I want a way to trap those errors and handle them cleanly, without having to write custom handlers for each possibility.,
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

The regular PHP session functions don’t throw exceptions but trigger errors. Try writing an error handler function and setting the error handler before calling session_start.

function session_error_handling_function($code, $msg, $file, $line) {
    // your handling code here
}

set_error_handler('session_error_handling_function');
session_start();
restore_error_handler();

Answer by Aniya Guzman

I have this at the very top of my send.php file:,And the following at the very top of my test.php file:,So first thing it relate to permission ,Second thing it relate to session.save_path

I have this at the very top of my send.php file:

ob_start();
@session_start();

//some display stuff

$_SESSION['id'] = $id; //$id has a value
header('location: test.php');

And the following at the very top of my test.php file:

ob_start();
@session_start();

error_reporting(E_ALL);
ini_set('display_errors', '1');

print_r($_SESSION);

Answer by Egypt Acosta

session_cache_expire — Get and/or set current cache expire,session_abort — Discard session array changes and finish session,session_cache_limiter — Get and/or set the current cache limiter,session_id — Get and/or set the current session id


There is a nuance we found with session timing out although the user is still active in the session.  The problem has to do with never modifying the session variable.

The GC will clear the session data files based on their last modification time.  Thus if you never modify the session, you simply read from it, then the GC will eventually clean up.

To prevent this you need to ensure that your session is modified within the GC delete time.  You can accomplish this like below.

<?php
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
  $_SESSION['last_access'] = time();
?>

This will update the session every 60s to ensure that the modification date is altered.

Answer by Alisson Pugh

Session variables are set with the PHP global variable: $_SESSION.,A session is started with the session_start() function.,Also notice that all session variable values are stored in the global $_SESSION variable:,Note: The session_start() function must be the very
first thing in your document. Before any HTML tags.

session_start();
["favcolor"] = "green";

Answer by Gracie Welch

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.,While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required.,Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error(),Following is the way you can create one error handling function −

Try following example without having /tmp/test.xt file and with this file.

<?php
   if(!file_exists("/tmp/test.txt")) {
      die("File not found");
   }else {
      $file = fopen("/tmp/test.txt","r");
      print "Opend file sucessfully";
   }
   // Test of the code here.
?>

Syntax

error_function(error_level,error_message, error_file,error_line,error_context);

All the above error level can be set using following PHP built-in library function where level cab be any of the value defined in above table.

int error_reporting ( [int $level] )

Following is the way you can create one error handling function −

<?php
   function handleError($errno, $errstr,$error_file,$error_line) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
      echo "<br />";
      echo "Terminating PHP Script";
      
      die();
   }
?>

Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist.

<?php
   error_reporting( E_ERROR );
   
   function handleError($errno, $errstr,$error_file,$error_line) {
      echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
      echo "<br />";
      echo "Terminating PHP Script";
      
      die();
   }
   
   //set error handler
   set_error_handler("handleError");
   
   //trigger error
   myFunction();
?>

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
   try {
      $error = 'Always throw this error';
      throw new Exception($error);
      
      // Code following an exception is not executed.
      echo 'Never executed';
   }catch (Exception $e) {
      echo 'Caught exception: ',  $e->getMessage(), "n";
   }
   
   // Continue execution
   echo 'Hello World';
?>

You can define your own custom exception handler. Use following function to set a user-defined exception handler function.

string set_exception_handler ( callback $exception_handler )

Example

<?php
   function exception_handler($exception) {
      echo "Uncaught exception: " , $exception->getMessage(), "n";
   }
	
   set_exception_handler('exception_handler');
   throw new Exception('Uncaught Exception');
   
   echo "Not Executedn";
?>

Answer by Stanley Whitaker

The important thing is that the session_start function must be called at the beginning of the script, before any output is sent to the browser. Otherwise, you’ll encounter the infamous Headers are already sent error.,In this article, we’ve explored the basics of session handling in PHP. It’s a key concept which allows you to persist information across web pages.,Session handling is a key concept in PHP that enables user information to be persisted across all the pages of a website or app. In this post, you’ll learn the basics of session handling in PHP.,You can also learn about session variables in my post on using cookies in PHP.

This is the method that you’ll see most often, where a session is started by the session_start function.

<?php
// start a session
session_start();
 
// manipulate session variables
?>

There’s a configuration option in the php.ini file which allows you to start a session automatically for every request—session.auto_start. By default, it’s set to 0, and you can set it to 1 to enable the auto startup functionality.

session.auto_start = 1

On the other hand, if you don’t have access to the php.ini file, and you’re using the Apache web server, you could also set this variable using the .htaccess file.

php_value session.auto_start 1

As we discussed earlier, the server creates a unique number for every new session. If you want to get a session id, you can use the session_id function, as shown in the following snippet.

<?php
session_start();
echo session_id();
?>

That should give you the current session id. The session_id function is interesting in that it can also take one argument—a session id. If you want to replace the system-generated session id with your own, you can supply it to the first argument of the session_id function.

<?php
session_id(YOUR_SESSION_ID);
session_start();
?>

Let’s go through the following example script that demonstrates how to initialize session variables.

<?php
// start a session
session_start();
 
// initialize session variables
$_SESSION['logged_in_user_id'] = '1';
$_SESSION['logged_in_user_name'] = 'Tutsplus';
 
// access session variables
echo $_SESSION['logged_in_user_id'];
echo $_SESSION['logged_in_user_name'];
?>

Let’s see how to modify the session variables.

<?php
session_start();
 
if (!isset($_SESSION['count']))
{
  $_SESSION['count'] = 1;
}
else
{
  ++$_SESSION['count'];
}
 
echo $_SESSION['count'];
?>

On the other hand, if you would like to delete a session variable, you can use the unset function, as shown in the following snippet.

<?php
// start a session
session_start();
 
// initialize a session variable
$_SESSION['logged_in_user_id'] = '1';
 
// unset a session variable
unset($_SESSION['logged_in_user_id']);
?>

So if you’re using the session_destroy function to log a user out, you must unset the $_SESSION variable and unset the session cookie as well. Thus, the recommended way to destroy a session completely is:

<?php
// start a session
session_start();
 
// destroy everything in this session
 
unset($_SESSION);
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"],$params["httponly"]);
}
 
session_destroy();
?>

In our example, we’re going to store sessions in the MySQL database. So let’s create a table which stores the session data by using the following snippet.

CREATE TABLE `sessions` (
  `session_id` varbinary(192) NOT NULL,
  `created` int(11) NOT NULL DEFAULT '0',
  `session_data` longtext COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Next, let’s see how our custom database session handler looks:

<?php
class MySQLSessionHandler implements SessionHandlerInterface
{
    private $connection;

    public function __construct()
    {
        $this->connection = new mysqli("HOST_NAME","USERNAME","PASSWORD","DATABASENAME");
    }

    public function open($savePath, $sessionName)
    {
        if ($this->connection) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function read($sessionId)
    {
        try {
            $stmt = $this->connection->prepare("SELECT session_data FROM sessions WHERE session_id = ?");
            $stmt->bind_param("s", $sessionId);
            $stmt->execute();
            $stmt->bind_result($sessionData);
            $stmt->fetch();
            $stmt->close();

            return $sessionData ? $sessionData : '';
        } catch (Exception $e) {
            return '';
        }
    }

    public function write($sessionId, $sessionData)
    {
        try {
            $stmt = $this->connection->prepare("REPLACE INTO sessions(`session_id`, `created`, `session_data`) VALUES(?, ?, ?)");
            $stmt->bind_param("sis", $sessionId, $time=time(), $sessionData);
            $stmt->execute();
            $stmt->close();

            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public function destroy($sessionId)
    {
        try {
            $stmt = $this->connection->prepare("DELETE FROM sessions WHERE session_id = ?");
            $stmt->bind_param("s", $sessionId);
            $stmt->execute();
            $stmt->close();

            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public function gc($maxlifetime)
    {
        $past = time() - $maxlifetime;

        try {
            $stmt = $this->connection->prepare("DELETE FROM sessions WHERE `created` < ?");
            $stmt->bind_param("i", $past);
            $stmt->execute();
            $stmt->close();

            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public function close()
    {
        return TRUE;
    }
}

Our custom session handler class MySQLSessionHandler implements the SessionHandlerInterface interface. Thus, it must implement methods that are declared in the SessionHandlerInterface interface. We’ll look at these methods one by one to understand how each one works.

    public function __construct()
    {
        $this->connection = new mysqli("HOST_NAME","USERNAME","PASSWORD","DATABASENAME");
    }

First, to use this code, make sure to replace the HOST_NAMEUSERNAME, and other placeholders with actual values in the __construct method.

    public function open($savePath, $sessionName)
    {
        if ($this->connection) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

When the session is started, the open method is called. It returns TRUE if the database connection was successful. If there was any problem setting up the database connection, it returns FALSE.

    public function read($sessionId)
    {
        try {
            $stmt = $this->connection->prepare("SELECT session_data FROM sessions WHERE session_id = ?");
            $stmt->bind_param("s", $sessionId);
            $stmt->execute();
            $stmt->bind_result($sessionData);
            $stmt->fetch();
            $stmt->close();

            return $sessionData ? $sessionData : '';
        } catch (Exception $e) {
            return '';
        }
    }

Next, PHP calls the read method to read the session data. The read method receives the session id as the first argument. We’ll check if there’s any entry available for this session id in the session_data table. If it exists, we’ll return the session data; otherwise, an empty string will be returned.

    public function write($sessionId, $sessionData)
    {
        try {
            $stmt = $this->connection->prepare("REPLACE INTO sessions(`session_id`, `created`, `session_data`) VALUES(?, ?, ?)");
            $stmt->bind_param("sis", $sessionId, $time=time(), $sessionData);
            $stmt->execute();
            $stmt->close();

            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

When PHP needs to save or close a session, it calls the write method. It’s used to write the session data in a database. We’ve used the REPLACE syntax to make sure that if an entry exists, it will be updated; otherwise, it’ll be inserted.

    public function close()
    {
        return TRUE;
    }

The close method is called after the session write method has been called. It works similar to a destructor in classes. In our case, there is nothing particular that needs to be done in the close method.

    public function destroy($sessionId)
    {
        try {
            $stmt = $this->connection->prepare("DELETE FROM sessions WHERE session_id = ?");
            $stmt->bind_param("s", $sessionId);
            $stmt->execute();
            $stmt->close();

            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

The destroy method is called when the session is destroyed with either the session_destroy or session_regenerate_id function. In this method, the session data is deleted from a database if it exists.

    public function gc($maxlifetime)
    {
        $past = time() - $maxlifetime;

        try {
            $stmt = $this->connection->prepare("DELETE FROM sessions WHERE `created` < ?");
            $stmt->bind_param("i", $past);
            $stmt->execute();
            $stmt->close();

            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

Now, let’s see how to use the MySQLSessionHandler handler class.

$objSessionHandler = new MySQLSessionHandler();
session_set_save_handler($objSessionHandler, true);
session_start();
$_SESSION['favoriteWebsite'] = 'tutsplus.com';

Answer by Danna Molina

In PHP, we can use our custom method to display any message or execute any code when error occurs. All we have to do is set our method as the default error handler for PHP using the function set_error_handler(),Error handling is done to gracefully handle errors in the code and provide a better user experience to the end user.,As you can see in the code above the error condition is handled. Now our code will not display any error on scree, rather it will display a message and exit gracefully.,Now let’s see how we can use conditional statements to handle error conditions. This type of error handling is useful when we know situations which may lead to errors beforehand.

An error can occur when we try to divide a number with zero, or try to open a file which doesn’t exist, let’s take an example and see how we can use die() function or conditional statement to handle error conditions.

<?php
    
    $fileName = "noerror.txt";
    // opening the file
    fopen($fileName, "r")
    or die("Unable to open file $fileName");
    
?>

For example, the below code will lead to error:

<?php
    
    function division($numerator, $denominator) {
        // perform division operation
        echo $numerator / $denominator;
    }
    
    // calling the function
    division(7, 0);
    
?>

In such situation, where we know certain condition can lead to error, we can use conditional statement to handle the corner case which will lead to error. Let’s fix the above code:

<?php
    
    function division($numerator, $denominator) {
        // use if statement to check for zero
        if($denominator != 0) {
            echo $numerator / $denominator;
        }
        else {
            echo "Division by zero(0) no allowed!";
        }
    }

    // calling the function
    division(7, 0);
    
?>

Let’s take an example:

<?php
    
    // custom function to handle error
    function studytonight_error_handler($error_no, $error_msg) {
        echo "Oops! Something unexpected happen...";
        echo "Possible reason: " . $error_msg;
        echo "We are working on it.";
    }
    
    // set the above function s default error handler
    set_error_handler("studytonight_error_handler");
    
    $result = 7 / 0;
    
?>

Following is the syntax for this function:

<?php
    // error reporting function
    error_reporting($reporting_level);
    
?>

Answer by Troy Patton

On the call of new SimpleSAMLAuthSimple(‘default-sp’); it tries to create a new session or use the existing session for SimpleSAML, where it fails with an error,But the cookies SimpleSAML and SimpleSAMLAuthToken have values and as seen from the error message I shared in the issue, it tries to load the session using that session id from cookie SimpleSAML.,But for a validation page in the application, it fails after it has user authenticated with IDP and has the auth token already in session.,@jaimeperez I have been looking into sessions configuration and stumbled upon these error messages generated by simplesaml, this is after the authentication is done from the IDP.

Fatal error: Uncaught SimpleSAMLErrorException: Cannot load PHP session with a specific ID. in /var/simplesamlphp/lib/SimpleSAML/SessionHandlerPHP.php:268 
Stack trace: 
#0 /var/simplesamlphp/lib/SimpleSAML/Session.php(344): SimpleSAMLSessionHandlerPHP->loadSession('...') 
#1 /var/simplesamlphp/lib/SimpleSAML/Session.php(259): SimpleSAMLSession::getSession() 
#2 /var/simplesamlphp/lib/SimpleSAML/Auth/Simple.php(51): SimpleSAMLSession::getSessionFromRequest() 
#3 /var/www/html/*.php(14): SimpleSAMLAuthSimple->__construct('default-sp') 
#4 /var/www/html/*.php(186): .....
#5 {main} thrown in /var/simplesamlphp/lib/SimpleSAML/SessionHandlerPHP.php on line 268

Answer by Danna Molina

Exception handling is a powerful mechanism of PHP, which is used to handle runtime errors (runtime errors are called exceptions). So that the normal flow of the application can be maintained.,PHP provides a powerful mechanism, exception handling. It allows you to handle runtime errors such as IOException, SQLException, ClassNotFoundException, and more. A most popular example of exception handling is — divide by zero exception, which is an arithmetic exception.,Exception handling is an important mechanism in PHP, which have the following advantages over error handling -,In other words, — «An unexpected result of a program is an exception, which can be handled by the program itself.» Exceptions can be thrown and caught in PHP.

Exception Message: Value must be less than 1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

GasparSukk opened this issue

Dec 19, 2016

· 6 comments

Comments

@GasparSukk

Sorry, i have to make this ticket again. It is not resolved unfortunately.
Old one (closed prematurely): #5074
I made this fix in my code.
Now both areas — admin and frontend (same PHP version in use) — display this error.

OC 2.3.0.2
PHP 5.6.28


Session Support enabled
Registered save handlers files user redis
Registered serializer handlers php_serialize php php_binary
session.auto_start	Off
session.cache_expire	180
session.cache_limiter	nocache
session.cookie_domain	no value
session.cookie_httponly	Off
session.cookie_lifetime	0
session.cookie_path	/
session.cookie_secure	Off
session.entropy_file	no value
session.entropy_length	0
session.gc_divisor	100
session.gc_maxlifetime	1440
session.gc_probability	1
session.hash_bits_per_character	4
session.hash_function	0
session.name	PHPSESSID
session.referer_check	no value
session.save_handler	files
session.save_path	/***/***/tmp (* the directory is writable by apache)
session.serialize_handler	php
session.upload_progress.cleanup	On
session.upload_progress.enabled	On
session.upload_progress.freq	1%
session.upload_progress.min_freq	1
session.upload_progress.name	PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix	upload_progress_
session.use_cookies	On
session.use_only_cookies	On
session.use_strict_mode	Off
session.use_trans_sid	0

@GasparSukk

The old version 2.2.0.0 works.

@arnisjuraga

By the way, wild guess — do you have Compression enabled?
System > Settings > edit > Server tab

Output Compression Level — is it something more than 0?

@GasparSukk

@b3rend

Any ideas? I have the exact same issue and a fix a nowhere to be found.

@ayoeng

I have the same problem with php7. I can not install the oc

@danielkerr

fixed in 3.0

just replace and createsid() lines with

		if (function_exists('random_bytes')) {
			$session_id = substr(bin2hex(random_bytes(26)), 0, 26);
		} else {
			$session_id = substr(bin2hex(openssl_random_pseudo_bytes(26)), 0, 26);
		}

Following small piece of code comes handy whenever you are working for a J2EE web application in JSP/Servlet/Struts/JSF or any Servlet oriented web framework.
A lot of time we have to handle session errors in such applications and redirect user to particular error page. Generally user is redirected to the login page where she can giver her credential and log in the application again.
In my previous post, I wrote about handling session errors and other server errors at client side using AJAX. But for doing this still we have to handle the session errors first at server side. Let us see how we can track user session using Servlet Filter and redirect her to login page if session is already invalidated. We will induce session tracking facility to our web project (for this tutorial, I am using normal JSP web application in Eclipse).
[ad#blogs_content_inbetween]

Step 1: Create Servlet Filter to track Session

Create a package to place our session filter (in this case net.viralpatel.servlet.filter) and create a Java class SessionFilter. session-handle-servlet-filter Copy following code in the Java file.

package net.viralpatel.servlet.filter; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class SessionFilter implements Filter { private ArrayList<String> urlList; public void destroy() { } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String url = request.getServletPath(); boolean allowedRequest = false; if(urlList.contains(url)) { allowedRequest = true; } if (!allowedRequest) { HttpSession session = request.getSession(false); if (null == session) { response.sendRedirect("index.jsp"); } } chain.doFilter(req, res); } public void init(FilterConfig config) throws ServletException { String urls = config.getInitParameter("avoid-urls"); StringTokenizer token = new StringTokenizer(urls, ","); urlList = new ArrayList<String>(); while (token.hasMoreTokens()) { urlList.add(token.nextToken()); } } }

Code language: Java (java)

The init() method will get called by the servlet container and will get FilterConfig object as arguement. From this config object, we read the init parameters. We will see shortly what parameters do we passed in filter. The doFilter() method will be called for each request of our application. Hence we can check the session in this method and see if it is valid. From init() method, we had generated a list of pages (urls) that were having access although the session is null. Index pages, error pages and other pages that you think user can access without logging in should be specified in this list. In doFilter() method, you will notice one response.sendRedirect. I have redirected my user to index.jsp page if session is not valid. You can give any landing URL that you want your user to go when session is not valid. Alternatively you may want to create a JSON response and send it to client if you think the request was originated from AJAX.

Step 2: Specify filter entry in Web.xml deployment descriptor

Copy following entry in your application’s Web.xml file.

<filter> <filter-name>SessionFilter</filter-name> <filter-class> net.viralpatel.servlet.filter.SessionFilter </filter-class> <init-param> <param-name>avoid-urls</param-name> <param-value>index.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>SessionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

Code language: HTML, XML (xml)

We have specified the filter in web.xml file which will get called for url /*. You can configure the URL mapping like normal filters URL mapping. Also note that we have specified a parameter avoid-url in init-parameters of filter. The value of this parameter will be a comma separated paths that we do not want to apply session validations on. I have specified index.jsp, you can give more urls separated by comma.
e.g.
index.jsp, someAction.do, Request.jsp, Message.jsf

Хочу описать статью с возможными ошибками работы PHP и сессиями в Unix/Linux. Думаю многие сталкиваются и будет полезно знать как решать ту, или иную ошибку.

Обновлял заббикс и после его обновления, перестал корректно работать, посмотрел лог и увидел:

2017/12/08 21:15:48 [error] 40014#40014: *395 FastCGI sent in stderr: "PHP message: PHP Warning:  require_once(/etc/zabbix/web/maintenance.inc.php): failed to open stream: Permission denied in /usr/share/zabbix/include/classes/core/ZBase.php on line 269

-=== Ошибка 1 ===-

Можно увидить следующую ошибку:

Cannot start session without errors, please check errors given in your PHP and/or webserver log file and configure your PHP installation properly. Also ensure that cookies are enabled in your browser.

Возникла у меня при установке phpmyadmin.

Так же, если имеется cPanel, может возникнуть такая же ошибка, я описывал решение в моей статье:

ошибка в phpMyAdmin «Cannot start session without errors»

-=== Ошибка 2 ===-

При работе с апачем, я получил:

Warning: session_start() [function.session-start]: open(/var/lib/php/session/sess_eqbchncji8kj22f0iqa9g3v7u2, O_RDWR) failed: Permission denied (13) in /var/www/vhosts/httpdocs/index.php on line 6
Warning: Unknown: open(/var/lib/php/session/sess_eqbchncji8kj22f0iqa9g3v7u2, O_RDWR) failed: Permission denied (13) in Unknown on line 0
Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0

-=== Ошибка 3 ===-

Получил еще ошибку:

FastCGI sent in stderr: “PHP message: PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0” while reading upstream, client: 37.***.***.56, server: rtfm.co.ua, request: “POST /wp-admin/admin-ajax.php HTTP/1.1”, upstream: “fastcgi://127.0.0.1:9009”, host: “rtfm.co.ua”, referrer: “http://linux-notes.org/wp-admin/post.php?post=5496&action=edit&message=10”

Другие ошибки я буду добавлять по мере их возникновения.

Решения ошибок работы с PHP сессиями в Unix/Linux

Ну что, пришли к решению. Первое что необходимо сделать, — так проверить путь куда сохраняются сессии, для этого, выполните:

$ php -i |grep save_path

session.save_path => /var/lib/php/session => /var/lib/php/session

Как видно у меня этот путь рассположен в /var/lib/php/session директории.

Проверим права на данную директорию:

# ls -alh /var/lib/php/session

Смотрим от какого юзера идет выполнение php кода:

# ps aux |grep php-fpm

PS: Или, можно зайти в ваш пул php-fpm и найти пользователя от которого он запущен!

Решение довольно примитивное. Для начала, стоит создать папку под использующие сессии (если ее нет еще) и выставить права:

# mkdir /var/lib/php/session
# chmod 1777 /var/lib/php/session

И так же, выставляем владельца и группу:

# chown root:www /var/lib/php/session
# chown -R www: /var/cache/nginx

ИЛИ:

# chmod o+rw /var/lib/php/session

Потом, открываем ваш php.ini и находим строку:

;session.save_path = "/tmp"

И нужно выполнить расскоменчивание данной строки.

PS: Возможно, нужно будет выставить права и владельца!

Если вы используете выделенные пулы под свои php- проекты, то стоит поискать данную строку в:

# grep -lR 'php_value' /etc/php-fpm.d

Если покажет файлы, то стоит посмотреть привести к:

[...]
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session
[...]

Перезапускаем php-fpm службу:

# service php-fpm restart

Для апача, следуюет указать следующие строки:

php_value session.save_handler "files"
php_value session.save_path    "/var/lib/php/session"

а поиск файла можно сделать так:

# grep -lR 'php_value' /etc/

И тоже, выполнить перезапуск службы:

# service httpd restart

Вот и все решение! А у меня на этом статья «Ошибки работы с PHP сессиями в Unix/Linux» завершена.

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

Введение

SessionHandler это специальный класс, который может использоваться для
дополнения внутреннего обработчика сессий PHP путём создания дочерних классов от этого.
Существует семь методов, которые являются обёртками над семью внутренними обработчиками хранения
данных сессии (open, close, read,
write, destroy, gc и
create_sid). По умолчанию этот класс оборачивает все внутренние
обработчики хранения сессии, определённые в опции конфигурации session.save_handler.
Эта опция по умолчанию имеет значение files.
Другие внутренние обработчики сессий предоставляются PHP-модулями, такими как
SQLite (sqlite), Memcache (memcache)
и Memcached (memcached).

Экземпляр класса SessionHandler может устанавливаться в
качестве обработчика сессии посредством вызова функции session_set_save_handler().
В этом случае он станет обёрткой существующего внутреннего обработчика.
Классы, расширяющие SessionHandler позволят переопределить
методы обработчика сессии или перехватить/отфильтровать их путём вызова
родительских методов-обёрток внутреннего обработчика сессий PHP.

Это позволит вам, к примеру, перехватить методы read и
write для шифровки/дешифровки данных сессии и передачи
результата родительскому классу и от него. Или, к примеру, вы можете полностью
переопределить такой метод как callback-функция сборщика мусора (gc).

Так как SessionHandler является обёрткой над стандартным
внутренним обработчиком сессии, то пример, приведённый выше про шифровку данных
может быть применён к любому внутреннему обработчику сессии даже без понимания
внутреннего устройства процесса работы сессии.

Для использования этого класса, во-первых, установите обработчик, который вы хотите
дополнить используя session.save_handler.
Далее передайте экземпляр класса SessionHandler или одного из
классов, расширяющих его функции session_set_save_handler().

Обратите внимание, что callback-методы этого класса предназначены для внутреннего вызова PHP
и не предназначены для вызова из кода пользовательского пространства.
Возвращаемые значения одинаково обрабатываются внутри PHP.
Дополнительную информацию о работе с сессией можно узнать
из описания функции session_set_save_handler().

Обзор классов

public destroy(string $id): bool

public gc(int $max_lifetime): int|false

public open(string $path, string $name): bool

public read(string $id): string|false

public write(string $id, string $data): bool

}

Внимание

Этот класс предназначен для расширения текущего внутреннего обработчика сессии PHP.
При этом, если вам нужно написать собственный обработчик, то необходимо написать
собственную реализацию интерфейса SessionHandlerInterface
вместо расширения класса SessionHandler.

Пример #1
Использование SessionHandler для того, чтобы добавить
шифровку данных ко внутреннему обработчику сессий PHP.


<?php/**
* расшифровать данные, используя алгоритм AES 256
*
* @param data $edata
* @param string $password
* @return расшифрованные данные
*/
function decrypt($edata, $password) {
$data = base64_decode($edata);
$salt = substr($data, 0, 16);
$ct = substr($data, 16);$rounds = 3; // зависит от длины ключа
$data00 = $password.$salt;
$hash = array();
$hash[0] = hash('sha256', $data00, true);
$result = $hash[0];
for (
$i = 1; $i < $rounds; $i++) {
$hash[$i] = hash('sha256', $hash[$i - 1].$data00, true);
$result .= $hash[$i];
}
$key = substr($result, 0, 32);
$iv = substr($result, 32,16);

return

openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv);
}
/**
* зашифровать данные алгоритмом AES 256
*
* @param data $data
* @param string $password
* @return base64 зашифрованные данные
*/
function encrypt($data, $password) {
// Генерация криптографически безопасной случайной соли с помощью функции random_bytes()
$salt = random_bytes(16);$salted = '';
$dx = '';
// Ключ соли (32) и вектор инициализации (16) = 48
while (strlen($salted) < 48) {
$dx = hash('sha256', $dx.$password.$salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32,16);$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv);
return
base64_encode($salt . $encrypted_data);
}

class

EncryptedSessionHandler extends SessionHandler
{
private
$key;

public function

__construct($key)
{
$this->key = $key;
}

public function

read($id)
{
$data = parent::read($id);

if (!

$data) {
return
"";
} else {
return
decrypt($data, $this->key);
}
}

public function

write($id, $data)
{
$data = encrypt($data, $this->key);

return

parent::write($id, $data);
}
}
// Здесь мы перехватываем встроенный обработчик 'files', но можно использовать любой другой
// обработчик, например 'sqlite', 'memcache' или 'memcached',
// которые предоставлены модулями PHP.
ini_set('session.save_handler', 'files');$key = 'secret_string';
$handler = new EncryptedSessionHandler($key);
session_set_save_handler($handler, true);
session_start();// устанавливаем и получаем значения из $_SESSION

Замечание:

Так как методы этого класса предназначены для внутренних вызовов из PHP, как часть
нормального процесса работы сессий, вызовы родительских методов из дочернего класса
(иными словами «родных» обработчиков) будет возвращать false до тех пор,
пока сессия не будет запущена (автоматически или прямым вызовом session_start()).
Это важный момент для понимания, особенно при тестировании, где методы класса
могут быть вызваны вручную.

Содержание

  • SessionHandler::close — Закрывает сессию
  • SessionHandler::create_sid — Возвращает новый идентификатор сессии
  • SessionHandler::destroy — Уничтожает сессию
  • SessionHandler::gc — Очищает старые сессии
  • SessionHandler::open — Инициализирует сессию
  • SessionHandler::read — Считывает данные сессии
  • SessionHandler::write — Записывает данные сессии

rasmus at mindplay dot dk

7 years ago


As the life-cycle of a session handler is fairly complex, I found it difficult to understand when explained using just words - so I traced the function calls made to a custom SessionHandler, and created this overview of precisely what happens when you call various session methods:

https://gist.github.com/mindplay-dk/623bdd50c1b4c0553cd3

I hope this makes it considerably easier to implement a custom SessionHandler and get it right the first time :-)


tony at marston-home dot demon dot co dot uk

4 years ago


Your custom session handler should not contain calls to any of the session functions, such as session_name() or session_id(), as the relevant values are passed as arguments on various handler methods. Attempting to obtain values from alternative sources may not work as expected.

saccani dot francesco dot NOSPAM at gmail dot com

2 years ago


I made this gist to provide a complete overview of the PHP session handler life cycle updated to version 7.0 or above. In particular, I wanted to emphasize what methods and in what order are called when the native PHP functions are used for session management.

https://gist.github.com/franksacco/d6e943c41189f8ee306c182bf8f07654

I hope this analysis will help all the developers interested in understanding in detail the native session management performed by PHP and what a custom session handler should do.
Any comment or suggestion is appreciated.


tuncdan dot ozdemir dot peng at gmail dot com

5 days ago


Those who are planning to implement your own SessionHandler, let's say using a Database system, please make sure your 'create_sid' method creates a new record in your database with empty string '' as your 'data' using the new session ID created, otherwise when 'read' method is called (which is always called no matter if it is a brand new session or not), you will get an error because there is no record with that session ID yet.  The funny part is that the error you get will sound like PHP is trying open the session on your local drive (coming from your .ini file).

tuncdan dot ozdemir dot peng at gmail dot com

6 days ago


The best way to set up your own session handler is to extend the native SessionHandler (override the 7 methods + constructor as per your need, keeping the same signatures).  Optionally, you can also implement SessionUpdateTimestampHandlerInterface if you plan to use 'lazy_write':

Option 1:

class MyOwnSessionHandler extends SessionHandler { ..... }

Option 2:

class MyOwnSessionHandler extends SessionHandler implements SessionUpdateTimestampHandlerInterface { ..... }

I would NOT recommend to do this:

class MyOwnSessionHandler implements SessionHandlerInterface, SessionIdInterface, SessionUpdateTimestampHandlerInterface { ... }

If you are curious, here are the methods called in the order (using PHP 8.2 with XAMPP v3.3.0 on Windows 11 64-bit):

- open (always called)

- validateId and/or create_sid:

    validateId is called if you implement SessionUpdateTimestampHandlerInterface.  If validation fails, create_sid is called.    

    create_sid is called if a new session ID is needed: new session, etc.

- read (always called)

- write OR updateTimestamp OR destroy:

    if you call 'destroy', neither 'write' or 'updateTimestamp' is called,

    if you have the 'lazy_write' on AND implemented SessionUpdateTimestampHandlerInterface,
    then 'updateTimestamp' is called instead of 'write' if nothing changes.

- close (always called)


jeremie dot legrand at komori-chambon dot fr

6 years ago


Here is a wrapper to log in a file each session's operations. Useful to investigate sessions locks (which prevent PHP to serve simultaneous requests for a same client).
Just change the file name at the end to dump logs where you want.

class DumpSessionHandler extends SessionHandler {
    private $fich;

    public function __construct($fich) {
        $this->fich = $fich;
    }

    public function close() {
        $this->log('close');
        return parent::close();
    }

    public function create_sid() {
        $this->log('create_sid');
        return parent::create_sid();
    }

    public function destroy($session_id) {
        $this->log('destroy('.$session_id.')');
        return parent::destroy($session_id);
    }

    public function gc($maxlifetime) {
        $this->log('close('.$maxlifetime.')');
        return parent::gc($maxlifetime);
    }

    public function open($save_path, $session_name) {
        $this->log('open('.$save_path.', '.$session_name.')');
        return parent::open($save_path, $session_name);
    }

    public function read($session_id) {
        $this->log('read('.$session_id.')');
        return parent::read($session_id);
    }

    public function write($session_id, $session_data) {
        $this->log('write('.$session_id.', '.$session_data.')');
        return parent::write($session_id, $session_data);
    }

    private function log($action) {
        $base_uri = explode('?', $_SERVER['REQUEST_URI'], 2)[0];
        $hdl = fopen($this->fich, 'a');
        fwrite($hdl, date('Y-m-d h:i:s').' '.$base_uri.' : '.$action."n");
        fclose($hdl);
    }
}
ini_set('session.save_handler', 'files');
$handler = new DumpSessionHandler('/path/to/dump_sessions.log');
session_set_save_handler($handler, true);


wei dot kavin at gmail dot com

3 years ago


php -S localhost:8000 -t foo/

touch index.php

vi index.php
============================================================
class NativeSessionHandler extends SessionHandler
{
    public function __construct($savePath = null)
    {
        if (null === $savePath) {
            $savePath = ini_get('session.save_path');
        }

        $baseDir = $savePath;

        if ($count = substr_count($savePath, ';')) {
            if ($count > 2) {
                throw new InvalidArgumentException(sprintf('Invalid argument $savePath '%s'', $savePath));
            }

            // characters after last ';' are the path
            $baseDir = ltrim(strrchr($savePath, ';'), ';');
        }

        if ($baseDir && !is_dir($baseDir) && !@mkdir($baseDir, 0777, true) && !is_dir($baseDir)) {
            throw new RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $baseDir));
        }

        ini_set('session.save_path', $savePath);
        ini_set('session.save_handler', 'files');
    }
}

$handler = new NativeSessionHandler("/var/www/foo");
session_set_save_handler($handler, true);
session_start();
$a = $handler->write("aaa","bbbb");var_dump($a);exit;

============================================================

output:bool(false)


Session Handler Error


I recently dropped cloudflare and am using my cloud WAF only. We are getting the kinks of the settings but I keep seeing this in my error log:

2017-03-05 8:30:55 — PHP Warning: SessionHandler::write(): open(/tmp/sess_90265767b4c4fe01ab2cadbda, O_RDWR) failed: Permission denied (13) in /home/xxxxxxxx/public_html/system/library/session/native.php on line 21

Any idea what this session handler error is?


Self Taught Opencart User & Developer Since 2010.


User avatar


Re: Session Handler Error


Post

by Qphoria » Mon Mar 06, 2017 11:04 am

The session is the server’s version of a «cookie». It stores information about the customer’s browsing session on your site so that it can save certain details like their cart and any user-specific variables related to the customer during the shopping process. This data is saved to a randomly generated file on your server, usually in a folder that you never have to look at or worry about. But occasionally this folder can run out of space or have the wrong permissions due to a mistake that your host made. So to fix it, just contact your webhost and tell them the error and they will fix it. This isn’t related to OpenCart or any platform, it is strictly a server storage error.


Image


User avatar


Re: Session Handler Error


Post

by Rainforest » Mon Mar 06, 2017 8:55 pm

Thank you, Q.
Always appreciate your help!


Self Taught Opencart User & Developer Since 2010.


User avatar


Re: Session Handler Error


Post

by panagos » Mon Mar 06, 2017 9:41 pm

Check your apache php.ini’s session.save_path configuration setting. You need to make sure that the folder in question is writeable.


Re: Session Handler Error


Post

by sicotommo » Wed Jan 24, 2018 10:28 pm

Hi Guys

Just come across this issue myself — not sure why it came up either. Using OC2.3.0.2 which was installed as an upgrade of 1.5 in mid December. It appears all the session files created were stored since around then. Should that happen? Should the sessions be removed after a time period?

Any info would be great as I want to get on top of this and make sure it doesn’t re-occur.

Thanks for you help.

Regards
Simon

Who is online

Users browsing this forum: No registered users and 12 guests

0 Пользователей и 1 Гость просматривают эту тему.

  • 24 Ответов
  • 26442 Просмотров

Переустановил OpenServer. Пробовал запустить на нем сайт со старого, но выдает ошибку

Warning: session_start(): Failed to read session data: user (path: e:/openserver/ospanel/userdata/temp/) in E:OpenServerOSPaneldomainsDomkomexprlibrariesjoomlasessionhandlernative.php on line 260
Error: Failed to start application: Failed to start the session

В чем может быть проблема ?

Нет соединения с базой данных. Проверьте привилегии и соответствие юзера БД.

А где их можно посмотреть ?

а базу данных перед установкой бекапили?

а базу данных перед установкой бекапили?

У меня такая же фигня после бэкапа, что делать?
Mar 26 12:41:40 vh164 apache_error: sharik-rybinsk.ru [Tue Mar 26 12:41:40 2019] [warn] [pid 5943] sapi_apache2.c(362): [client 92.53.115.234:54836] PHP Warning: session_start(): Failed to read session data: user (path: /tmp) in /home/c/cx43819/sharik-rybinsk.ru/public_html/libraries/joomla/session/handler/native.php on line 260

После восстановления с бекапа?

в конфигурационном файле configuration.php попробуйте запись сессии с файла на бд переделать

public $session_handler = 'database';

в конфигурационном файле configuration.php попробуйте запись сессии с файла на бд переделать

public $session_handler = 'database';

Там так и прописано

После восстановления с бекапа?

да

Всем спасибоВсё заработало. Поменял путь к tmp на правильный и изменил версию php на более раннюю

У меня была ошибка «Error: Failed to start application: Failed to start the session», при попытке открыть страницу сайта на Joomla.
Возникла после клонирования файлов и базы на другой сервер и обновления Joomla до последней версии. Началась с того, что я заметил, что в админке в настройках базы данных указан адрес старого хоста. Когда я изменил его на новый, то сохранить настройки не удалось. Попробовал изменить хост в файле configuration.php, но тут то было. Была та же ошибка. Менял хост на ‘localhost’, но видимо наложилось, что я обновлялся и старая база на localhost не подцепилась, либо были какие-то еще проблемы, в общем, ошибка осталась. Пол дня проверял все подряд (PHP, MySQL, apache). Потом скачал полный дистрибутив новой Joomla 3.9.14. Разархивировал его, установил. Сайт на новой joomle заработал. Взял конфигурационный файл из нее, закинул его в клонированную базу и изменил некоторые параметры на нужные. (Кстати заметил что в новом установленном конфиге $host = ‘localhost’). И ура! Сайт заработал.

Возможно, кому то поможет. На одном хостинге версия PHP 7.2 — сайт работает нормально, на другом та же 7.2 выдает ошибку
libraries Joomla session handler native.php on line 260 error failed to start application failed to start the session
мне помогло переключение на версию 7.1
не знаю как, мистика может, или на том хостинге семерка как то не так настроена, но вобщем фишка была именно в этом

Записан

Разработка сайтов любой сложности, на Joomla 3.9-4.x и не только на ней. Пишу компоненты, модули и плагины на заказ. Переношу сайты с ветки 2.5.х на 4-ю версию Joomla. Пишу любые скрипты и интерфейсы.

День добрый! Столкнулся с такой проблемой: при переносе сайта на хостинг(timeweb) c OpenServera ни сайт, ни админка не открываются, вместо этого белый экран с надписью Error. При включении $error_reporting = ‘development’; в config выводится следующая ошибка: Warning: session_start(): Failed to read session data: user (path: /tmp) in /home/c/***/***/public_html/libraries/joomla/session/handler/native.php on line 260. Error: Failed to start application: Failed to start the session.

выводится следующая ошибка: Warning: session_start(): Failed to read session data: user (path: /tmp) in /home/c/***/***/public_html/libraries/joomla/session/handler/native.php on line 260. Error: Failed to start application: Failed to start the session.

Проверьте подключение к базе данных и права юзера БД .

Хотя может и права на папку
Не работает сайт на локалке

как переносили

через filezilla напрямую, ну и базу данных по стандарту

Проверьте подключение к базе данных и права юзера БД .

Хотя может и права на папку
Не работает сайт на локалке

Права менял по-разному, не помогло (хотя не пробовал задавать 755 для всех файлов пути /libraries/joomla/session/handler/native.php)
Права администратора к базе (до этого сайт переносил, проблем не было)

А как можно проверить само подключение к БД?

« Последнее редактирование: 18.06.2020, 16:56:53 от Kayle »

Записан

Столкнулся с такой же проблемой, причина оказалась в том, что MySQL-сервер был реализован через докер, а файлы были вне докера (как обычно). Соответственно, пользователь MySQL не имел прав на доступ к базе (были права на подключение только через localhost). Дал права на подключение из любого места — %, сразу все заработало.
Но это, конечно, не дело — так оставлять, надо использовать либо БД без докера, либо, чтобы файлы сайта тоже там же жили.

А как можно проверить само подключение к БД?

Дать пользователю БД права супер-юзера с подключением из любого места и посмотреть, что будет в этом случае (если ваш хостинг дает такие возможности).

Проверить права юзера:
SHOW GRANTS FOR ‘user’@’%’ — подключение из любого места

SHOW GRANTS FOR ‘user’@’localhost’ — подключение только с сервера

Дать юзеру супер-мега права (нужно предварительно залогиниться таким же крутым юзером, например, рутом):
GRANT ALL PRIVILEGES ON *.* TO ‘user’@’%’ IDENTIFIED BY PASSWORD ‘*C8516ХХХХХХХХХХХХХХХХХХХХХХХХХХХХХХХХBE’ WITH GRANT OPTION

—————
соответственно, вместо user пишите свой username, вместо C8516ХХХХХХХХХХХХХХХХХХХХХХХХХХХХХХХХBE — свой хэш пароля

Судя по всему с базой все нормально. Прописал SQL-запрос SHOW GRANTS FOR ‘user’@’localhost’ в PMA, запрос успешно выполнился:

GRANT USAGE ON *.* TO ‘***’@’localhost’ IDENTIFIED BY PASSWORD <secret>
GRANT ALL PRIVILEGES ON `***`.* TO ‘***’@’localhost’

Вообще на локальном сервере все работает стабильно без ошибок, возможно ли что это может связано с каким-то компонентом?

посмотрите логи ошибок сайта в папке logs

Обычно она расположена на 2 уровня выше директриии вашего сайта (хотя точный путь зависит от хостера):

/logs/вашсайт.ру.error.log
/www/вашсайт.ру/index.php и др. файлы и папки сайта тут

Установите чистую Joomla и проверьте .

Тоже столкнулся с такой  ошибкой после установки последней версии Openserver и переноса сайта со старой. Все оказалось банально и просто. В отличие от предыдущих версий, когда для доступа к БД в phpMyAdmin нужно было только имя пользователя root без пароля, теперь нужно писать имя пользователя MySQL и пароль MySQL. Соответственно, после переноса надо открыть файл configuration.php и записать:
public $user = ‘mysql’;
public $password = ‘mysql’;
 У меня после этого все заработало.

В этот раз при возникновении данной ошибки помогло изменение в конфиге на:
$host = ‘localhost’;

День добрый! Столкнулся с такой проблемой: при переносе сайта на хостинг(timeweb) c OpenServera ни сайт, ни админка не открываются, вместо этого на каких биржах торгуют трейдеры https://expert.com.ua/145531-na-kakix-birzhax-torguyut-kriptovalyutoj-trejdery.html с надписью Error. При включении $error_reporting = ‘development’; в config выводится следующая ошибка: Warning: session_start(): Failed to read session data: user (path: /tmp) in /home/c/***/***/public_html/libraries/joomla/session/handler/native.php on line 260. Error: Failed to start application: Failed to start the session.

Как по итогу решил проблему?

Как по итогу решил проблему?

У меня было
Warning: session_start(): Failed to read session data: user (path: c:/openserver/userdata/temp) in C:openserverdomainslocalhostlibrariesjoomlasessionhandlernative.php on line 259
Error displaying the error page: Application Instantiation Error: Failed to start the session

перенос был с другого пк название диска изменилось, изначально скопировал полностью и поверх установил опенсервер.
ошибка заключалась в том, что после установки поверх не было пользователей бд кроме root и в базе таблица с сессией не работала.

Решил так:
поставил чистую версию openserver, скопировал данные сайта в domains
Исправил пути в переменных log_path и tmp_path в файле C:openserverdomainslocalhostconfiguration.php
и скопировал содержимое файлов папки с базой данных в C:openserveruserdata* в моём случае была папка MariaDB-10.5

« Последнее редактирование: 22.04.2022, 10:43:13 от omnipresent »

Записан

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Handjet ebs 250 error
  • Handbrake ошибка ситроен
  • Handbrake on ошибка пежо 307
  • Hamming error correcting code
  • Hamming code error correction and error detection

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии