Change file name in custom upload form - php

i want change file upload name and add the name of user that upload it.
This my function.php
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$user = wp_get_current_user();
$username = $user->display_lastname;
$filename = $username . $file_return['file'];
return $filename;
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
i try with $filename = $username . $file_return['file']; but don't work.

wp_handle_upload accepts an array of overrides, and one of the arguments is unique_filename_callback where you can specify a custom function to rename the file.
Try something like this:
1: Add a function to functions.php to rename the file as you want it, e.g.
function my_custom_filename($dir, $name, $ext){
$user = wp_get_current_user();
/* You wanted to add display_lastname, but its not required by WP so might not exist.
If it doesn't use their username instead: */
$username = $user->display_lastname;
if (!$username) $username = $user->user_login;
$newfilename = $username ."_". $name; /* prepend username to filename */
/* any other code you need to do, e.g. ensure the filename is unique, remove spaces from username etc */
return $newfilename;
}
2: Then in your upload_user_file(), specify your custom callback function in the wp_handle_upload overrides, e.g.
$overrides = array(
'test_form' => false, /* this was in your existing override array */
'unique_filename_callback' => 'my_custom_filename'
);
/* pass your overrides array into wp_handle_upload */
$file_return = wp_handle_upload($file,$overrides);
UPDATE:
To get the new filename in the upload_user_file function, you can get it from the "url" in the $file_return array that's returned by wp_handle_upload:
$newfilename = basename($file_return["url"]);

Related

I want to Upload Image from front-end with Advanced custom field

I have a lot of advanced custom fields. There are three image types between them. I have added ACF text fields with add_post_meta. But I can't add the images.
Here is my code sample
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['new_post'] )) {
$title="New Property for Sale";
$custom_tags = $_POST['tax_input']; //load thread tags (custom tax) into array
$post = array(
'post_title'=>$title,
'post_content' => $_POST['property_description'],
'tax_input' => $custom_tags,
'post_status' => 'pending',
'post_type' => 'property'
);
$post_id = wp_insert_post($post);
//send our post, save the resulting ID
if($post_id){
add_post_meta($post_id, 'type', $_POST['acf']['field_60338ebdd3ca4'], true);
add_post_meta($post_id, 'locality', $_POST['acf']['field_603374e8f8d62'],true);
add_post_meta($post_id, 'address', $_POST['acf']['field_6034ed6a0cd29'], true);
add_post_meta($post_id, 'facing', $_POST['acf']['field_6034eda30cd2b'],true);
add_post_meta($post_id, 'bed_number', $_POST['acf']['field_60337452f8d5f'], true);
add_post_meta($post_id, 'balconies', $_POST['acf']['field_6034f2180cd2c'], true);
//send the user along to their newly created post
}
}
I have added the featured image of the post.
if ( $_FILES['image']['name']!="" ) {
$upload = wp_upload_bits($_FILES["image"]["name"], null, file_get_contents($_FILES["image"]["tmp_name"]));
// $post_id = $post_id; //set post id to which you need to set featured image
$filename = $upload['file'];
$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'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if ( ! is_wp_error( $attachment_id ) ) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
I have to add more two images with ACF. Please Help me.
This is the most straight away full code on WP codex to upload to Media:
https://developer.wordpress.org/reference/functions/media_handle_upload/
So, try creating this file inside a wordpress page template and after attaching you will have to set the ID on your ACF metadata
<?php
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// The nonce was valid and the user has the capabilities, it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
// Remember, 'my_image_upload' is the name of our file input in our form above.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
echo "ERROR";
} else {
// The image was uploaded successfully!
echo "Image ID is: " . $attachment_id;
//Now set your image ACF field to the $attachment_id
// My case because its a user metadata update:
//update_user_meta( $userID, 'YOUR_IMAGE_NAME_ACF_FIELD_HERE!!', $attachment_id );
// update post meta of your ACF field with the new attachment id
update_post_meta ( $_POST['post_id'], 'YOUR_IMAGE_NAME_ACF_FIELD_HERE!!' , $attachment_id );
}
} else {
// The security check failed, maybe show the user an error.
}
?>
<!-- HTML code for uploading this single file -->
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
<input type="hidden" name="post_id" id="post_id" value="55" />
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>

add an attachment in Xero using php Xero api

