I am posting a file to dspace through dspace api, I am doing this with an action in php. With postman I send a form-data with the file, filename, bitstream id and token.
I am getting the temp file path with $_FILES and sending it by postfields curl option, but the file uploads empty, or with weird data, without its content.
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> $file,'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('photo'=> new CURLFILE('/C:/Users/pfile3.jpeg'),'name' => $name),
this is the example of uploading a file with form key as photo and another key name
in your screen shot you have id and token in form data but in code its not inside POSTFIELDS
in postman you can generate equalent code of request in any language , try generating the PHP equalent code and see if it works:
To do this just click code link under the request url after saving the request
I already post the file by the $_FILE variable, But what I needed to do was to use CURLFILE to create a new file, and give it the temp path of the file in the server
$file = $_FILES['file']['tmp_name'];
and this in the postfields
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
Thanks for the help friends
Here the code:
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
The posted files with the rigth size(finally)
The form data I send by Postman, no need to use the field path
Related
With the help of #Tanaike(see here), I can successfully upload files to GoogleDrive by using php-curl, here is my code by using php-curl:
function uploadByCurl($uploadFilePath, $accessToken){
$ch = curl_init();
$boundary = md5(mt_rand() . microtime());
//MetaData
$params = json_encode([
'name' => basename($uploadFilePath),
'description' => 'This is a test',
]);
$fileContent = file_get_contents($uploadFilePath);
$dataToUpload = "--{$boundary}\r\n";
$dataToUpload .= "Content-Type: application/json\r\n\r\n";
$dataToUpload .= "{$params}\r\n";
$dataToUpload .= "--{$boundary}\r\n";
$dataToUpload .= "Content-Transfer-Encoding: base64\r\n\r\n";
$dataToUpload .= base64_encode($fileContent) . "\r\n";
$dataToUpload .= "--{$boundary}--";
$options = [
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $dataToUpload,
CURLOPT_HTTPHEADER => [
'Authorization:Bearer ' . $accessToken,
'Content-Type: multipart/related; boundary=' . $boundary,
],
//In case you're in Windows, sometimes will throw error if not set SSL verification to false
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
];
//In case you need a proxy
//$options[CURLOPT_PROXY] = 'http://127.0.0.1:1087';
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
return $result;
}
$uploadFilePath = '<YOU-FILE-ABS-PATH>';
$accessToken = '<YOU-ACCESS-TOKEN>';
$ret = uploadByCurl($uploadFilePath, $accessToken);
var_dump($ret);
Response json:
{
"kind": "drive#file",
"id": "1lkuCTeMooRmde8uzNa7COUTTCLAk_jdq",
"name": "timg (12).jpeg",
"mimeType": "image/jpeg"
}
But when I'm trying to use Guzzle6(An curl client written by PHP) to do the same thing, the file(image file) can successfully upload but its name is "Untitled" and I can't preview the image(see the screenshot below):
Here is my code snippet by using Guzzle:
function uploadByGuzzle($uploadFilePath, $accessToken){
$boundary = md5(mt_rand() . microtime());
//MetaData
$params = json_encode([
'name' => basename($uploadFilePath),
'description' => 'This is a test',
]);
$fileContent = file_get_contents($uploadFilePath);
$dataToUpload = "--{$boundary}\r\n";
$dataToUpload .= "Content-Type: application/json\r\n\r\n";
$dataToUpload .= "{$params}\r\n";
$dataToUpload .= "--{$boundary}\r\n";
$dataToUpload .= "Content-Transfer-Encoding: base64\r\n\r\n";
$dataToUpload .= base64_encode($fileContent) . "\r\n";
$dataToUpload .= "--{$boundary}--";
$GuzzleConfig = [
'base_uri' => 'https://www.googleapis.com/upload/drive/v3/files/',
'timeout' => 30.0,
];
//In case you need a proxy
$GuzzleConfig['proxy'] = 'http://127.0.0.1:1087';
//GuzzleHttp
$client = new Client($GuzzleConfig);
$uri = '?uploadType=multipart';
$response = $client->request('POST', $uri, [
'verify' => false,
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'Content-Type: multipart/related; boundary=' . $boundary,
],
'body' => $dataToUpload,
]);
$string = $response->getBody()->getContents();
return $string;
}
$uploadFilePath = '<YOU-FILE-ABS-PATH>';
$accessToken = '<YOU-ACCESS-TOKEN>';
$ret = uploadByGuzzle($uploadFilePath, $accessToken);
var_dump($ret);
I think that the request body is correct. In your script, Content-Type is not correct. In this case, I think that body is sent as application/octet-stream. By this, the file of Untitled is created. And I think that it is the text data of the request body.
So how about this modification?
From:
'Content-Type' => 'Content-Type: multipart/related; boundary=' . $boundary,
To:
'Content-Type' => 'multipart/related; boundary=' . $boundary,
I am trying to send a confirmation email once the user has used the form I am creating via acf.
Below is the code I am using in a plugin, but somehow the wp_email is not sending an email. Not receiving it, nor did I receive an error.
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new_post' ) {
return $post_id;
}
// Create a new post
$post = array(
'id' => $post_id,
'post_status' => 'publish',
'post_title' => $_POST['acf']['_post_title'],
'email' => $_POST['acf']['field_5d49dcb49a31f'],
'bedrag' => $_POST['acf']['field_5d49dd749a321'],
'periodiek' => $_POST['acf']['field_5d49de569a322'],
);
// // insert the post
$post_id = wp_insert_post( $post );
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$name = get_field('post_title', $post_id);
$email = get_field('email', $post_id);
$body_text = get_field('email_tekst', 'option');
$to = $name . ' <' . $email . '>' . "\r\n";
$headers = array('Content-Type: text/html; charset=UTF-8', 'From: Some name <info#somedomain.com> <noreply#'.$_SERVER['HTTP_HOST'].'>');
$subject = 'Bedankt voor uw donatie: ' . get_field('bedrag', $post_id) . ' ' . get_field('periodiek', $post_id);
$body = $body_text;
wp_mail($to, $subject, $body, $headers );
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post');
Save the form works, as I see data in the backend.
But I am just not receiving the email.
To make sure that emails are send, I am using a plugin (wp mail smtp).
Do I miss anything?
Ok, I know what was going wrong.
I didn’t used the correct priority.
Now using the following code:
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
add_action('acf/save_post' , 'my_save_post', 15);
function my_save_post($post_id) {
if( get_post_type($post_id) !== 'donations' ) {
return;
}
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$name = get_field('post_title', $post_id);
$email = get_field('email', $post_id);
$body_text = get_field('email_tekst', 'option');
$to = $email;
$headers = array('From: some name <some email> <noreply#'.$_SERVER['HTTP_HOST'].'>');
$subject = 'Bedankt voor uw donatie: ' . get_field('bedrag', $post_id) . ' ' . get_field('periodiek', $post_id);
$message = $body_text;
wp_mail($to, $subject, $message, $headers );
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
}
The priority is now 15, so runs after the save was done.
i'm using in my symfony project Json data and in my controller i return data with New Response , it would be like :
{"cn":"dvsdvsdvergfe","gender":"M","fgff":"data","mail":"sino#hotmail.fr","sn":"SINO","uid":"sino"}
but if i return my data in a JsonResponse i have data like this format :
"{\"cn\":\"dvsdvsdvergfe\",\"gender\":\"M\",\"fgff\":\"data\",\"mail\":\"sino#hotmail.fr\",\"sn\":\"SINO\",\"uid\":\"sino\",
}"
the controller :
public function getUserByUidAction($uid)
{
$url = self::Ws_URL . self::Ws_PORT . self::Ws_GetUserByUID . $uid;
$headers = array() ;
$headers[] = "auth_token: ".self::Ws_Token ;
$headers[] = "Content-Type: application/json" ;
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
"http" =>array(
"method" => "GET",
"header" => "auth_token: ".self::Ws_Token
)
);
$response = file_get_contents($url, true, stream_context_create($arrContextOptions));
$viewHandler = $this->get('fos_rest.view_handler');
$view = View::create($response);
$view->setFormat('json');
return $viewHandler->handle($view);
return New Response($response) ;
}
what is happened ?
I use Request solution for ajax-request, but I get an error:
reqwest.min.js:6 Mixed Content: The page at 'https://...' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://...'. This request has been blocked; the content must be
served over HTTPS.
Server-side code (i'm using wordpress plugin for this):
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users
function wpse144893_search_data(){
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$errors = array();
$data = array(
'status' => 'error',
'message' => '',
'result' => array()
);
if(!isset($_REQUEST['term']) || empty($_REQUEST['term']))
$errors[] = 'No search term given!';
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit']))
$limit = 10;
else
$limit = (int) $_REQUEST['limit'];
if(empty($errors)){
$term = sanitize_text_field($_REQUEST['term']);
// setup query data
$args = array(
'posts_per_page' => $limit,
's' => $term
);
$query = new WP_Query($args); // run query
$results = array();
if($query->have_posts()): while($query->have_posts()): $query->the_post();
$post_item = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'permalink' => get_permalink()
);
$results[] = $post_item;
endwhile;
$data['status'] = 'success';
$data['message'] = 'Results found!';
$data['result'] = $results;
else:
$errors[] = 'No post found!';
$data['message'] = $errors;
endif;
}
echo json_encode($data); // print json
die(); // kill the script
}
Client-side code (request plugin):
reqwest({
url: 'http://...'
, type: 'json'
, method: 'get'
, crossOrigin: true
, withCredentials: true
, error: function (err) { alert('1'); }
, success: function (resp) {
alert('2');
}
})
I tried use this header('Content-type: application/json');header('Access-Control-Allow-Origin: *'); (see in server code above) but it does not solve the problem.
Problem is solved by moving second server to HTTPS...
I need your help with Google notifications sending which works correctly but with empty messages, title, message etc. are missing...
Any ideas ?
Here is picture how it looks like:
define( 'API_ACCESS_KEY', 'AIzaSyBBh4ddPa96rQQNxqiq_qQj7sq1JdsNQUQ' );
//$registrationIds = array( $_GET['id'] );
$user_device_key = 'eVuuhJNB3vs:APA91bGyf2iAcDEHMVe8MmYzUmNAVl08tfP4wHQFi0sIMhtlZ9PwljdEfZ8JhtfJ_O0rhXTvdJEiVbeRJaUfWn2qvHG6Gw7OjV2jSCmkUd1HK93dyocyC26_48xb0srxa5imUpqXSxMk';
$payload_info = create_payload_json("I know how to send push notifications!");
// API access key from Google API's Console
define('API_ACCESS_KEY', 'AIzaSyAjcvboyovxihsZBtrs2FmVkFbLs-bNk1k');
// prep the bundle
$msg = array
(
'message' => json_decode($payload_info)->aps->alert,
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$fields = array
(
'registration_ids' => array($user_device_key),
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
echo $fields;
$result = curl_exec($ch);
curl_close($ch);
return $result > 0;
function create_payload_json($message) {
//Badge icon to show at users ios app icon after receiving notification
$badge = "0";
$sound = 'default';
$payload = array();
$payload['aps'] = array('alert' => $message, 'badge' => intval($badge),'sound' => $sound);
return json_encode($payload);
}