excuse me :: my english writing is very bad :))
I am developing a wordpress plugin and i need to get some row from custom table by rest api and excel format.
by this codes, excel file create in wordpress root and query works, but i cant download this when request address,
when request address, excell file that downloaded is empty and just writing "resourse ... " in it
please help me, thanks
add_action( 'rest_api_init', 'wpc_register_wp_api_endpoints' );
function wpc_register_wp_api_endpoints() {
register_rest_route( 'api', '/output/', array(
'methods' => 'GET',
'callback' => 'wpc_somename_search_callback',
'args' => array(
'date' => array(
'required' => true,
)
)
));
}
function wpc_somename_search_callback( $request ) {
global $wpdb;
$date = $request['date'];
$query = "SELECT * FROM {$wpdb->prefix}tickets where inroute_id=16 and date='$date'";
$list = $wpdb->get_results($query);
$jsonDecoded = json_decode( json_encode($list), true);
$fileName = 'example.csv';
$fp = fopen($fileName, 'w');
foreach($jsonDecoded as $row){
fputcsv($fp, $row);
}
fclose($fp);
header('Content-disposition: attachment; filename='.$fileName);
header('Content-type: application/json');
print $fp;
exit;
}
my request is
http://yootaabmarine.ir/wp-json/api/output/?date=13970822
I think that $jsonDecoded = json_decode( json_encode($list), true); is useless in your code, you are transforming an array to a JSON string and then transforming it back to an array, it is better to use $list directly.
$fp contains a resource, which is a PHP type in its own (see in the doc fopen function return type is resource), and a resource is completely different from a string, so you can't use print $fp;.
We could use readfile to correctly send a file to the browser, here is a solution:
function wpc_somename_search_callback( $request ) {
global $wpdb;
$date = $request['date'];
$query = "SELECT * FROM {$wpdb->prefix}tickets where inroute_id=16 and date='$date'";
$list = $wpdb->get_results($query);
$fileName = 'example.csv';
$fp = fopen($fileName, 'w');
foreach($list as $row){
fputcsv($fp, $row);
}
fclose($fp);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'. $fileName .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
readfile($fileName);
exit;
}
Beware of SQL injections, use prepared queries instead.
Related
I am trying to create a PDF file using WP Rest API. I wrote this small code on function.php. But when I call the API from the postman, it shows - Internal Server Error.
Here is my code:
add_action(
'rest_api_init',
function () {
register_rest_route(
'api',
'/get_location',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'get_location',
)
);
}
);
function get_location() {
global $wpdb;
$results = array();
require get_stylesheet_directory() . '/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
use Dompdf\Options;
$options = new Options();
$options->set( 'isRemoteEnabled', true );
// Instantiate and use the dompdf class
$dompdf = new Dompdf( $options );
$dompdf->loadHtml( 'hello world<br/>TEST' );
$dompdf->setPaper( 'A4', 'landscape' );
// Render the HTML as PDF
$dompdf->render();
$output = $dompdf->output();
$now = strtotime( 'now' );
// file_put_contents($now.".pdf", $output);
file_put_contents( get_stylesheet_directory() . '/dompdf/' . $now . '.pdf', $output );
return $results;
The above code show internal server error in postman
I'm building a site on Wordpress which is going to be using Amazon API to grab price, title and image link after inputing Amazon ASIN.
I got it working with the script I have found (pasted below) but it works only about 5 out of 6 times. Every so often the API returns price as 0.00 and empty title and image link.
Is there something I am missing? I was prepared to use CRON job to auto update products on my website periodically but with this bug some products will be pretty much "reset" to 0.00 price.
Any help would be appreciated.
code here:
<?php
$amazon_asin = get_post_meta( get_the_ID(), 'amazon_asin', true);
$response = getAmazonPrice("co.uk", $amazon_asin);
function getAmazonPrice($region, $asin) {
$xml = aws_signed_request($region, array(
"Operation" => "ItemLookup",
"ItemId" => $asin,
"IncludeReviewsSummary" => False,
"ResponseGroup" => "Medium,OfferSummary",
));
$item = $xml->Items->Item;
$title = htmlentities((string) $item->ItemAttributes->Title);
$url = htmlentities((string) $item->DetailPageURL);
$image = htmlentities((string) $item->MediumImage->URL);
$price = htmlentities((string) $item->OfferSummary->LowestNewPrice->Amount);
$code = htmlentities((string) $item->OfferSummary->LowestNewPrice->CurrencyCode);
$qty = htmlentities((string) $item->OfferSummary->TotalNew);
if ($qty !== "0") {
$response = array(
"code" => $code,
"price" => number_format((float) ($price / 100), 2, '.', ''),
"image" => $image,
"url" => $url,
"title" => $title
);
}
return $response;
}
function getPage($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$html = curl_exec($curl);
curl_close($curl);
return $html;
}
function aws_signed_request($region, $params) {
$public_key = get_option('public_key');
$private_key = get_option('private_key');
$method = "GET";
$host = "ecs.amazonaws." . $region;
$host = "webservices.amazon." . $region;
$uri = "/onca/xml";
$params["Service"] = "AWSECommerceService";
$params["AssociateTag"] = get_option('associate_tag'); // Put your Affiliate Code here
$params["AWSAccessKeyId"] = $public_key;
$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
$params["Version"] = "2011-08-01";
ksort($params);
$canonicalized_query = array();
foreach ($params as $param => $value) {
$param = str_replace("%7E", "~", rawurlencode($param));
$value = str_replace("%7E", "~", rawurlencode($value));
$canonicalized_query[] = $param . "=" . $value;
}
$canonicalized_query = implode("&", $canonicalized_query);
$string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
$signature = str_replace("%7E", "~", rawurlencode($signature));
$request = "http://" . $host . $uri . "?" . $canonicalized_query . "&Signature=" . $signature;
$response = getPage($request);
var_dump($response);
$pxml = #simplexml_load_string($response);
if ($pxml === False) {
return False;// no xml
} else {
return $pxml;
}
}
?>
Well, it seems to be a problem with Amazon Product API. If you make the same request several times, then it should either always work or not work at all.
You can ask on Amazon Product API forums about the problem: https://forums.aws.amazon.com/forum.jspa?forumID=9
You can also update your code so it does not update the product price if the title is missing from Amazon API response
I want to upload a file from external URL to the WordPress Media Library (that is common to ALL POSTS/PAGES). The return value I want to get is attachment ID in order to inject them into a shortcode (e.g. img).
I tried using IMEDIA_HANDLE_SIDELOAD but I got lost with $_FILES settings.
However, I am not sure about the parameters:
Is this the right function?
where in the code (aFile) should I place the URL I want to download from?
What is the "tmp_name" and "name"?
See my code:
// my params
$post_id = 0; // is this what makes it common to all posts/pages?
$url = 'www.some_external_url.com/blabla.png';
// example from some forum
$filepath = '/relative/path/to/file.jpg';
$wp_filetype = wp_check_filetype( basename( $filepath ), null );
$aFile["name"] = basename( $filepath );
$aFile["type"] = $wp_filetype;
$afile["tmp_name"] = $filepath;
$attach_id = $media_handle_sideload( $aFile, $post_id, 'sometitle' );
Solution:
private function _uploadImageToMediaLibrary($postID, $url, $alt = "blabla") {
require_once("../sites/$this->_wpFolder/wp-load.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/image.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/file.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/media.php");
$tmp = download_url( $url );
$desc = $alt;
$file_array = array();
// Set variables for storage
// fix file filename for query strings
preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
#unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $postID, $desc);
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
#unlink($file_array['tmp_name']);
return $id;
}
return $id;
}
How to use a shortcode attributes value in a seperate php file
I have written a shortcode which acepts parameters file and type
[includefile file='membership-booking' mtype="group"]
function shortcode_includefile( $atts){
$data= shortcode_atts( array (
'mtype' => 'post',
), $atts ) ;
$path = dirname(__FILE__) . "/shortcode_includefile/" . $atts['file']. ".php";
if(file_exists($path))
include $path;
$code = ob_get_contents();
ob_end_clean();
return $code;
}
attributes file is fixed 'membership-booking' only mtype can be either group or individual.
Now in membership-booking file i want to read attributes mtype value. on the basis of mytype value i need to echo something
In your function, you can use mtype like;
$mtype = $data["mtype"];
and you can use that variable globally like;
$mtype = "post"; // This is global
function shortcode_includefile( $atts){
$data = shortcode_atts( array (
'mtype' => 'post',
), $atts ) ;
$mtype = $data["mtype"];
$path = dirname(__FILE__) . "/shortcode_includefile/" . $atts['file']. ".php"; // You can use $mtype in this file
if(file_exists($path))
include $path;
$code = ob_get_contents();
ob_end_clean();
return $code;
}
I am having trouble with a form I created with gravityforms. This form's purpose is to grab the form's input, encrypt the password and write that data directly to a database. I have verified the database's username, password and IP.
The problem is that the form does submit, I can see the entry, but no data is written to the database. it just stucks with a loading circle next to the submit button.
Here is the code I use inside my functions.php file:
add_action("gform_after_submission_1", "create_account", 10, 2);
function create_account($entry, $form) {
define('mySQL_hostname', '<ip>'); //database IP
define('mySQL_database', '<database name>'); //database name
define('mySQL_username', '<user>'); //database user
define('mySQL_password', '<pass>'); //database password
$db_link = mysql_pconnect( mySQL_hostname, mySQL_username, mySQL_password )
or die( 'Error connecting to mysql<br><br>'.mysql_error() );
function l2j_encrypt($password) {
return base64_encode(pack("H*", sha1(utf8_encode($password))));
}
$str = l2j_encrypt($entry["2"]);
$user = $entry["1"];
$currdate = date('Y-m-d H:i:s');
$email = $entry["3"];
$db_select = mysql_select_db( mySQL_database, $db_link )
or die( 'Error connecting to Database<br><br>'.mysql_error() );
if ($user == '') { print'Incorrect UserID'; mysql_close(); }
else {
$db_add = mysql_query( "INSERT INTO `accounts` VALUES ('$user', '$str', '0', '0', '', '1', '$email', '$currate')" )
or die( 'Error: '.mysql_error() );
}
mysql_close();
}
Also, what's the deal with the 10,2 parameters? I couldn't find anything that explains those...
Note that the above code, when in a separate php file, combined with an html form, work just fine....
Any help?
P.S: Can anyone help me build a function that submit this data to an external php file? In case I cannot make this work....
After playing around with gravity for a bit, i managed to find a workaround.
add_action("gform_after_submission_6", "set_page_log", 10, 2);
function set_page_log($entry, $form){
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
if($form["id"] == 6){//checking if the correct form is being used or not (optional)
$data = array(
"item1" => $entry["2"],
"item2" => $entry["5"],
"item3" => $entry["4"]
);
post_to_url("http://www.example.com/post_data.php", $data);
//you can make changes to the data passed by gravity at the above url
}
}
I have tested the above code with Gravity 1.6 and WP 3.5.1.