copy php file

2

I have this copy function

$srcfile='C:\xampp\htdocs\imagenes\M1001.jpg';
$dstfile='C:\xampp\htdocs\imagenes-copiadas\M1001.jpg';
mkdir(dirname($dstfile), 0777, true);
copy($srcfile, $dstfile);

I need the name M1001.jpg to be a variable called = $ image.jpg I tried double quotes, double \, single bar and double bar for variable \ $ image, and it does not work.

I tried this:

$srcfile='C:\xampp\htdocs\imagenes\$imagen.jpg';
$dstfile='C:\xampp\htdocs\imagenes-copiadas\$imagen.jpg';
 mkdir(dirname($dstfile), 0777, true);
 copy($srcfile, $dstfile);

but it does not work

    
asked by Ivan Diaz Perez 26.05.2018 в 10:49
source

1 answer

2

The problem is that with the single quotes a literal string is created, giving the following output:

$srcfile='C:\xampp\htdocs\imagenes\$imagen.jpg';
// C:\xampp\htdocs\imagenes\$imagen.jpg

If you use double quotes, the backslash serves as the escape for $ of the variable, giving the output:

$srcfile="C:\xampp\htdocs\imagenes\$imagen.jpg";
// C:\xampp\htdocs\imagenes\$imagen.jpg

Solution

You can escape the backslash with double quotes:

$srcfile="C:\xampp\htdocs\imagenes\$imagen.jpg";
// C:\xampp\htdocs\imagenes\NOMBRE_IMAGEN.jpg

You can concatenate with the single quotes:

$srcfile='C:\xampp\htdocs\imagenes\' . $imagen . '.jpg';
// C:\xampp\htdocs\imagenes\NOMBRE_IMAGEN.jpg

Or use the sprintf function:

$srcfile = sprintf('C:\xampp\htdocs\imagenes\%s.jpg', $imagen);
// C:\xampp\htdocs\imagenes\NOMBRE_IMAGEN.jpg
    
answered by 26.05.2018 / 11:29
source