I am having a problem transferring files using NuSOAP. I understand that you can read a file and transfer it as a string, but it's not working. Here is an example:
Client:
require('libraries/nusoap/nusoap.php');
$url = "http://www.example.com";
$client = new nusoap_client($url);
args = array('file_name' => 'myfile.zip');
$return = $client->call('getFile', array($args));
if(empty($return){
echo "WHY IN THE WORLD IS THIS EMPTY!!!!!";
}
Server:
require('libraries/nusoap/nusoap.php');
$server = new nusoap_server;
$server->configureWSDL('server', 'urn:server');
$server->wsdl->schemaTargetNamespace = 'urn:server';
$server->register('getFile',
array('value' => 'xsd:string'),
array('return' => 'xsd:string'),
'urn:server',
'urn:server#getFile');
function getFile($value){
$returnData= "";
$filePath=$value['file_path'];
$mode="r";
if (floatval(phpversion()) >= 4.3) {
$returnData= file_get_contents($filePath);
} else {
if (!file_exists($filePath)){
return -3;
}
$handler = fopen($filePath, $mode);
if (!$handler){
return -2;
}
$returnData= "";
while(!feof($handler)){
$returnData.= fread($handler, filesize($filePath));
}//end while
fclose($handler);
}//end else
return $returnData;
}
Here is the really strange part. If I return the file name or file size or something like that, it will work. It will just not return the file itself. Help please.
In the server side getFile function you should return base64_encode($returnData);
Related
I want to upload files in chunks to a URL endpoint using guzzle.
I should be able to provide the Content-Range and Content-Length headers.
Using php I know I can split using
define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of chunk
function readfile_chunked($filename, $retbytes = TRUE) {
$buffer = '';
$cnt = 0;
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, CHUNK_SIZE);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
How Do I achieve sending the files in chunk using guzzle, if possible using guzzle streams?
This method allows you to transfer large files using guzzle streams:
use GuzzleHttp\Psr7;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$resource = fopen($pathname, 'r');
$stream = Psr7\stream_for($resource);
$client = new Client();
$request = new Request(
'POST',
$api,
[],
new Psr7\MultipartStream(
[
[
'name' => 'bigfile',
'contents' => $stream,
],
]
)
);
$response = $client->send($request);
Just use multipart body type as it's described in the documentation. cURL then handles the file reading internally, you don't need to so implement chunked read by yourself. Also all required headers will be configured by Guzzle.
In magento as we use the rest url to access the data, as http://localhost/magento/api/rest/products it returns in xml format instead of that I need JSON.
I have tried below code, but no use
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody($jsonData);
in the folder \magento\app\code\core\Mage\Api\Controller\Action.php
vinox, you should override the default file Request.php. copy \app\code\core\Mage\Api2\Model\Request.php to your local directory and add the following code just before end of the getAcceptTypes() Method.
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
in other way your getAcceptTypes() method should look like this.
public function getAcceptTypes(){
$qualityToTypes = array();
$orderedTypes = array();
foreach (preg_split('/,\s*/', $this->getHeader('Accept')) as $definition) {
$typeWithQ = explode(';', $definition);
$mimeType = trim(array_shift($typeWithQ));
// check MIME type validity
if (!preg_match('~^([0-9a-z*+\-]+)(?:/([0-9a-z*+\-\.]+))?$~i', $mimeType)) {
continue;
}
$quality = '1.0'; // default value for quality
if ($typeWithQ) {
$qAndValue = explode('=', $typeWithQ[0]);
if (2 == count($qAndValue)) {
$quality = $qAndValue[1];
}
}
$qualityToTypes[$quality][$mimeType] = true;
}
krsort($qualityToTypes);
foreach ($qualityToTypes as $typeList) {
$orderedTypes += $typeList;
}
unset($orderedTypes);
$orderedTypes=Array("application/json" => 1);
return array_keys($orderedTypes);
}
I guess your $jsonData is not actually JSON. Try using a json helper
$jsonData = Mage::helper('core')->jsonEncode($data)
Hello: I have a web form that submits data to my db. I am able to create a signature image and save it within my directory. I want to save/store that signature image in my mysql db along with the record so I can call it later.
Written in CodeIgniter 2.0
here are my model and controller.
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
imagepng($img, 'signature.png');
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form);
}
}
public function insert_signature($data)
{
$sig_hash = sha1($data['output']);
$created = time();
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'first_name' => $data['fname'],
'last_name' => $data['lname'],
'signator' => $data['name'],
'signature' => $data['output'],
'sig_hash' => $sig_hash,
'ip' => $ip,
'created' => $created
);
return $this->db->insert('signatures', $data);
}
I found the function below on php.net but apparently I am doing something wrong or various things wrong. Does anyone know how to accomplish this functionality?
$imagefile = "changethistogourimage.gif";
$image = imagecreatefromgif($imagefile);
ob_start();
imagepng($image);
$imagevariable = ob_get_contents();
ob_end_clean();
Got it - For those curious here are the changes to my controller:
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
// Save to file
$file_name = trim(str_replace(" ","_",$_POST['name']));//name to used for filename
imagepng($img, APPPATH."../images/signatures/".$file_name.'.png');
$sig_name = $file_name.'.png'; //pass to model
// Destroy the image in memory when complete
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form, $sig_name);
}
}
i got a problem in PHP. i want to get all the bus stations in india. so i have made an xml request and post that xml data to given API URL. but i did not get the result. below is the .net code which is working fine. even i have used the "HttpRequest" method in php, but it gives me an error like "Fatal error: Class 'HttpRequest' not found".
can anybody help me to give me the equivalent code in php or possible ways to get the data..?
thanks in advance.
.net code (working fine)
protected void getBusServices(string journeydate)
{
XmlDocument doc = new XmlDocument();
StringReader stream;
StreamReader reader;
XmlTextReader textreader;
HttpWebRequest req;
HttpWebResponse response;
try
{
string password = "password";
DateTime dt = Convert.ToDateTime(journeydate);
string strJrneyDate = dt.ToString("MM-dd-yyyy");
string strRtDate = dt.AddDays(3).ToString("MM-dd-yyyy");
string url = Bus_Api_Url;
string RequestCommand = "<Command>GET_STATIONS</Command> <Username>username</Username> <Password>password</Password>";
req = (HttpWebRequest)WebRequest.Create(url);
string RequestData = "RequestXML=<?xml version='1.0' encoding='utf-8' ?><BusRequest xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" + RequestCommand + "</BusRequest>";
req.Method = WebRequestMethods.Http.Post;
req.ContentLength = RequestData.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
{
writer.Write(RequestData);
}
response = (HttpWebResponse)req.GetResponse();
Stream responsestream = response.GetResponseStream();
reader = new StreamReader(responsestream);
string xmlresponse = reader.ReadToEnd();
stream = new StringReader(xmlresponse);
textreader = new XmlTextReader(stream);
doc.LoadXml(xmlresponse);
DataSet ds = new DataSet();
ds.ReadXml(textreader);
}
catch (Exception ex)
{
EBUtils.Logger.LogError.Publish(ex);
}
finally
{
reader = null;
// stream = null;
reader = null;
response = null;
doc = null;
}
}
}
its really simple, check out http://php.net/manual/en/simplexml.examples-basic.php
i've used the same method lot of times, heres a little snippet from one of my active php projects.
$file = "http://the_address_of_the_xml_file.com";
if(!$xml = simplexml_load_file($file)) {
return 0;
} else { //open
$status = $xml->attributes()->statu
if($status=='ok') {//open
$bio = $xml->artist->bio;
//closed
for ($i = 0; $i < 1; $i++) {
and how about file_get_content ?
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
ha im not on top form today, in bed really unwell ;)
I would like to get content of a pdf file into a variable. I tried to do this using
file_get_contents("file.pdf")
but it's returning NULL. If I do the same with .jpg file for example it's working. Any idea how to overcome this problem? Is there another way? Thanks in advance!
Edit:
Service code:
<?php
function sendAttachment($msg){
$responsePayloadString = <<<XML
<payload:receiveReport xmlns:payload="http://wso2.org/wsfphp/samples/mtom">
<payload:reports>
<payload:report>
<payload:content xmlmime:contentType="application/pdf" xmlns:xmlmime="http://www.w3.org/2004/06/xmlmime">
<xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:report1"></xop:Include>
</payload:content>
</payload:report>
</payload:reports>
</payload:receiveReport>
XML;
$report1 = file_get_contents("samplePDF.pdf");
$responseMessage = new WSMessage($responsePayloadString,
array("attachments" => array("report1" => $report1),
"useWSA" => TRUE));
return $responseMessage;
}
$operations = array("receiveReport" => "sendAttachment");
$service = new WSService(array("operations" => $operations,
"requestXOP" => TRUE,
"useMTOM" => TRUE));
$service->reply();
?>
Client Code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
/******* FirePHP Debug *******/
require_once('../FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
/******* FirePHP Debug *******/
$requestPayloadString = <<<XML
<receiveReport></receiveReport>
XML;
try {
$client = new WSClient(
array( "to" => "http://localhost/ReportDL/ReportService.php",
"useMTOM" => TRUE,
"responseXOP" => TRUE,
"useWSA" => TRUE));
$requestMessage = new WSMessage($requestPayloadString);
$responseMessage = $client->request($requestMessage);
$cid2stringMap = $responseMessage->attachments;
$cid2contentMap = $responseMessage->cid2contentType;
if($cid2stringMap && $cid2contentMap){
foreach($cid2stringMap as $i=>$value){
$f = $cid2stringMap[$i];
$contentType = $cid2contentMap[$i];
$firephp->log($f, "pdf"); //DEBUG
}
}else{
printf("attachments not received ");
}
} catch (Exception $e) {
if ($e instanceof WSFault) {
printf("Soap Fault: %s\n", $e->Reason);
} else {
printf("Message = %s\n",$e->getMessage());
}
}
?>
Edit2:
string '%PDF-1.5
%âãÏÓ
2 0 obj
<</Length 285/Filter/FlateDecode>>stream
xœ’_KÃ0Åßó)Ä{“4i|S¨‚ÓÀžµKiçÚ0¿½i;ëýƒ#ÐÐÃýœž¦dwŽI
&ÒàV,qlÁJfŒ�%hCåÙ’;YǪÕrÿÎÿêeã|}O#\Æ0,‹<ÌXäE¯6OW°‹‡z
ñÑ
Z¸}¼t]®æ$ä’Õð³ToGÞ!5¾í»R ›4Ù<)¤:•&ž#©ù¸v’4®ƒžB®gÁ6è49X»P‚c#uÌíPñîÝÃҿ“ß|V;Hö/Å&÷Ðw?f I.MHq²Mö>w~5k$‘8Šq£ç:õÛmVçù?òi©ý'Ó-Í^$eNðÿ\¥sá6ø(¼`ßè¿Á÷
endstream
endobj
6 0 obj
<</Type/Catalog/PageMode/UseNone/Pages 3 0 R>>
endobj
7 0 obj
<</Creator(BIRT Report Engine 2.6.0 using iText version unknown.)/Producer('... (length=1231)
file_get_contents() should return FALSEif a file is unreadable - otherwise it return a string containing the files content.
The problem must lie elsewhere - start debugging your code in a procedural way with var_dump() to find out where your data is lost.
You need to add the following code at the top of your PHP page.
header("Content-type:application/pdf");
In case anyone else comes here for this, my issue was the file Permissions weren't correct for www-data. Once permissions were changed, the web server could read it and functioned as expected.
I know it's a "duh" thing, but it wasn't obvious to me at first.
if ($file_ext == 'pdf') { $content_type = "application/pdf"; }
elseif($file_ext == 'ppt') { $content_type = "application/vnd.ms-powerpoint"; }
elseif($file_ext == 'pptx') { $content_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; }
elseif($file_ext == 'xls') { $content_type = "application/vnd.ms-excel"; }
elseif($file_ext == 'xlsx') { $content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
elseif($file_ext == 'doc') { $content_type = "application/vnd.ms-word"; }
elseif($file_ext == 'docx') { $content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; }
else { $content_type = "application/octet-stream"; }
$document_contents = file_get_contents("/Server/location/to/$file");
header("Content-type: $content_type");
echo $document_contents;
die();