Reputation: 125
I am trying to get content of a file with PHP. Then adding it inside a new file. I am using file_get_contents()
but it shows the error:
PHP Warning: file_get_contents(./home-starter.php): failed to open stream: No such file or directory
Even though the path is correct. Both files are in the same folder.
Main Folder
errorfile.php
home-starter.php
Any Suggestions?
<?php
require_once('private/initialize.php');
$city = 'Lahore';
$keyword = 'Homemade Food';
$areas = ['DHA', 'Bahria Town', 'Cantt', 'Gulberg', 'Valencia Town', 'Sui Gas Housing Society', 'Izmir Town', 'Faisal Town', 'Garden Town', 'Johar Town', 'Punjab Housing Society', 'Canal Housing Societies', 'State Life Housing Society', 'Model Town', 'Liaqatabad', 'Rehmanpura', 'Samanabad', 'Muslim Town', 'Town Ship', 'Iqbal Town', 'Ferozepure Road', 'Multan Road', 'Baghbanpura', 'Mughalpura', 'Walton'];
foreach ($areas as $area) {
$permalink = strtolower(str_replace(' ', '-', $keyword)) . '-' . strtolower(str_replace(' ', '-', $area)) . '-' . strtolower($city);
$page_title = 'Homemade Food Delivery - Lunch Dinner - ' . $area . ' - ' . $city;
$meta_desc = 'Lunch.pk is Pakistan #1 website to order homemade food in ' . $area . ' ' . $city . '. You get tasty and healthy food cooked and delivered by families near you.';
$location = $area . ' ' . $city;
$filename = $permalink . '.php';
$content = file_get_contents( __DIR__ . '/home-starter.php');
$content = str_replace('[page-title]', $page_title, $content);
$content = str_replace('[meta-desc]', $meta_desc, $content);
$content = str_replace('[location]', $location, $content);
$is_file_created = file_put_contents($filename, $content);
if (!$is_file_created) {
echo 'Err';
break;
}
}
Upvotes: 6
Views: 19398
Reputation: 19
Check your PHP version supports __DIR__
, i was able to get file content via a very similar method on PHP 7.4.24, but mine used a function that returns the contents.
$content = get_file_data("myfile.txt");
function get_file_data($filename) {
$data = file_get_contents(__DIR__ . "/$filename");
return $data;
}
Upvotes: 0
Reputation: 4294
I had this issue when implementing a cronjob after running the script successfully on a local dev machine.
My solution was to use the second function parameter of file_get_contents setting $use_include_path to TRUE
$currentFile = file_get_contents($fileinfo->getFilename(),true);
See the function's docs at php.net
Upvotes: 3
Reputation: 4201
check the file if exists then
$file=__DIR__ . '/home-starter.php';
if(file_exists($file))
{
$content=file_get_contents($file);
}
you cant find the correct path, use getcwd()
function get the current working directory
for example, your project has this structure
assume you will get content of config.php in anywhere, you should use the below code
$content=file_get_contents(getcwd().'/config/config.php');
Upvotes: 5
Reputation: 73
You need to use physical url
./home-starter.php
e.g. file_get_contents('C:\xampp\htdocs\project1\home-starter.php');
Upvotes: 0