PHP/Laravel中不依赖file_get_contents()和curl读取同服务器JSON文件的替代方案
file_get_contents & curl) Hey there! Let's break this down: since your JSON file lives on the same server as your Laravel code, you don't need to rely on HTTP-based methods like file_get_contents() with a URL or curl at all. Those methods are failing because they're trying to make a full network request (even to the same server), which is likely blocked by your client's server firewall, SELinux policies, or web server configuration—hence the "connection reset by peer" errors.
Below are reliable, file-system-based alternatives that skip the network layer entirely:
1. Use Laravel's Built-in Storage Facade
Laravel's Storage system is clean, handles path management automatically, and integrates seamlessly with your app. Depending on where your JSON file is stored:
If the file is in storage/app/:
use Illuminate\Support\Facades\Storage; try { $jsonContent = Storage::get('your-file.json'); $data = json_decode($jsonContent, true); // Convert to associative array } catch (\Illuminate\Contracts\Filesystem\FileNotFoundException $e) { // Handle missing file error dd("File not found: " . $e->getMessage()); }
If the file is in public/:
Use the public disk (run php artisan storage:link first if you need public web access to the file):
use Illuminate\Support\Facades\Storage; $jsonContent = Storage::disk('public')->get('your-file.json'); $data = json_decode($jsonContent, true);
2. Native PHP File Reading with fopen() + fread()
If you prefer a low-level, framework-agnostic approach, use these native PHP functions to read the file directly:
// Use Laravel's helper functions to get absolute paths (avoids relative path bugs) $filePath = base_path('your-file.json'); // For files in your project root // OR $filePath = public_path('your-file.json'); // For files in public/ // OR $filePath = storage_path('app/your-file.json'); // For files in storage/app/ $fileHandle = fopen($filePath, 'r'); if ($fileHandle) { $jsonContent = fread($fileHandle, filesize($filePath)); fclose($fileHandle); $data = json_decode($jsonContent, true); } else { // Handle file open failure (check permissions!) dd("Unable to open file: " . $filePath); }
Critical Tips to Avoid Issues:
- Always Use Absolute Paths: Use Laravel's helper functions like
base_path(),public_path(), orstorage_path()to build file paths—relative paths can break depending on where your code is executed from. - Check File Permissions: Ensure the web server user (e.g.,
www-datafor Apache,nginxfor Nginx) has read access to the JSON file. Fix permissions with:chmod 644 /path/to/your-file.json - Why Your Original Methods Failed: When you use
file_get_contents($url)or curl to access a local file via HTTPS/HTTP, you’re triggering a full network loopback request. Client servers often block these for security, leading to the connection reset errors. Direct file reading skips this network layer entirely.
内容的提问来源于stack exchange,提问作者Saswat

