开发WordPress网站与配套Android应用:能否通过PHP脚本获取wp_loggedin值并返回至应用?
Hey there! Great question—yes, you absolutely can build an independent PHP script to check a user's WordPress login status and send that data back to your Android app. Let's break this down into actionable steps with code examples to make it work reliably.
Step 1: Create the PHP Script (Integrated with WordPress)
First, your script needs to tap into WordPress's core functions to accurately check login status. You can't just read the wp_loggedin cookie directly (it's encrypted and tied to WordPress's session system), so we'll load WordPress's core to use its built-in is_user_logged_in() function.
Create a file like check-login-status.php in your WordPress root directory, with this code:
<?php // Load WordPress core to access authentication functions require_once('wp-load.php'); // Optional but highly recommended: Add nonce verification to prevent CSRF attacks $nonce = isset($_GET['nonce']) ? sanitize_text_field($_GET['nonce']) : ''; if (!wp_verify_nonce($nonce, 'check_login_status')) { wp_send_json(['logged_in' => false, 'error' => 'Invalid security token'], 403); exit; } // Check if the user is logged in $is_logged_in = is_user_logged_in(); // Set CORS header (adjust the origin to your Android app's domain for production) header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); // Return the login status as JSON (easy for Android to parse) wp_send_json([ 'logged_in' => $is_logged_in, 'user_id' => $is_logged_in ? get_current_user_id() : null ]); ?>
Key Notes:
- WordPress Core Integration:
require_once('wp-load.php')pulls in all WordPress functions so we can useis_user_logged_in()and nonce tools. - Nonce Security: The nonce ensures only legitimate requests from your app (not random bots) can use this endpoint. Generate the nonce in WordPress (e.g., with
wp_create_nonce('check_login_status')) and pass it from your Android app to the script. - CORS: The
Access-Control-Allow-Originheader lets your Android app (running on a different "origin" than your WordPress site) make requests to this script. For production, replace*with your app's specific domain or package-related origin.
Step 2: Call the Script from Your Android App
On the Android side, you'll need to send an HTTP request to your PHP script, include the user's WordPress session cookie (to maintain login state), and parse the JSON response.
Here's a quick example using OkHttp (a popular Android HTTP client):
import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.json.JSONObject; import java.io.IOException; // Initialize OkHttp client OkHttpClient client = new OkHttpClient(); // Fetch the nonce from your WordPress site first (e.g., via a login response or dedicated endpoint) String securityNonce = "your_fetched_nonce_here"; // Get this cookie from the login response when the user signs into WordPress via your app String wordpressSessionCookie = "wordpress_logged_in_yourhash=your_session_value"; // Build the request Request request = new Request.Builder() .url("https://your-wordpress-domain.com/check-login-status.php?nonce=" + securityNonce) .addHeader("Cookie", wordpressSessionCookie) .build(); // Execute the request asynchronously client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // Handle network errors (e.g., show a toast to the user) e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String jsonString = response.body().string(); try { JSONObject jsonResponse = new JSONObject(jsonString); boolean isLoggedIn = jsonResponse.getBoolean("logged_in"); Integer userId = jsonResponse.isNull("user_id") ? null : jsonResponse.getInt("user_id"); // Update your app's UI or logic with the login status runOnUiThread(() -> { if (isLoggedIn) { // User is logged in—show personalized content, dashboard, etc. } else { // User is logged out—redirect to login screen or show guest content } }); } catch (Exception e) { e.printStackTrace(); } } } });
Key Notes for Android:
- Session Cookie: When the user logs into WordPress via your app (e.g., using WP's REST API login endpoint or a custom login form), save the
wordpress_logged_in_*cookie from the response. This cookie must be included in every request to thecheck-login-status.phpscript to identify the user. - JSON Parsing: The script returns JSON, which is easy to parse on Android using
JSONObjector libraries like Gson/Moshi for more complex data structures. - Nonce Handling: Fetch the nonce from your WordPress site (e.g., during login) and include it in the request to pass the security check.
Step 3: Additional Security & Best Practices
- Avoid Direct Cookie Reading: Never try to decrypt the
wp_loggedincookie manually—WordPress's authentication system handles this securely viais_user_logged_in(). - Restrict CORS Origins: In production, replace
*in the CORS header with your Android app's specific origin (e.g.,https://your-app-domain.comorapp://your-package-namedepending on your setup). - Use HTTPS: Always serve your WordPress site and PHP script over HTTPS to encrypt data between the app and server.
内容的提问来源于stack exchange,提问作者Wali Muhammad Khubaib

