Created
December 7, 2016 00:56
-
-
Save imvaskii/3df810d7a33e71b2599bba48916d8933 to your computer and use it in GitHub Desktop.
[Wordpress] Copies attachments from remote server (Production site)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Copies file from url to current path | |
* @param type $url | |
* @return type file_name on success else bool false | |
*/ | |
function copy_file_from_url( $url ) { | |
if( empty( $url ) ) | |
return false; | |
// first check if url is accessable or not. | |
// $headers = get_headers( $url, 1 ); | |
// | |
// if( 'HTTP/1.0 404 Not Found' != reset( $headers ) ) | |
// return false; | |
$local_upload_url = home_url() . '/wp-content/uploads'; | |
$live_upload_url = 'http://www.sitename.com/wp-content/uploads'; | |
$file_name = basename( $url ); | |
// extracting uploads section folder eg. 2016/01/02 | |
$file_path = ( strpos( $url, $local_upload_url ) > -1 )? str_replace( $local_upload_url, '', $url ): str_replace( $live_upload_url, '', $url ); | |
$source_url = str_replace( $local_upload_url, $live_upload_url, $url ); | |
$file_path = str_replace( $file_name, '', $file_path ); | |
$upload_path = wp_upload_dir['upload_path'] . $file_path; | |
// echo $upload_path . $file_name; | |
// var_dump( file_exists( $upload_path . $file_name ) ); die; | |
if( file_exists( $upload_path . $file_name ) ) { | |
return; | |
} | |
if( ! file_get_contents( $source_url ) ) | |
return false; | |
if ( ! file_exists( $upload_path ) ) { | |
mkdir( $upload_path, 0777, true ); | |
} | |
printf( "\Downloading {$upload_path}{$file_name} ...\n" ); | |
if( file_put_contents( $upload_path . $file_name, file_get_contents( $source_url ) ) ){ | |
return $file_name; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment