Imrul.H
Imrul.H

Reputation: 5870

create file in another directory with 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);

Upvotes: 20

Views: 64108

Answers (5)

Kuldeep
Kuldeep

Reputation: 537

Had the same Problem, File will not be created in a folder having different permission, make sure the permissions of the folders are same like other files.

Upvotes: 1

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

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) . ")";
}
?>

Upvotes: 26

Jibin Mathew
Jibin Mathew

Reputation: 5102

Try this

$pagename = 'your_filename';
$newFileName = '../pages/'.$pagename.".php";

Upvotes: 0

ghazi
ghazi

Reputation: 71

$ourFileHandle = fopen("../pages/" .$ourFileName, 'w') or die("can't open file");

Make the above change to the third line and it will probably work; I tried it and it worked.

Upvotes: 7

Kishor Kundan
Kishor Kundan

Reputation: 3165

have you deliberately missed out on concatinating $dir_path and $ourFileName;

now

  1. is your directory/file writable?
  2. check for your current working directory
  3. is your error_reporting on ?

Upvotes: 2

Related Questions