php code for powerpoint2pdf in convertapi not working - php

I use the following to convert a doc file to pdf in PHP:
function CallToApi($fileToConvert, $pathToSaveOutputFile, $apiKey, &$message,$unique_filename)
{
try
{
$fileName = $unique_filename.".pdf";
$postdata = array('OutputFileName' => $fileName, 'ApiKey' => $apiKey, 'file'=>"#".$fileToConvert);
$ch = curl_init("http://do.convertapi.com/word2pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
$header=ParseHeader(substr($result,0,$headers["header_size"]));
$body=substr($result, $headers["header_size"]);
curl_close($ch);
if ( 0 < $headers['http_code'] && $headers['http_code'] < 400 )
{
// Check for Result = true
if (in_array('Result',array_keys($header)) ? !$header['Result']=="True" : true)
{
$message = "Something went wrong with request, did not reach ConvertApi service.<br />";
return false;
}
// Check content type
if ($headers['content_type']<>"application/pdf")
{
$message = "Exception Message : returned content is not PDF file.<br />";
return false;
}
$fp = fopen($pathToSaveOutputFile.$fileName, "wbx");
fwrite($fp, $body);
$message = "The conversion was successful! The word file $fileToConvert converted to PDF and saved at $pathToSaveOutputFile$fileName";
return true;
}
else
{
$message = "Exception Message : ".$result .".<br />Status Code :".$headers['http_code'].".<br />";
return false;
}
}
catch (Exception $e)
{
$message = "Exception Message :".$e.Message."</br>";
return false;
}
}
I now want to use the same to convert a ppt to pdf. For which I change
$ch = curl_init("http://do.convertapi.com/word2pdf");
to
$ch = curl_init("http://do.convertapi.com/PowerPoint2Pdf");
but I am not sure why it isnt converting the given input. Is there something that I may be missing?

It's due to PHP 5.6.
You need to add this line to your code as well
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
See:Backward incompatible changes (at the bottom).

Related

VAT Number Validation Function Not Working

I'm trying to write a vat number validation function which checks a vat number to see if it's valid.
Currently i've got this
function tep_check_vatnum($countries_id, $vatnum) {
$country = tep_get_countries_with_iso_codes($countries_id);
$iso = $country['countries_iso_code_2'];
if($iso == "GB"){
return false;
} else {
$url = "http://isvat.appspot.com/$iso/$vatnum";
$session = curl_init();
curl_setopt($session, CURLOPT_URL, $url);
// curl_setopt($session, CURLOPT_HTTPGET, 1);
// curl_setopt($session, CURLOPT_HEADER, false);
// curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
//echo "<!-- NOTE:" . $response . "-->";
curl_close($session);
if($response == "true"){
return true;
} else {
return false;
}
}
}
The service i'm using http://isvat.appspot.com is working, But it's not working.
EDIT
Hmm no luck. By not working, it keeps giving me an error saying the vat number isn't valid. On the create account form i've got this code.
<?php echo tep_draw_input_field('vatnum', '', 'class="input"') . ' ' . (tep_not_null(ENTRY_COMPANY_TEXT) ? '<span class="inputRequirement">' . ENTRY_COMPANY_TEXT . '</span>': ''); ?>
if (is_numeric($country) == false) {
$error = true;
$messageStack->add('create_account', ENTRY_COUNTRY_ERROR);
} else {
if(strlen($vatnum) != 0){
if(is_numeric($vatnum) == false || tep_check_vatnum($country, $vatnum) == false){
$error = true;
$messageStack->add('create_account', "VAT Number is not a valid EU, non-UK VAT no.");
}
}
I guess there might be a problem invoking cURL. The good news is, you probably don't need to. ;) Give this a try:
function tep_check_vatnum($countries_id, $vatnum) {
$country = tep_get_countries_with_iso_codes($countries_id);
$iso = $country['countries_iso_code_2'];
if($iso == "GB"){
return false;
} else {
$url = "http://isvat.appspot.com/$iso/$vatnum";
$context = stream_context_create(array(
'http' => array(
'proxy' => 'http://PROXY_IP:PROXY_PORT'
),
));
$fp = fopen($url,'r',$context);
$response = fgets($fp);
fclose($fp);
//echo "<!-- NOTE:" . $response . "-->";
if($response == "true"){
return true;
} else {
return false;
}
}
}
It should work even if you don't have the cURL extension enabled.
Edit: As Michas said, it is difficult to find the problem with your original code without knowing what you mean by "not working". You could try to get some more information about the problem by stating error_reporting(E_ALL) or curl_error($session).
Possible causes: cURL is not installed or configured correctly or a proxy or firewall is blocking your request. While the code I suggested would eliminate the first one, the second one might also apply using it, depending on your settings.
Edit 2: Added simple proxy configuration

PHP and timestamp protocol

In PHP i must sign a document with the Timestamp Protocol via HTTP (RFC 3161) using ARUBA as CA.
The Aruba's documentation says:
To time-stamp a datum you must call the url https://servizi.arubapec.it/tsa/ngrequest.php
with a POST method. In the POST body you must insert the structure TimeStampReq (RFC 3161)
encode in DER.
How can i make the request using the php?
you can use curl function in php.
Ok, This is part of my edited/modified tcpdf.php.
//Send request to TSA Server with Curl
if(extension_loaded('curl')) {
$hdaLog .= "\nCurl was already Loaded\nCurl is sending tsRequest to \"".$this->timestamp_url."\"";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->timestamp_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERAGENT, '1');
curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data);
$tsResponse = curl_exec($ch);
if($tsResponse != false) {
$hdaLog .= "\ntsRequest is sent";
} else {
hdaLog("$hdaLog\ncan't send tsRequest, Timestamp failed",'w');
}
//parse ts response
$hexTs = bin2hex($tsResponse);
$tsparse = asn1parse($hexTs);
$tsparse0 = asn1parse($tsparse[0][1]);
if(count($tsparse0 > 1)) { //Remove response status data, only take timeStampToken
$timeStamp = seq($tsparse0[1][1]);
} else {
$timeStamp = seq($tsparse0[0][1]);
}
//Add timestamp to TCPDF Signature
$timeStamp = seq("060B2A864886F70D010910020E".set($timeStamp));
$pkcs7 = int($pa1[0][1]).seq($pa1[1][1]).seq($pa1[2][1]).explicit(0, $pa1[3][1]).seq($pa1[4][1]).oct($pa1[5][1]);
$time = seq($pkcs7.explicit(1,$timeStamp));
$aa=seq(int(1). set($p3[1][1]).seq($p3[2][1]).explicit(0, $p3[3][1]).set($time));
$hdaSignature = seq("06092A864886F70D010702".explicit(0,($aa)))."0000";
$signature = $hdaSignature;
hdaLog("$hdaLog\nTimestamp Success");
} else {
$hdaLog .= "\nCurl was not loaded, trying to load it...";
if(#dl('php_curl.dll')) {
$hdaLog .= "\nCurl successfully Loaded";
} else {
hdaLog("$hdaLog\nCurl failed to load timestamping failed", 'w');
}
}

