通过编程方式模拟另一个用户而不会导致当前登录的用户注销

drupal.stackexchange https://drupal.stackexchange.com/questions/315

  •  16-10-2019
  •  | 
  •  

$user, ,执行自己的代码,并还原 $user 如果发生错误,则不会导致当前用户被记录吗?

有帮助吗?

解决方案

drupal_cron_run() 函数为此提供了一个完美的示例,因为每当运行cron时,它将当前用户更改为匿名,然后在完成后将其切换。

// Prevent session information from being saved while doing funky stuff.
$original_session_state = drupal_save_session();
drupal_save_session(FALSE);

// Force the current user to anonymous to ensure consistent permissions on
// funky stuff runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user(); // Or use user_load() for a non-anonymous user.

// Do funky stuff here...

// Restore the user.
$GLOBALS['user'] = $original_user;
drupal_save_session($original_session_state);
许可以下: CC-BY-SA归因
scroll top