Link to home
Start Free TrialLog in
Avatar of MOSTAGHASSI
MOSTAGHASSIFlag for United States of America

asked on

How can use variable for setting filename and dir name-php5?

Hello,
I have these 2 variables
$artistID
$albumID

how can i use these to put name of a file a name of a dir as:

$filename='$albumID.txt';
$dir='C:/myfolder/$artistID';

so if $artistID=3 and $albumID=1 then i have:

$filename='1.txt';
$dir='C:/myfolder/3';

Thanks
ASKER CERTIFIED SOLUTION
Avatar of ddrudik
ddrudik
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Use double quotes to embed PHP variables into strings

$filename="$albumID.txt";
$dir="C:/myfolder/$artistID";


Use string concatenation

$filename=$albumID . '.txt';
$dir='C:/myfolder/' . $artistID;


Use heredoc

$filename=<<<END_TEXT
$albumID.txt
END_TEXT;

$dir=<<<END_TEXT
C:/myfolder/$artistID
END_TEXT;

Avatar of MOSTAGHASSI

ASKER

yes, but when i creat a file like below then the file name become e.g 31.txt and folder of 3 does not creat like :
c:/myfolder/3
i see that inside myfolder is 31.txt, my code is:
<?php
$albumID=1;
$artistID=3;
$filename="$albumID.txt";
$dir="C:/myfolder/$artistID";
 
$somecontent="Hello world";
 
$fullPath = $dir.$filename;
 
if( file_exists($fullPath) ) 
{
	$handle = fopen($fullPath, "a+");
}
else
{
	$handle = fopen($fullPath, "w+");
}
 
 
if( !$handle )
{
	echo "Unable to open file.";
	exit;
}
else
{
	fwrite($handle, $somecontent);
	fclose($handle);
}
?>

Open in new window

/ need to be \ for Windows paths.
yes, my system is win xp but   this \ doesnot work  and i use this /   i don't know why
i think i must creat also folder with name of  $artistID and because it doesnot exist but how?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
So it is better that i correct my question:

"Create a file and a dir with 2 variables and putting that file in that folder".
Thanks-i increased point
what is PHP constant DIRECTORY_SEPARATOR?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
echo DIRECTORY_SEPARATOR;

On windows = \\
On unix/llinux = /

Saves thinking.