Skip to content

Instantly share code, notes, and snippets.

@ascottmccauley
Created March 30, 2016 22:59
Show Gist options
  • Save ascottmccauley/baad35394a2dee1eb1941fb3fa18386a to your computer and use it in GitHub Desktop.
Save ascottmccauley/baad35394a2dee1eb1941fb3fa18386a to your computer and use it in GitHub Desktop.
function upandup_ajax_cropper_upload() {
$response = array();
if ( check_ajax_referer( 'upandup_cropper_nonce', 'nonce', false ) ) {
$uploads = wp_upload_dir();
$uploadPath = trailingslashit( $uploads['path'] );
$uploadURL = trailingslashit( $uploads['url'] );
// get and sanitize global variables
if ( isset( $_POST['sessionID'] ) ) {
$sessionID = sanitize_text_field( $_POST['sessionID'] );
$uploadPath .= $sessionID . '/';
$uploadURL .= $sessionID . '/';
// create folder if it doesn't exist
if ( ! file_exists( $uploadPath ) ) {
mkdir( $uploadPath, 0757, true);
}
}
if ( isset( $_POST['imageData'] ) ) {
// convert imageData to a jpg and save to the server.
$imageData = sanitize_text_field( $_POST['imageData'] );
$imageData = str_replace( 'data:image/png;base64,', '', $imageData );
$imageData = str_replace( ' ', '+', $imageData );
$imageData = base64_decode( $imageData );
$filename = 'final-crop.jpg';
$filePath = $uploadPath . $filename;
$fileURL = $uploadURL . $filename;
$image = imagecreatefromstring( $imageData );
imagealphablending( $image, true );
imagesavealpha( $image, true );
imagejpeg( $image, $filePath, 100 );
imagedestroy( $image );
$response = array( 'success' => true, 'url' => $fileURL, 'path' => $filePath );
}
} else {
$response = array( 'success' => false, 'error' => 'invalid nonce');
}
// return response
header('Content-Type: application/json');
echo json_encode( $response );
die();
}
add_action( 'wp_ajax_cropper_upload', 'upandup_ajax_cropper_upload' );
add_action( 'wp_ajax_nopriv_cropper_upload', 'upandup_ajax_cropper_upload' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment