Why $_FILES['uploadfiles'] not working and running blank? - wordpress

I am trying to upload image through custom.php in wordpress when i print the
`$_FILES['uploadfiles'];`
its not showing any thing the same code i have used before one day in another wordpress site the code is working good over there on ec2 my current wordpress is on ec2 and have bitnami image i have checked all configuration like in php.ini file upload_tmp_dir=/opt/bitnami/php/tmp ,file_uploads=on,upload_max_filesize=40M.
i am not using any form i have just added upload field in one hook that display that field on one page.
I am using thesis theme.so any boday have any idea why this happening with this code on while one copy of same code work on another wordpress with guru theme.
Bellow is the code i am using to upload image.
<input type="file" name="uploadfiles[]" id="uploadfiles" size="35" class="uploadfiles" />
<?php
$uploadfiles = $_FILES['uploadfiles'];
print_r ($uploadfiles);
if (is_array($uploadfiles)) {
echo "1";
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
echo $attach_data;
echo $filedest;
wp_update_attachment_metadata( $attach_id, $attach_data );
//echo wp_get_attachment_url( $attach_id );
//exit();
$urlimage=wp_get_attachment_url( $attach_id );
$_SESSION["oldurl"]=$urlimage;
echo $_SESSION["oldurl"];
}
}
}
?>

Related

File doesn't exist! in wordpress function.php file while creating new post or page

function wp_json_file_decode( $filename, $options = array() ) {
$result = null;
$filename = wp_normalize_path( realpath( $filename ) );
if ( ! file_exists( $filename ) ) {
trigger_error(
sprintf(
/* translators: %s: Path to the JSON file. */
__( "File %s doesn't exist!" ),
$filename
)
);
return $result;
}
$options = wp_parse_args( $options, array( 'associative' => false ) );
$decoded_file = json_decode( file_get_contents( $filename ), $options['associative'] );
if ( JSON_ERROR_NONE !== json_last_error() ) {
trigger_error(
sprintf(
/* translators: 1: Path to the JSON file, 2: Error message. */
__( 'Error when decoding a JSON file at path %1$s: %2$s' ),
$filename,
json_last_error_msg()
)
);
return $result;
}
return $decoded_file;
}
i have been working on wordpress website,
cant able to create new post
cant able to create new page
is there any plugin errors

move_uploaded_file() not working on wordpress front end

I have working code that uploads an image from the front end and sets it as a featured image and custom field photo for a custom post type but I am unable to figure out how to set the upload path.
Essentially if I have an employee I would like to use the custom field last_first to generate a folder path:
"wp-content/uploads/employee_mug/[last_first]/"
which would contain a photo of the employee. I require this as the folder structure is required for another page. The code is in my functions.php file but is simply in an if statement.
I've attempted to use move_uploaded_file with no success.
if (isset($_POST['last_first']) && is_user_logged_in()){
$my_post = array (
'post_type' => 'employee',
'post_status' => 'publish', // can also draft, private or publish
'post_title' => $_POST['last_first'],
);
$postID = wp_insert_post($my_post);
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$attach_id = media_handle_upload( $file, $postID );
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
update_field('date_of_birth', $_POST['dob'], $postID);
update_field('sex', $_POST['sex'], $postID);
die;}
I would like that when a file is attached the end result be:
"wp-content/uploads/employee_mug/[last_first]/1.jpg"
UPDATE 1.0
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$path = "./wp-content/uploads/mug_shots/";
$path .= $name;
if ( wp_mkdir_p( $path ) ) {
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
} else {
wp_mkdir_p( $path );
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
}
}
now checks to see if a folder was create and if not it will make one with the employee name but the move_uploaded file is not moving the photo into the generator folder. I simply need to find a way to make the file move to the generated folder at this point, Any help would be greatly appreciated!
UPDATE 2.0
the bellow code moves the file to wp-content/uploads/employee_mug/ but will not move it into the generated folder with the employee is name. I'm very close here I simply need the file moved into the employee is named folder at this point!
$name = $_POST['last_first'];
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
//for MKDIR FOR CREATION
$path = "./wp-content/uploads/employee_mug/";
$path .= $name;
//FOR MOVING UPLOADED IMAGE
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $name;
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
if ( wp_mkdir_p( $path ) ) {
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
} else {
wp_mkdir_p( $path );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
}
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
////////////////////////////////////////////////////////////////////////////////////////////
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
UPDATE 3.0 SOLVED ******
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $_POST['last_first'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}

How to generate multiple image with different size using rest api in wordpress

