Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create file in another directory with php

Tags:

file

php

My folder structure is like -

root
  admin
    create_page.php
  pages
    my_page1.php
    my_page2.php

I have code for creating a new php file in "pages" folder. the code is like -

$dir_path = "../pages/";
$ourFileName = '../'.$page_name.".txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
$ourFileContent = '<?php echo "something..." ?>';
if (fwrite($ourFileHandle, $ourFileContent) === FALSE) {
    echo "Cannot write to file ($filename)";
    exit;
}

The code executes normally..no problem. but the page is not being created. please tell me what i am doing wrong. is there problem with the path? fclose($ourFileHandle);

like image 543
Imrul.H Avatar asked Mar 31 '12 16:03

Imrul.H


1 Answers

Here's an example using the more simpler file_put_contents() wrapper for fopen,fwrite,fclose

<?php 
error_reporting(E_ALL);

$pagename = 'my_page1';

$newFileName = './pages/'.$pagename.".php";
$newFileContent = '<?php echo "something..."; ?>';

if (file_put_contents($newFileName, $newFileContent) !== false) {
    echo "File created (" . basename($newFileName) . ")";
} else {
    echo "Cannot create file (" . basename($newFileName) . ")";
}
?>
like image 142
Lawrence Cherone Avatar answered Sep 23 '22 10:09

Lawrence Cherone