How to copy a file with PHP?

Asked

Viewed 3,788 times

0

Well my problem is the following wish to print a PHP code in another file.

For example, I have a file x.php, and I have a file y.php, in this file y.php I want this one to create a file z.php and make a copy of the file x.php, How can I do it?

3 answers

3

Well, if you’re going to copy a file . php use the php copy() function: http://php.net/manual/en/function.copy.php

$arquivo = 'arquivo.php';
$copia   = 'copia.php';

if (!copy($arquivo, $copia)) {
    echo "falha ao copiar $arquivo...\n";
}

3

To copy in PHP, as mentioned above, you can use the function copy() which allows you to copy a file to another location or to another file because the input name does not have to be the same as the output name.

Example

Contents of the archive x.php

<?php
// Eu sou o arquivo X

echo "X é muita fixe, mas o bubu é mais fixe!";
?>

Contents of the archive y.php

<?php
// Eu sou o arquivo Y

// Vou criar um arquivo "z.php" e copiar para lá o arquivo "x.php"
copy("caminho/para/arquivo/x.php", "caminho/para/arquivo/z.php");
?>

The result of what the archive y.php does is create a file with the name z.php which will contain the contents of the file x.php.

1

You can include PHP code inside another using the commands include, require and require_once. The best in your case is include, which can be used like this:

include('arquivo.php');

Remember that the file to be called must be in the same directory as the current file, if it is in another folder, or in a previous folder, you need to specify exactly the path, examples:

include('scripts/arquivo.php'); // Arquivo em uma pasta que está dentro do diretório atual
include('../arquivo.php'); // Arquivo em um diretório antes

To know the difference between the commands you can give a search. Here a quick reference: https://webpub.wordpress.com/2007/11/11/diferenca-entre-require-require_once-include-include_once/

  • For example, I have a file x.php, and I have a file y.php, in this file y.php I want this to create a file z.php and make a copy to the file x.php, how can I do it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.