Can anyone help me add a pdf to a Xero Invoice using the official (non calcanai) PHP SDK. I'm connected with oAuth2 and have previously created a draft invoice.
I then update the invoice to Authorised and try to add an attachment to the invoice. At this point I am not getting any luck, the attachments is sent but comes back in the respose as null. The docs are not at all useful and do not give any examples of adding an attachment or even minimal fields. So this is what I have:
...
$attachments = $apiResponse->getInvoices()[0]->getAttachments();
$attachment = new XeroAPI\XeroPHP\Models\Accounting\Attachment;
$attachment->setFileName( $filename )
->setIncludeOnline( true )
->setMimeType( 'application/pdf' );
$attachments[] = $attachment;
$apiResponse->getInvoices()[0]->setAttachments( $attachments );
$apiResult = $accountingApi->updateOrCreateInvoices( $xeroTenantId, $apiAuth );
if ( !$apiResult->getInvoices()[0]->getHasAttachments() ) {
$errors[] = 'Pdf file was not added to Xero.';
}
$errorList = array();
$errList = $apiResult->getInvoices()[0]->getValidationErrors()[0];
if ( !is_null( $errList ) ) {
$errorList = $errList;
}
foreach ( $errorList as $err ) {
$errors[] = $err->getMessage();
}
if ( count( $errors ) == 0 ) {
$result['message'] = 'New Invoice Authorised: ' . $xeroInvoice->getReference();
$result['apiResult'] = $apiResult;
$result['success'] = true;
} else {
$result['message'] = print_r( $errors );
$result['success'] = false;
}
...
any ideas?
thanks
* CODE AFTER *
public function attachPDF( $xeroTenantId, $accountingApi, $invoice ) {
$filename = 'AUTH#' . sprintf( '%08d', $invoice->id ) . '.pdf';
$guid = $invoice->invoice_id;
$content = $invoice->getPDF( \Mpdf\Output\Destination::FILE, true, $filename );
$handle = fopen( $filename, "r" );
$contents = fread( $handle, filesize( $filename ) );
fclose( $handle );
unlink( $filename );
return $accountingApi->createInvoiceAttachmentByFileName( $xeroTenantId, $guid, $filename, $contents, true );
}
Adding an attachment requires two API calls.
// Create or Get your Invoice ID, then create Attachment
$invoices = $apiInstance->getInvoices($xeroTenantId);
$guid = $invoices->getInvoices()[0]->getInvoiceId();
// file in the same dir.
$filename = "./helo-heros.jpg";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$result = $apiInstance->createInvoiceAttachmentByFileName($xeroTenantId,$guid,"helo-heros.jpg",$contents);
Anyone else who has this same issue it is due to the filename having a # in it (AUTH#00000123.pdf in my example) the updated code based on sidneys answer is also the way forward

Image insertion problem into DB in laravel

I am facing this error while uploading an image with a title and description text to DB in PHP Laravel. I am using the same code for other webpage there it is working properly but the same code is not working here.
Below is a function code inside my controller, where I am passing tile, description, img and input names from a form.
public function submitFanfic(Request $request){
$user_id = session('userid');
$name = $_FILES['img']['name'];
$tem_name = $_FILES['img']['tmp_name'];
$dir = 'public/uploads/fanfic/';
$dir1 = $dir.$name;
move_uploaded_file($tem_name, $dir1);
$data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $name,
'user_id' => $user_id
);
DB::table('fanfic')->insert($data);
Session::flash('message', 'Fanfic Submitted Successfully');
return redirect('/author/write_fanfic');
}
I tried again and again and this code (specifically for image insertion into DB) worked!!
public function submitFanfic(Request $request){
$user_id = session('userid');
$imageName = $request->file('img');
if($imageName!==null){
// get the extension
$extension = $imageName->getClientOriginalExtension();
// create a new file name
$new_name = date( 'Y-m-d' ) . '-' . str_random( 10 ) . '.' . $extension;
// move file to public/images/new and use $new_name
$imageName->move( public_path('uploads/fanfic'), $new_name);
}
$fanfic_data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $new_name,
'user_id' => $user_id
);
DB::Table('fanfic')->insert($fanfic_data);
Session::flash('message', 'Fanfic Submitted Successfully');

Post parent as current id not working

