PHP结合.htaccess实现友好URL及URL传参异常后端解决方案
Hey there! Let's work through your friendly URL setup and fix that parameter issue you're hitting. Here's a step-by-step breakdown:
First, your current rewrite rule doesn't match your desired URL structure or target file. Let's adjust it to align with what you want (project-view/11042 pointing to project-view.php?id=11042):
If your .htaccess file is in the root directory (above the G-Zip folder):
RewriteEngine On # Handle project-view friendly URLs RewriteRule ^G-Zip/project-view/([0-9]+)/?$ /G-Zip/project-view.php?id=$1 [L,QSA,NC]
If your .htaccess file is inside the G-Zip folder:
RewriteEngine On # Handle project-view friendly URLs RewriteRule ^project-view/([0-9]+)/?$ project-view.php?id=$1 [L,QSA,NC]
- The
([0-9]+)captures numeric IDs, ensuring only valid project IDs are passed. QSApreserves any additional query parameters if needed,NCmakes the rule case-insensitive, andLstops processing further rules once this one matches.
Now, update your project-view.php to safely retrieve and validate the ID parameter—this will fix those variable anomalies you're seeing:
<?php // Validate the ID to avoid missing or invalid values if (!isset($_GET['id']) || !ctype_digit($_GET['id'])) { // Redirect to projects page or show an error if ID is invalid/missing header("Location: /G-Zip/Projects"); exit; } // Convert the ID to an integer to ensure it's a numeric value $projectId = (int)$_GET['id']; // Now use $projectId in your logic (e.g., database queries) // Important: Use prepared statements to prevent SQL injection! // Example: // $stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?"); // $stmt->execute([$projectId]); // $project = $stmt->fetch(); ?>
This validation ensures you never try to use an undefined or non-numeric ID, which was likely causing your variable issues.
Make sure you're linking to the friendly URL format from projects.php instead of the old query string version:
<?php // Example: Assume you have a project ID from your projects list $projectId = 11042; // Replace with your dynamic ID variable ?> <a href="/G-Zip/project-view/<?php echo htmlspecialchars($projectId); ?>">View Project</a>
Using htmlspecialchars() ensures the ID is escaped safely for the URL.
The most likely cause of your variable anomaly was that your original .htaccess rule pointed to view_project.php instead of project-view.php—so your actual project-view.php file was never receiving the id parameter. Fixing the rewrite rule and validating the parameter in PHP should resolve this completely.
内容的提问来源于stack exchange,提问作者George Albert