convert doc to pdf in php

I need to convert doc file in pdf format
for that I am following saaspose functions mentioned below
(http://api.saaspose.com/v1.0/words/help)
I am not getting an error and a garbage file is uploaded along with doc file but I need to upload pdf file with same doc contents.
private function convertDocToPdf($inputFileName,$outputFileName)
{
$doc = new WordDocument("");//Word document is a class to create new document
$result = $doc->ConvertLocalFile($inputFileName, $outputFileName,"pdf");
}
private function ConvertLocalFile($input_path, $output_path, $output_format) {
try {
$str_uri = "http://api.saaspose.com/v1.0/words/convert?format=" + $output_format;
$signed_uri = Sign($str_uri);
$responseStream = uploadFileBinary($signed_uri, $input_path, "xml");
$v_output = ValidateOutput($responseStream);
if ($v_output === "") {
if ($output_format == "html")
$save_format = "zip";
else
$save_format = $output_format;
saveFile($responseStream,$outputFilename);
return "";
}
else
return $v_output;
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
public static function saveFile($input, $fileName){
$fh = fopen($fileName, 'w') or die("can't open file");
fwrite($fh, $input);
fclose($fh);
}
public static function Sign($UrlToSign) {
// parse the url
$url = parse_url($UrlToSign);
if (isset($url['query']) == "")
$urlPartToSign = $url['path'] . "?appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa;
else
$urlPartToSign = $url['path'] . "?" . str_replace(" ","%20",$url["query"]) . "&appSID=" . SaasposeApp::$AppSID;
// Decode the private key into its binary format
$decodedKey = self::decodeBase64UrlSafe(87c027855aebf72e204b3bcd710de1c0);
// Create a signature using the private key and the URL-encoded
// string using HMAC SHA1. This signature will be binary.
$signature = hash_hmac("sha1", $urlPartToSign, $decodedKey, true);
$encodedSignature = self::encodeBase64UrlSafe($signature);
if (isset($url['query']) == "")
return $url["scheme"] . "://" . $url["host"] . str_replace(" ", "%20",$url["path"]) . "?appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa . "&signature=" . $encodedSignature;
else
return $url["scheme"] . "://" . $url["host"] . str_replace(" ", "%20",$url["path"]) . "?" . str_replace(" ","%20",$url["query"]) . "&appSID=" . 1fc17cb5-6c47-462e-9dfd-d1a9525220fa . "&signature=" . $encodedSignature;
}
public static function uploadFileBinary($url, $localfile, $headerType="XML") {
$headerType = strtoupper($headerType);
$fp = fopen($localfile, "r");
$session = curl_init();
curl_setopt($session, CURLOPT_VERBOSE, 1);
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_PUT, 1);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($session, CURLOPT_HEADER, false);
if ($headerType == "XML") {
curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
} else {
curl_setopt($session, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
}
curl_setopt($session, CURLOPT_INFILE, $fp);
curl_setopt($session, CURLOPT_INFILESIZE, filesize($localfile));
$result = curl_exec($session);
//$error = curl_error($session);
//$http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
curl_close($session);
fclose($fp);
return $result;
}
public static function ValidateOutput($result)
{
$string = (string)$result;
$validate = array("Unknown file format.", "Unable to read beyond the end of the stream",
"Index was out of range", "Cannot read that as a ZipFile", "Not a Microsoft PowerPoint 2007 presentation",
"Index was outside the bounds of the array", "An attempt was made to move the position before the beginning of the stream",
);
$invalid = 0;
foreach ($validate as $key => $value) {
$pos = strpos($string, $value);
if ($pos === 1)
{
$invalid = 1;
}
}
if($invalid == 1)
return $string;
else
return "";
}
Kindly provide me the solution because this error hampers my work terribly.

PHP PROXY having tough time for "POST" Data but able to use GET

http://benalman.com/code/projects/php-simple-proxy/examples/simple/
I am exactly following above Blog for Using PHP Proxy setting for Cross Domain. I am using XHR. I am able to successful to use GET method. But While using POST I am getting error CODE 200 and Empty XML in reply object.
However when i am using the simple XHR Code without phpproxy with below setting of google. chrome.exe --disable-web-security. I am successful for GET and POST both.
I am sure i am wrong somewhere in XHR.Send(Mydata). But if i was wrong in this method than i could not have been able to send success full post method.
Please help. I am novice in PHP i am sure i am missing something in PHP code that would enable me to post successfull. Below is crux of PHP code.
$enable_jsonp = true;
$enable_native = false;
$valid_url_regex = '/.*/';
$url = $_GET['url'];
if (!$url)
{
// Passed url not specified.
$contents = 'ERROR: url not specified';
$status = array(
'http_code' => 'ERROR'
);
}
else if (!preg_match($valid_url_regex, $url)) {
// Passed url doesn't match $valid_url_regex.
$contents = 'ERROR: invalid url';
$status = array(
'http_code' => 'ERROR'
);
}
else
{
$ch = curl_init($url);
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
}
if ($_GET['send_cookies'])
{
$cookie = array();
foreach ($_COOKIE as $key => $value)
{
$cookie[] = $key . '=' . $value;
}
if ($_GET['send_session'])
{
$cookie[] = SID;
}
$cookie = implode('; ', $cookie);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_GET['user_agent'] ? $_GET['user_agent'] : $_SERVER['HTTP_USER_AGENT']);
list($header, $contents) = preg_split('/([\r\n][\r\n])\\1/', curl_exec($ch), 2);
$status = curl_getinfo($ch);
curl_close($ch);
}
// Split header text into an array.
$header_text = preg_split('/[\r\n]+/', $header);
if ($_GET['mode'] == 'native')
{
if (!$enable_native)
{
$contents = 'ERROR: invalid mode';
$status = array(
'http_code' => 'ERROR'
);
}
// Propagate headers to response.
foreach ($header_text as $header)
{
if (preg_match('/^(?:Content-Type|Content-Language|Set-Cookie):/i', $header))
{
header($header);
}
}
print $contents;
}
else
{
// $data will be serialized into JSON data.
$data = array();
// Propagate all HTTP headers into the JSON data object.
if ($_GET['full_headers'])
{
$data['headers'] = array();
foreach ($header_text as $header)
{
preg_match('/^(.+?):\s+(.*)$/', $header, $matches);
if ($matches)
{
$data['headers'][$matches[1]] = $matches[2];
}
}
}
// Propagate all cURL request / response info to the JSON data object.
if ($_GET['full_status'])
{
$data['status'] = $status;
}
else
{
$data['status'] = array();
$data['status']['http_code'] = $status['http_code'];
}
// Set the JSON data object contents, decoding it from JSON if possible.
$decoded_json = json_decode($contents);
$data['contents'] = $decoded_json ? $decoded_json : $contents;
// Generate appropriate content-type header.
$is_xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
header('Content-type: application/' . ($is_xhr ? 'json' : 'x-javascript'));
// Get JSONP callback.
$jsonp_callback = $enable_jsonp && isset($_GET['callback']) ? $_GET['callback'] : null;
// Generate JSON/JSONP string`enter code here`
$json = json_encode($data);
print $jsonp_callback ? "$jsonp_callback($json)" : $json;
}

check a url is valid or not and valid XML in php

I'm wanted to read a rss feed and store it.for this I m using:-
<?php
$homepage = file_get_contents('http://www.forbes.com/news/index.xml');
$xml = simplexml_load_string($homepage);
echo '<pre>';
print_r($xml);
?>
but first I want to check
1.URL is valid or not ,means if its response time of
$homepage = file_get_contents('http://www.forbes.com/news/index.xml');
is less than 1 minutes and the url address is correct
2.Then check the File(http://www.forbes.com/news/index.xml) have a valid XML data or not.
if valid XML then show response time else show error.
answer Of MY QUESTION:
Thanks everybody for your help and suggestion.I solved this problem. for this I wrote this code
<?php
// function() for valid XML or not
function XmlIsWellFormed($xmlContent, $message) {
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML($xmlContent);
$errors = libxml_get_errors();
if (empty($errors))
{
return true;
}
$error = $errors[ 0 ];
if ($error->level < 3)
{
return true;
}
$lines = explode("r", $xmlContent);
$line = $lines[($error->line)-1];
$message = $error->message . ' at line ' . $error->line . ': ' . htmlentities($line);
return false;
}
//function() for checking URL is valid or not
function Visit($url){
$agent = $ch=curl_init();
curl_setopt ($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch,CURLOPT_VERBOSE,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_SSLVERSION,3);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
$page=curl_exec($ch);
//echo curl_error($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300) return true;
else return false;
}
$url='http://www.forbes.com/news/index.xml';
if (Visit($url)){
$xmlContent = file_get_contents($url);
$errorMessage = '';
if (XmlIsWellFormed($xmlContent, $errorMessage)) {
echo 'xml is valid';
$xml = simplexml_load_string($xmlContent);
echo '<pre>';
print_r($xml);
}
}
?>
If the url is not valid file_get_contents would fail.
To check if the xml is valid
simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml'))
That would return true if its and would fail entirely if it isn't.
if(simplexml_load_string(file_get_contents('http://www.forbes.com/news/index.xml'))){
echo "yeah";
}else { echo "nah";}
This page has a snippet with a validator for a URL using regular expressions. The function and usage:
function isValidURL($url)
{
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
if(!isValidURL($fldbanner_url))
{
$errMsg .= "* Please enter valid URL including http://<br>";
}
if (!filter_var('anyurl',FILTER_VALIDATE_URL))
echo "Wrong url";
end;
http://php.net/manual/en/filter.filters.validate.php

Categories