Laravel登录会话中单词内数字位置随机化实现方案咨询
Hey there! Let's walk through a solid solution for your problem—randomly picking a digit position from a word in a Laravel session, asking the user to input that digit, and keeping the position consistent throughout the session.
核心思路
The key here is to:
- Extract all positions of digits in your target word.
- Randomly select one position and store it in the user's session (so it stays the same until the session ends or we clear it).
- Show the user which position they need to input, then validate their answer against the correct digit at that position.
Step 1: Generate & Store Random Digit Position in Session
First, we'll extract all digit positions from your word and save a random one to the session. This should run once per session (when the user first lands on the verification page, for example).
// In your controller method (e.g., showVerificationPage) public function showVerificationPage() { $targetWord = "Larav3lR0cks123"; // Replace with your actual word // Collect all positions where there's a digit (adjust index to start at 1 if you prefer) $digitPositions = []; for ($i = 0; $i < strlen($targetWord); $i++) { if (is_numeric($targetWord[$i])) { $digitPositions[] = $i; // Use $i + 1 if you want positions to start at 1 instead of 0 } } // Only set the random position if it doesn't already exist in the session if (!session()->has('random_digit_position')) { // Pick a random position from our collected array $selectedPosition = $digitPositions[array_rand($digitPositions)]; session()->put('random_digit_position', $selectedPosition); // Store the target word too, so we can validate later session()->put('target_word', $targetWord); } return view('verification'); }
Step 2: Display the Verification Form to the User
In your Blade view, we'll pull the session data to tell the user which digit position they need to input.
<!-- resources/views/verification.blade.php --> <form method="POST" action="{{ route('verify.digit') }}"> @csrf <div class="mb-3"> <p>Please enter the digit at position {{ session('random_digit_position') + 1 }} in this word: <strong>{{ session('target_word') }}</strong></p> <input type="text" name="user_digit" class="form-control" required maxlength="1"> @error('user_digit') <div class="text-danger">{{ $message }}</div> @enderror </div> <button type="submit" class="btn btn-primary">Submit</button> </form>
(Note: I added +1 to the position here because most users expect positions to start at 1, not 0—adjust this if you want to use 0-indexed positions.)
Step 3: Validate the User's Input
Next, create a controller method to check if the user's input matches the correct digit at the stored position.
// In your controller public function verifyDigit(Request $request) { // Validate the input is a single digit $validated = $request->validate([ 'user_digit' => 'required|numeric|digits:1', ]); // Fetch session data $targetWord = session('target_word'); $selectedPosition = session('random_digit_position'); $correctDigit = $targetWord[$selectedPosition]; if ($validated['user_digit'] == $correctDigit) { // Success! Clear the session data (optional, but clean) session()->forget(['random_digit_position', 'target_word']); return redirect()->route('dashboard')->with('success', 'Verification passed!'); } // If incorrect, send user back with error return back()->withErrors(['user_digit' => 'That digit is wrong—please try again.']); }
Why Your strpos Approach Didn't Work
The issue with using strpos alone is that it only finds the first occurrence of a specific character. To make this work randomly, you need to first collect all digit positions, then pick one at random and store it in the session. Without storing it in the session, you'd generate a new random position on every request, which would make validation impossible (since the position would change between showing the form and submitting it).
Extra Notes
- Handle edge cases: Add a check to make sure
$digitPositionsisn't empty (in case your word has no digits) to avoid errors witharray_rand. - Session persistence: The position will stay the same until the user's session ends (e.g., they close their browser) or you explicitly clear the session keys.
- Customization: Adjust the target word to come from a database, config, or wherever your application needs it.
内容的提问来源于stack exchange,提问作者thedream3