I want to generate multiple image when passed image url through rest api.
and serialize '_wp_attachment_metadata' data in postmeta table like thisa:5:{s:5:"width";i:1920;s:6:"height";i:1200;s:4:"file";s:29:"2018/05/Haute-Panoramic-1.jpg";s:5:"sizes";a:8:{s:9:"thumbnail";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-300x188.jpg";s:5:"width";i:300;s:6:"height";i:188;s:9:"mime-type";s:10:"image/jpeg";}s:12:"medium_large";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-768x480.jpg";s:5:"width";i:768;s:6:"height";i:480;s:9:"mime-type";s:10:"image/jpeg";}s:5:"large";a:4:{s:4:"file";s:30:"Haute-Panoramic-1-1024x640.jpg";s:5:"width";i:1024;s:6:"height";i:640;s:9:"mime-type";s:10:"image/jpeg";}s:6:"slider";a:4:{s:4:"file";s:30:"Haute-Panoramic-1-1440x550.jpg";s:5:"width";i:1440;s:6:"height";i:550;s:9:"mime-type";s:10:"image/jpeg";}s:25:"real_estate_lite_property";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-400x300.jpg";s:5:"width";i:400;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:32:"real_estate_lite_property_slider";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-800x600.jpg";s:5:"width";i:800;s:6:"height";i:600;s:9:"mime-type";s:10:"image/jpeg";}s:27:"real_estate_lite_page_thumb";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-400x220.jpg";s:5:"width";i:400;s:6:"height";i:220;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
Here is the my code:-
$fetured_array=["https://media.architecturaldigest.com/photos/585811cfdcb583e908275f46/4:3/w_384/buildings-with-trees-001.jpg","https://media.architecturaldigest.com/photos/585811cfdcb583e908275f46/4:3/w_384/buildings-with-trees-001.jpg"]
$count_img=0;
foreach($feature_img as $url)
{
//$url = $feature_img;
$path = parse_url($url, PHP_URL_PATH);
$filename = mt_rand().basename($path);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($url);
$savefile = fopen($uploadfile, 'w');
chmod($uploadfile, 0777);
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'ID'=>$page_id,
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'post_parent'=>$new_post_id,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
if($count_img==0){
if ($attach_id) {
set_post_thumbnail( $new_post_id, $attach_id );
}
}
$newwidth = '250';
foreach ($attachment as $attached) {
$id = $attach_id;
$metadata = wp_get_attachment_metadata($id);
$metadata['width'] = $newwidth;
wp_update_attachment_metadata($id,$metadata);
}
array_push($fetured_array,$attach_id);
$count_img++;
}
$format_fetured_img=implode('|',$fetured_array);
update_post_meta($new_post_id, 'real_estate_property_images', $format_fetured_img);
Currently its working but only uploaded images into uploads/2018/5
folder with original size of the image. How can I upload image with
dynamic generate size as like when upload image in Media library by
wordpress admin
Please help me out to find the solution for the above.
Thanks in advance
Here is the solution.
First make sure you attached the image.php file just before the $fetured_array like this
require ( ABSPATH . 'wp-admin/includes/image.php' ); after that add thumbsize add_image_size( 'custom-size', 110, 100 );
Now after $attach_id = wp_insert_attachment( $attachment, $uploadfile ); add following two lines
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploadfile);
wp_update_attachment_metadata( $attach_id, $attach_data );
Now your code will work. This code is tested and its working fine.
I found the function to create it!! It will create all images automatically.
https://gist.github.com/m1r0/f22d5237ee93bcccb0d9
function crb_insert_attachment_from_url($url, $parent_post_id = null) {
if( !class_exists( 'WP_Http' ) )
include_once( ABSPATH . WPINC . '/class-http.php' );
$http = new WP_Http();
$response = $http->request( $url );
if( $response['response']['code'] != 200 ) {
return false;
}
$upload = wp_upload_bits( basename($url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name, null );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name,
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
// Create the attachment
$attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );
// Include image.php
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id;
}
and for call this function, use it.
$xxx = crb_insert_attachment_from_url('http://ronaldoguedes.com.br/img/hello_word_2.png', null);

Upload multiple images to a Woocommerce product

I am trying to upload various images from an URL to a given woocommerce product. The issue I am facing with my code is that, although I see that the images are being uploaded to the server, when I go to see my post I only see the last image uploaded to the gallery.
Here is my code:
function generateSecondImage($image_url, $post_id)
{
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($attachment, $file, $post_id);
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
$res3 = update_post_meta($post_id, '_product_image_gallery', $attach_id);
}
And here is how I call the function
for ($j=1; $j <$picCount ; $j++) {
generateSecondImage($pic[$j]->url, $post_id);
}
I am thinking that maybe, res3 is overwriting the gallery and showing only the last image posted, but if that is the case, how would I tell wordpress to include all of the images in the for loop?
Finally managed to solve it!
Here is my final code. My upload function goes like this:
function generateSecondImage($image_url, $post_id)
{
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($attachment, $file, $post_id);
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
echo "Attach ID is".$attach_id;
return $attach_id;
}
And then I had to create a comma-separated list of the IDs and add it to the add_post_meta
So my loop changed to this:
for ($j=1; $j <$picCount ; $j++) {
$attarray[] = generateSecondImage($pic[$j]->url, $post_id);
}
$commaList = implode(', ', $attarray);
$res3 = add_post_meta($post_id, '_product_image_gallery', $commaList);
Hope this helps anyone else looking for a solution.

Wordpress Updating Attachment Data

I'm attempting to add a feature to a plugin that extends media management. This feature would allow you to rename an attachment file. I've been able to complete this with the following code.
public function update_attachment_filename( $post_ID ) {
// Get path to existing file
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Generate new file name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the name and reference to file
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
}
While the original file gets renamed using the above method, all additional image sizes defined in the plugins/theme are not updated. I'm struggling to figure out the best way to accomplish this task.
I've looked into wp_update_attachment_metadata() and wp_generate_attachment_metadata() but am unsure whether they will give me the desired functionality.
Additionally I've looked into something such as:
$file_meta = wp_get_attachment_metadata( $post_ID );
foreach( $file_meta['sizes'] as $image ) {
// Do something
}
Any nudge in the right direction would be greatly appreciated.
Thanks!
I was able to utilize both the wp_generate_attachment_metadata() and the wp_update_attachment_metadata() function to achieve the desired end result.
public function update_attachment_filename( $post_ID ) {
if( isset( $_POST['update_filename'] ) && ! empty( $_POST['update_filename'] ) ) {
// Get path to existing attachment
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Create new attachment name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the attachment name
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
// Update attachment meta data
$file_updated_meta = wp_generate_attachment_metadata( $post_ID, $file_updated );
wp_update_attachment_metadata( $post_ID, $file_updated_meta );
}
}

Resources