I am new to PHP and need help with my code to create files and folders based on variable values. Here's the setup:

1. I have approximately 100 categories. I've assigned a variable to each category. E.g.

  • Variable 1 (as in $c1) contains category one's name.
  • Variable 2 (as in $c2) contains category two's name.
  • Variable 3 (as in $c3) contains category three's name.
  • Etc. for all 70 variables / categories.

2. My script needs to create a folder for each category and then add a content file into each category folder.

Here's my code so far:

<?php include '0vars.php'; ?> // The file containing the list of variables.

	$mypath="$c1"; // Set the path to create the first folder using variable $c1 for the folder name.
	mkdir($mypath,0755,TRUE);  // Create the folder / directory	
	chdir($mypath); // Change Directory to enter the folder just created	
	$filename = 'index.php'; // Name the file to be created
	$handle = fopen($filename,"x+");  // Not sure what this does??	
	$somecontent = "include"../content/c1.php";  // This has got me!!! Content must be an include from the content folder.
	fwrite($handle,$somecontent);  // Closing of the script - last 3 lines.
	echo "Success";
	chdir('../'); // Go back up one directory level
// Now repeat the process for all +- 100 categories.
	$filename = 'index.php';
	$handle = fopen($filename,"x+");
	$somecontent = "xxxxxxxxxxxx";
	echo "Success";
	//----------------------------- Etc.	

The code works except for the line:

$somecontent = "include"../content/c1.php";

which I clearly don't know how to format.

The included file name 'c1.php' must match the variable name '$c1.'
Likewise, the created folder must match the variable name '$c1.'

The resulting structure would be

Category1 (The first directory)
index.php with c1.php included

Category2 (The second directory)
index.php with c2.php included


Repeating the above code 100 times for each category / folder would be tedious, but I am not sure how to loop it.

Thank you. I hope the above makes sense.

As you are clearly very new to php, I'd recommend you read up on arrays and loops.

Member Avatar

OK just a little bit.

Yours 'variables' in the include file should be placed in an array so that you can loop over them, e.g.

$mynames = array("c1","c2","c3"...);


foreach($mynames as $name){
  $existfile = "../content/" . $name . ".php";
  $newfile = "$name/index.php";
  if (!copy($existfile, $newfile)) {
    echo "copy $file failed...<br />";

Not tested, but that's the sort of thing I'd do. If you simply want to MOVE the files, use rename() instead of copy().