I'm using the wp dropzone plugin trying to tweak things a little to create a a front end image uploader that sets the current post as the attachments parent.
The plugin as is works really well but by default no matter where I locate the uploader any attachments are marked as un attached in my media library.
I can't for the life of me work out why this isn't working as I've tried all standard calls to get the current post id and set this as the parent.
The full php plugin file is quite extensive so I've included the core section which operates the attachment insertion. See my progress what I have below.
Importantly if I set the post parent as the actual id number; '240' for example it attaches to the called post. I'm looking to attach this to the current post.
/**
* Handle ajax file upload to media library.
*
* #since 1.0.0
*/
function wpday_dz_ajax_upload_handle() {
if (!empty($_FILES) && wp_verify_nonce($_REQUEST['wpday_dz_nonce'], 'wpday_dz_protect')) {
// Including file library if not exist
if (!function_exists('wp_handle_upload')) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
// Uploading file to server
$movefile = wp_handle_upload($_FILES['file'], ['test_form' => false]);
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$filetype = wp_check_filetype(basename($filename), null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_parent' => $post->ID,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
// Adding file to media
$attachment_id = wp_insert_attachment($attachment, $filename);
// If attachment success
if ($attach_id) {
require_once ABSPATH . 'wp-admin/includes/image.php';
// Updating attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
}
$message['error'] = 'false';
$message['data'] = wp_get_attachment_url($attach_id);
} else {
$message['error'] = 'true';
$message['data'] = $movefile['error'];
}
wp_send_json($message);
}
}
add_action('wp_ajax_wpday_dz', 'wpday_dz_ajax_upload_handle');
add_action('wp_ajax_nopriv_wpday_dz', 'wpday_dz_ajax_upload_handle');
EDIT:
Have tried:
$id = get_the_ID();
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$filetype = wp_check_filetype(basename($filename), null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_parent' => $id,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
Still returns unattached
I downloaded WP Dropzone and had a look at the code. AFAICT the function you are working on is called via AJAX, once a file is dropped/uploaded. In that case, there is no "post" in the current request - you're in an AJAX file unrelated to any post.
So the question becomes how to get the ID of the post that called the current AJAX request. I found this SO answer which answers that:
$url = wp_get_referer();
$post_id = url_to_postid( $url );

AJAX Post Custom Plugin WordPress slows down all of the web site

I am writ plugin for WordPress. It sends a link to the images on the PHP file (Ajax).
The array consists of 10 photos.
obj.photos.push({ img_url: img_url, source: source, photo_text: photo_text, tag: tag });
var data_insert = {
action: 'instapin_insert',
data: obj
};
$.ajax({
type: 'POST',
url: '/wp-content/plugins/instapin/ajax.php',
data: data_insert,
});
Next, the file takes a picture and the script loads to the cloud with Google (Google Drive).
<?php
session_start();
session_write_close();
require_once('../../../wp-config.php');
global $service;
if(class_exists('INSTAPIN'))
{
$instapin = new INSTAPIN();
}
$google_drive = get_option('instapin_drive');
$photos_array = $_POST['data']['photos'];
// Создаём объект записи
$instapin_post = array(
'post_title' => 'Название записи',
'post_content' => '',
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(0)
);
// Вставляем запись в базу данных
$post_id = wp_insert_post( $instapin_post );
if($google_drive == 'on'){
$folder = get_option('google_upload_folder');
$found = false;
$files = $service->files->listFiles();
foreach ($files['items'] as $item) {
if ($item['title'] == $post_id) {
$folder_insert_photo = $item['id'];
$found = true;
break;
}
}
if($found == false){
$file = new Google_Service_Drive_DriveFile();
//Setup the Folder to Create
$file->setTitle($post_id);
$file->setDescription('Photo folder: post_id - ' . $post_id);
$file->setMimeType('application/vnd.google-apps.folder');
//Set the ProjectsFolder Parent
$parent = new Google_Service_Drive_ParentReference();
$parent->setId( $folder );
$file->setParents(array($parent));
//create the ProjectFolder in the Parent
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
$folder_insert_photo = $createdFile->id;
$instapin->insertPermission($service, $folder_insert_photo, 'id', 'anyone', 'reader');
}
$count = 1;
$photo = new Google_Service_Drive_DriveFile();
$parent_folder = new Google_Service_Drive_ParentReference();
foreach($photos_array as $item){
if($count == 40){
break;
}
$img_url = strtok($item['img_url'], '?');
$image_url = str_replace("s150x150/", "", $img_url);
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
$wp_filetype = wp_check_filetype( $filename, null );
$MimeType = $wp_filetype['type'];
$seo_name = $item['tag'] . '_' . $count . '.jpg';
//Setup the Folder to Create
$photo->setTitle($seo_name);
$photo->setDescription('Photo: ' . $image_url);
$photo->setMimeType($MimeType);
$parent_folder->setId( $folder_insert_photo );
$photo->setParents(array($parent_folder));
// Try to upload the file, you can add the parameters e.g. if you want to convert a .doc to editable google format, add 'convert' = 'true'
$createdPhoto = $service->files->insert($photo, array(
'data' => $image_data,
'mimeType' => $MimeType,
'uploadType'=> 'multipart'
));
$instapin->insertPermission($service, $createdPhoto->id, 'id', 'anyone', 'reader');
$filePath = "GoogleDrive/{$folder_insert_photo}/{$seo_name}";
$fullFile = "https://googledrive.com/host/{$folder_insert_photo}/{$seo_name}";
print_r($fullFile);
$count++;
}
}
?>
But when I send an AJAX post to upload 10 photos, all admin panel and front. Nothing can be done and go until the download is complete (the script works).
But when I post to download 10 photos, all admin panel and front crashes (hangs). Nothing can be done and go until the upload is finished (the script works).
How to make this multi-tasking? So the admin panel and front continue to work, and the script is working in the background.

Categories