Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace file in PHP [closed]

Tags:

file

replace

php

I would like to replace one image file with another in PHP. Both have same name (123), but they are in different directory and should have different extension. I want to replace first image with second image.

  1. ../images/123.gif
  2. ../images/xxx/123.png

Is it possible with any function? Thank you.

like image 717
user2406937 Avatar asked Oct 02 '13 21:10

user2406937


People also ask

How do I overwrite a file in PHP?

How to overwrite file contents with new content in PHP? 'w' -> Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. 'w+'-> Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length.

What is file_ put_ contents in PHP?

The file_put_contents() function in PHP is an inbuilt function which is used to write a string to a file. The file_put_contents() function checks for the file in which the user wants to write and if the file doesn't exist, it creates a new file.

How do I replace a word in a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How to get path of uploaded file in PHP?

php $dir = dirname(__FILE__); echo "<p>Full path to this dir: " . $dir . "</p>"; echo "<p>Full path to a . htpasswd file in this dir: " .


1 Answers

Moving, deleting, copying etc... are all basic actions that are needed whenever working with file systems. As such the documentation will undoubtedly have all of the information you need.

  1. http://php.net/rename
  2. http://php.net/copy
  3. http://php.net/unlink

You say that you want to replace the first file with the second.. But you don't mention what you want to happen to the original copy of the second image?

If you rename (i.e. move) it then the file will no longer exist in it's starting location. If you want the file to remain in both directories then you should use copy instead.

In this case, all you need is:

rename('/path/to/get/file.from', '/path/to/put/file.to');

NOTE: You are able to use relative pats (e.g. ./ and ../)


Additional code

rename('/path/to/get/file.b', '/path/to/put/file.b');
unlink('/path/to/remove/file.a');

Working example

rename('../image/new/8.jpg', '../image/8.jpg'); //Moves new (jpg) file to `../image` directory
unlink('../image/8.gif');                       //Delete old file with gif extension
like image 186
Steven Avatar answered Sep 22 '22 23:09

Steven