{"id":2241,"date":"2017-12-17T12:57:18","date_gmt":"2017-12-17T07:27:18","guid":{"rendered":"https:\/\/pheonixsolutions.com\/blog\/?p=2241"},"modified":"2017-12-26T10:47:10","modified_gmt":"2017-12-26T05:17:10","slug":"moving-wordpress-media-amazon-cloudfront-s3","status":"publish","type":"post","link":"https:\/\/pheonixsolutions.com\/blog\/moving-wordpress-media-amazon-cloudfront-s3\/","title":{"rendered":"Moving WordPress Media To Amazon CloudFront and S3"},"content":{"rendered":"<p><strong>Posted Date:20-07-2017<\/strong><\/p>\n<p>In this post we will explain moving wordpress media to amazon cloudfront and S3.<\/p>\n<p>step 1: Install the following plugins on wordpress.<\/p>\n<p><a href=\"https:\/\/wordpress.org\/plugins\/amazon-web-services\/\" target=\"_blank\" rel=\"noopener\">https:\/\/wordpress.org\/plugins\/amazon-web-services\/<\/a><\/p>\n<p><a href=\"https:\/\/wordpress.org\/plugins\/amazon-s3-and-cloudfront\/\" target=\"_blank\" rel=\"noopener\">https:\/\/wordpress.org\/plugins\/amazon-s3-and-cloudfront\/<\/a><\/p>\n<p>step 2:\u00a0To configure Amazon Web Services account here and create the new user in aws console.<\/p>\n<p>step 3: To create the aws s3 bucket for your domain and create the new users in aws and copy the awsAccess Key ID and Secret Access Key.<\/p>\n<p>step 4: Login into your server, configure the aws user using following command.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">aws configure<\/pre>\n<p>step 5:Go to your wordpress site upload folder and run the following command.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">aws s3 sync . s3:\/\/bucket-name\/folder<\/pre>\n<p>step 6: In the root folder you can create new file name as aws-cdn-script.php using following code.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&lt;?php\r\n\r\n    ini_set('display_errors', 1);\r\n    error_reporting(E_ALL);\r\n\r\n    \/* ======================================================\r\n    This script is NOT FULLY TESTED (not tested on Windows Server either)\r\n    USE AT YOUR OWN RISK - development environment Ubuntu Linux 14.04.3 LTS\r\n\r\n    The purpose of this script is for small websites and blogs\r\n    to have their existing media to work through Amazon S3\r\n    \r\n    There's a great plugin, WP Offload S3, that we'll be tapping\r\n    into...it works great for new media, but this is a quick\r\n    fix for EXISTING media - media added before you start\r\n    using WP Offload S3.\r\n\r\n    This script is not fully tested, but should be useful for\r\n    most situations.  It does create a backup of your database,\r\n    though it's not tested to work 100% in all hosting scenarios.\r\n\r\n    Put this file in your WordPress root directory, where wp-config.php is.\r\n    You must also already have these 2 plugins installed and configured:\r\n    - https:\/\/wordpress.org\/plugins\/amazon-web-services\/\r\n    - https:\/\/wordpress.org\/plugins\/amazon-s3-and-cloudfront\/\r\n\r\n    TURN OFF CACHING if you have it on your site.  Re-enable it after\r\n    everything is done.\r\n\r\n    ======================================================\r\n    STEPS\r\n\r\n    1) Manually upload all of your existing \/wp-content\/uploads\/ files to the\r\n    Amazon S3 bucket (the bucket you configured WP Offload S3 to use for new images)\r\n\r\n    2) Add and configure plugins (the 2 listed above)\r\n\r\n    3) Run this script from the root directory of your WordPress site\r\n\r\n    ======================================================\r\n    Developer: TJ Nevis\r\n    Website: http:\/\/blog.TJNevis.com, http:\/\/NevisTechnology.com\r\n    More Info: http:\/\/blog.tjnevis.com\/wordpress-and-amazon-s3-quick-fix-for-existing-media-to-be-served-on-amazon-s3\/\r\n    Last Updated: 04\/19\/2016\r\n    ====================================================== *\/\r\n\r\n    require_once 'wp-config.php';\r\n    require_once 'wp-content\/plugins\/amazon-s3-and-cloudfront\/wordpress-s3.php';\r\n    global $table_prefix;\r\n\r\n\r\n\r\n    echo '&lt;h1&gt;Move Existing Media to Amazon S3&lt;\/h1&gt;';\r\n    echo '&lt;h3&gt;By TJ Nevis [&lt;a href=\"http:\/\/NevisTechnology.com?ref=S3Script\" target=\"_blank\"&gt;NevisTechnology.com&lt;\/a&gt;] Detailed blog post &lt;a href=\"http:\/\/blog.tjnevis.com\/wp-offload-s3-quick-fix-for-existing-media\/\" target=\"_blank\"&gt;here&lt;\/a&gt;&lt;\/h3&gt;';\r\n\r\n\r\n\r\n    \/* ======================================================\r\n    First step, we're going to back up the database and\r\n    save it in the the root directory of your site (where this file is)    \r\n    ====================================================== *\/\r\n    $dbHost = $wpdb-&gt;dbhost;\r\n    $dbName = $wpdb-&gt;dbname;\r\n    $dbPassword = $wpdb-&gt;dbpassword;\r\n    $dbSaveFileLocation = dirname(__FILE__) . '\/backup-' . date('Y-m-d-h:i:s', time()) . '.sql';\r\n    $dbUser = $wpdb-&gt;dbuser;\r\n\r\n    exec(\"mysqldump --user=$dbUser --password=$dbPassword --host=$dbHost $dbName &gt; $dbSaveFileLocation\");\r\n\r\n    \/* ======================================================\r\n    Let's get set up with by grabbing WP Offload S3 values\r\n    ====================================================== *\/\r\n    amazon_web_services_require_files(); \/\/ Thanks k0nG\r\n    $aws = new Amazon_Web_Services( __FILE__ ); \/\/ Thanks k0nG\r\n    $awsS3 = new Amazon_S3_And_CloudFront(__FILE__, $aws); \/\/ Thanks k0nG\r\n    $bucket = ( !empty( $awsS3-&gt;get_setting('cloudfront') ) ) ? $awsS3-&gt;get_setting('cloudfront') : $awsS3-&gt;get_setting('bucket'); \/\/ If you're using a CDN and the setting is saved, use that for CloudFront URL replcaement, otherwise use the S3 bucket name\r\n    $region = $awsS3-&gt;get_setting('region'); \/\/ Thanks k0nG\r\n    $folderPrefix = $awsS3-&gt;get_setting('object-prefix');\r\n\r\n    \/* ======================================================\r\n    Check if the user is requesting to remove the existing media updates\r\n    ====================================================== *\/\r\n    if( isset($_GET['remove']) &amp;&amp; $_GET['remove'] ) { \/\/ ?removeS3Update=true\r\n        if( $dbConnection = mysqli_connect($dbHost, $dbUser, $dbPassword, $dbName) ) {\r\n\r\n            $removeAmazonS3Info = \"DELETE FROM \" . $table_prefix . \"postmeta WHERE meta_key = 'amazonS3_info';\";\r\n            $reversePostContentHref = updatePostContent(\r\n                                            'href',\r\n                                            $table_prefix . 'posts',\r\n                                            get_site_url( $wpdb-&gt;blogid ) . '\/' . $folderPrefix,\r\n                                            \"https:\/\/$bucket.s3.amazonaws.com\/$folderPrefix\",\r\n                                            true\r\n                                        );\r\n            $reversePostContentSrc = updatePostContent(\r\n                                            'src',\r\n                                            $table_prefix . 'posts',\r\n                                            get_site_url( $wpdb-&gt;blogid ) . '\/' . $folderPrefix,\r\n                                            \"https:\/\/$bucket.s3.amazonaws.com\/$folderPrefix\",\r\n                                            true\r\n                                        );\r\n\r\n            echo 'RUNNING COMMAND: ' . $removeAmazonS3Info . ' - '; \r\n            if( $dbConnection-&gt;query($removeAmazonS3Info) ) {\r\n                echo ' &lt;strong&gt;TRUE, ' . $dbConnection-&gt;affected_rows . ' rows affected&lt;\/strong&gt;&lt;br \/&gt;';\r\n            }\r\n\r\n            echo 'RUNNING COMMAND: ' . $reversePostContentHref . ' - ';\r\n            if( $dbConnection-&gt;query($reversePostContentHref) ) {\r\n                echo ' &lt;strong&gt;TRUE, ' . $dbConnection-&gt;affected_rows . ' rows affected&lt;\/strong&gt;&lt;br \/&gt;';\r\n            }\r\n\r\n            echo 'RUNNING COMMAND: ' . $reversePostContentSrc . ' - '; \r\n            if( $dbConnection-&gt;query($reversePostContentSrc) ) {\r\n                echo ' &lt;strong&gt;TRUE, ' . $dbConnection-&gt;affected_rows . ' rows affected&lt;\/strong&gt;&lt;br \/&gt;';\r\n            }   \r\n\r\n        }\r\n\r\n        echo '&lt;h3&gt;DONE with removing records for WP Offload S3 - reverted back to serving from the local server&lt;\/h3&gt;';\r\n\r\n        exit(); \/\/ Don't do the rest of the script\r\n    }\r\n\r\n    \/* ======================================================\r\n    Start fresh, delete data thatis from WP Offload S3    \r\n    ====================================================== *\/\r\n    $wpdb-&gt;delete($table_prefix . 'postmeta',\r\n        array(\r\n            'meta_key'  =&gt; 'amazonS3_info'\r\n        )\r\n    );\r\n\r\n    \/* ======================================================\r\n    Grab the attachments from the database, we'll need\r\n    the meta_value (image name), and the post ID it's related to\r\n    ====================================================== *\/\r\n    $picturesToUpdate = $wpdb-&gt;get_results(\"SELECT * FROM \" . $table_prefix . \"postmeta WHERE meta_key = '_wp_attached_file'\");\r\n\r\n    foreach($picturesToUpdate as $picture) {\r\n        $pictureMetaData = serialize(array(\r\n            'bucket'    =&gt; $bucket,\r\n            'key'       =&gt; $folderPrefix . $picture-&gt;meta_value,\r\n            'region'    =&gt; $region \/\/ Thanks k0nG\r\n        ));\r\n\r\n        \/* ======================================================\r\n        Now let's insert the record that WP Offload S3 looks for\r\n        to change the image URL to your S3 URL\r\n        ====================================================== *\/\r\n        $wpdb-&gt;insert($table_prefix . 'postmeta', \r\n            array(\r\n                'post_id'   =&gt; $picture-&gt;post_id,\r\n                'meta_key'  =&gt; 'amazonS3_info',\r\n                'meta_value'  =&gt; $pictureMetaData\r\n            )\r\n        );\r\n\r\n    }\r\n\r\n    if( $dbConnection = mysqli_connect($dbHost, $dbUser, $dbPassword, $dbName) ) {\r\n\r\n        $hrefMySQLUpdate = updatePostContent(\r\n                                'href',\r\n                                $table_prefix . 'posts',\r\n                                get_site_url( $wpdb-&gt;blogid ) . '\/' . $folderPrefix,\r\n                                \"https:\/\/$bucket.s3.amazonaws.com\/$folderPrefix\"\r\n                            );\r\n        $srcMySQLUpdate = updatePostContent(\r\n                                'src',\r\n                                $table_prefix . 'posts',\r\n                                get_site_url( $wpdb-&gt;blogid ) . '\/' . $folderPrefix,\r\n                                \"https:\/\/$bucket.s3.amazonaws.com\/$folderPrefix\"\r\n                            );\r\n\r\n        echo 'RUNNING COMMAND: ' . $hrefMySQLUpdate . ' - '; \r\n        if( $dbConnection-&gt;query($hrefMySQLUpdate) ) {\r\n            echo ' &lt;strong&gt;TRUE, ' . $dbConnection-&gt;affected_rows . ' rows affected&lt;\/strong&gt;&lt;br \/&gt;';\r\n        }\r\n\r\n        echo 'RUNNING COMMAND: ' . $srcMySQLUpdate . ' - ';\r\n        if( $dbConnection-&gt;query($srcMySQLUpdate) ) {\r\n            echo ' &lt;strong&gt;TRUE, ' . $dbConnection-&gt;affected_rows . ' rows affected&lt;\/strong&gt;&lt;br \/&gt;';\r\n        }\r\n\r\n    }\r\n\r\n    echo '&lt;h3&gt;DONE with adding records for WP Offload S3 to recognize the image on S3&lt;\/h3&gt;';\r\n\r\n\r\n\r\n    function updatePostContent($type, $table, $blog, $s3bucket, $reverse = FALSE) {\r\n        \/\/ $reverse is to remove the post_content updates and put them back to serving locally\r\n        $from   = ( !$reverse ) ? $blog : $s3bucket;\r\n        $to     = ( !$reverse ) ? $s3bucket : $blog;\r\n\r\n        return \"UPDATE $table SET post_content = replace(post_content, '$type=\\\"$from', '$type=\\\"$to');\";\r\n    }\r\n\r\n?&gt;<\/pre>\n<p>step 7: In the url you can access this page like http:\/\/sitename.com\/aws-cdn-script.php?remove=true and after execution automatically file will removed.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Posted Date:20-07-2017 In this post we will explain moving wordpress media to amazon cloudfront and S3. step 1: Install the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[1019],"tags":[280,273,167],"class_list":["post-2241","post","type-post","status-publish","format-standard","hentry","category-cloud-aws","tag-amazon","tag-php","tag-wordpress-2","psol-cat-cloud-aws"],"jetpack_publicize_connections":[],"jetpack_shortlink":"https:\/\/wp.me\/phn2x7-A9","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/2241","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/comments?post=2241"}],"version-history":[{"count":0,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/2241\/revisions"}],"wp:attachment":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/media?parent=2241"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/categories?post=2241"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/tags?post=2241"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}