Related
I have found pdf to byte array and vice-versa in java,dotnet and python. But i want to convert pdf to byte array in php laravel. I am using "IMUIS" which is accounting software solution and need to sending journal entries from laravel lumen to "IMUIS" for processing.But it gives the error after converting.
"Foutmelding": "Kan een object van het type System.String niet converteren naar het type System.Byte[]."
In english that means
"Error message": "Can not convert a System.String object to the System.Byte [] type."
The documentation is given here:
doc link
Here is the code for it.
public function saveJournal($values = '') {
//echo "adasd";dd();
$partnerKey = $values->input('Partnerkey');
$omgevingscode = $values->input('Environmentcode');
$file = file_get_contents($values->file('Pdffile'));
$str = base64_encode($file);
$options = array(
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_URL => env('IMUIS_URL'),
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_CLASSMAP => ClassMap::get(),
);
$login = new \mysdk\ImuisSDK\ServiceType\Login($options);
if ($login->Login(new \mysdk\ImuisSDK\StructType\Login($partnerKey, $omgevingscode)) !== false) {
$sessionid = $login->getResult()->SessionId;
}
$array = [
'BOE' => [
'JR' => '2018',
'PN' => '5',
'DAGB' => 20,
'REK' => 20032,
'TEGREK' => '40',
'FACT' => 0,
'BTW' => 4,
'BEDRBOEK' => 123.45,
'DAT' => '08-05-2018',
'OPM' => 'Anand testing from wsdl',
'BEDRBTW' => 21,
'FACT' => 0,
'OMSCHR' => 'Testing from wsdl api',
'BOEKSTUK' => 2018075
],
'DIGDOS' => [
'FILE' => $str
]
];
$journaalpost = ArrayToXml::convert($array, 'NewDataSet');//convert array to xml string
$create = new \mysdk\ImuisSDK\ServiceType\Create($options);
if ($create->CreateJournaalpost(new \mysdk\ImuisSDK\StructType\CreateJournaalpost($partnerKey, $omgevingscode, $sessionid, $journaalpost)) !== false) {
$jsonResponse = $create->getResult();
} else {
$jsonResponse = $create->getLastError();
}
return $jsonResponse;
}
and here is the response as well:
{
"success": true,
"result": {
"CreateJournaalpostResult": false,
"Journaalpost": "<?xml version=\"1.0\"?>\n<NewDataSet><BOE><JR>2018</JR><PN>5</PN><DAGB>20</DAGB><REK>20032</REK><TEGREK>40</TEGREK><FACT>0</FACT><BTW>4</BTW><BEDRBOEK>123.45</BEDRBOEK><DAT>08-05-2018</DAT><OPM>Anand testing from wsdl</OPM><BEDRBTW>21</BEDRBTW><OMSCHR>Testing from wsdl api</OMSCHR><BOEKSTUK>2018075</BOEKSTUK></BOE><DIGDOS><FILE>JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAyIDAgUgovQ29udGVudHMgNCAwIFI+PgplbmRvYmoKNCAwIG9iago8PC9GaWx0ZXIgL0ZsYXRlRGVjb2RlIC9MZW5ndGggMzg2Pj4Kc3RyZWFtCniclZNPb9pAEMXvfIp3TA8Zdme93jE3G0xFJWgKJtdolbhICTYU6L9v3zWEGKnUVeST1++9+b2xzfjUU2QdfvayAv2xRkJKofiKvOh9g00ssUCFS0xMzFDNY0uxw2OF/kRjtMGXxms06QSOLUnwP+Fmkd+lyMr9wddP+9r7aoDxfFE8NOfaKqtZO+PoV7X+gOK5mdekSBhg/opJfb0qK+9fDthsB2Cl5VbZWx1D80DZAbtzhiIX2iiSJGBTIoLd6mo1hRXesGMRSuxx3ixNpxjl2aRY5vPX1NDwzcASk1GXjnE6LJbL+Ww5nV51RCykokvHZDZMF5+R5aN5+rF1BJ2xcDoiY1DBSmBT5/s1FqceDPl3D8fEpxmj8schLB/DTbX19e+OJq1Hc+Q6CrTCJBzwFeUrhQ1fTfROitYTs+mAaHVamU4KI8TmnRStJ+Zr0WeKVvefVbBu/prjS6/333e+fiwx9bVflbs9MrqnDpjWq7WRDpoLYSTOUXyxwD9RUucvCmVuZHN0cmVhbQplbmRvYmoKMSAwIG9iago8PC9UeXBlIC9QYWdlcwovS2lkcyBbMyAwIFIgXQovQ291bnQgMQovTWVkaWV5s7I11RFTyPO/t9OL74tl5/das6enN0bXwr//AKZ629kqeo76x9P/AOOs4y+N/wDK6nJuq/7nerWTI6zQrTReVjEVir+fVST/AF1m6Wrf7W+uMQ+o/D744dNdW2I8fKx2Ny8nCOrKu5j18zJOGq/JoeLX9ndp47YfR9t7+zUmmy59IPG9wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABuIAowMDAwMDc2NDgzIDAwMDAwIG4gCjAwMDAwNzY1NTkgMDAwMDAgbiAKdHJhaWxlcgo8PAovU2l6ZSAxMQovUm9vdCAxMCAwIFIKL0luZm8gOSAwIFIKPj4Kc3RhcnR4cmVmCjc2NjA5CiUlRU9GCg0KCiAgICAgIA==</FILE></DIGDOS></NewDataSet>\n",
"Primarykey": null,
"Foutmelding": "Kan een object van het type System.String niet converteren naar het type System.Byte[]."
}
}
To convert PDF to byte array you will have to read the document using file_get_contents() and then parse it by function unpack().
<?php
public function saveJournal($values = '') {
$partnerKey = $values->input('Partnerkey');
$omgevingscode = $values->input('Environmentcode');
$file = file_get_contents($values->file('Pdffile'));
$byte_array = unpack("C*",$file);
$base64_encode = base64_encode(serialize($byte_array));
$options = array(
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_URL => env('IMUIS_URL'),
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_CLASSMAP => ClassMap::get(),
);
$login = new \mysdk\ImuisSDK\ServiceType\Login($options);
if ($login->Login(new \mysdk\ImuisSDK\StructType\Login($partnerKey, $omgevingscode)) !== false) {
$sessionid = $login->getResult()->SessionId;
}
$array = [
'BOE' => [
'JR' => '2018',
'PN' => '5',
'DAGB' => 20,
'REK' => 20032,
'TEGREK' => '40',
'FACT' => 0,
'BTW' => 4,
'BEDRBOEK' => 123.45,
'DAT' => '08-05-2018',
'OPM' => 'Anand testing from wsdl',
'BEDRBTW' => 21,
'FACT' => 0,
'OMSCHR' => 'Testing from wsdl api',
'BOEKSTUK' => 2018075
],
'DIGDOS' => [
'FILE' => $base64_encode
]
];
$journaalpost = ArrayToXml::convert($array, 'NewDataSet');//convert array to xml string
$create = new \mysdk\ImuisSDK\ServiceType\Create($options);
if ($create->CreateJournaalpost(new \mysdk\ImuisSDK\StructType\CreateJournaalpost($partnerKey, $omgevingscode, $sessionid, $journaalpost)) !== false) {
$jsonResponse = $create->getResult();
} else {
$jsonResponse = $create->getLastError();
}
return $jsonResponse;
}
?>
I think the problem is that WsdlToPhp has constructed client code which is sending the PDF entity as a String, when it needs to be a byte[].
So I think the problem may be in code that is not shown here.
Can you take a look at the code generated by WsdlToPhp and see if you have any flexibility in how the $journaalpost is serialized to see if you can fix in there?
// Convert the Base64 string back to text.
var byteString = atob(data.reportBase64Bytes);
// Convert that text into a byte array.
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// Blob for saving.
var blob = new Blob([ia], { type: "application/pdf" });
// Tell the browser to save as report.pdf.
saveAs(blob, "report.pdf");
// Alternatively, you could redirect to the blob to open it in the browser.
//document.location.href = window.URL.createObjectURL(blob);
There is a "bug" in the IMUIS software so it cant be possible to link a pdf file from php. Its may be done by Dotnet because its native language and the entire system built by it. Thanks to all of my SO friends for your efforts to helps me to find the issue, i have confirmed this information after call support. So in the future no one get stuck (afterall maybe end of 2018) :)
I am uploading a INI file in Codeigniter.
I file upload a file with some parameters but its values are blank, and i store the file and file-path in database.
Now, I want to let user write some values to that file.
So i open the file and let user add some values to it.
But when i save the file its doesn't get stored the way i want.
Current Result
SipUserName = ""
SipAuthName = ""
DisplayName = ""
Password = ""
Domain = ""
Proxy = ""
Port = ""
ServerMode = ""
UCServer = 123456
UCPassword = 123456
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS = ""
RTPToS = 123456
LogLevel = 123456
Expected Result:
[INIDetails]
SipUserName =
SipAuthName =
DisplayName =
Password =
Domain =
Proxy =
Port =
ServerMode =
UCServer = 123456
UCPassword = 123456
[DialPlan]
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456
[Advanced]
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS =
RTPToS = 123456
LogLevel = 123456
Below is my code:
public function edit_ini($id)
{
/*The ID wen get from View's URI*/
$path = "./uploads/";
$site = $this->session->userdata('site');
/*Set the path to open the file*/
$this->db->select('*');
$this->db->where('site_key',$site);
$this->db->where('id',$id);
/*Here the id it the ID we got in URI from View*/
$this->db->from('base_ini');
$query = $this->db->get();
$result = $query->row();
$filename= $result->base_ini_filename;
$path= $result->file_path;
echo $this->db->last_query();
/*Setting the Path and the filename from database.*/
file_get_contents($path.$filename);
/*Get All The Contents from that file*/
$this->data['params'] = $this->parameter_m->get();
/*Getting the parameters to display on view*/
$this->data['parameters'] = parse_ini_file($path.$filename,true);
$insert = array(
'SipUserName' => $this->input->post('SipUserName'),
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'UCServer' => $this->input->post('UCServer'),
'UCPassword' => $this->input->post('UCPassword'),
'DP_Exception' => $this->input->post('DP_Exception'),
'DP_Rule1' => $this->input->post('DP_Rule1'),
'DP_Rule2' => $this->input->post('DP_Rule2'),
'OperationMode' => $this->input->post('OperationMode'),
'MutePkey' => $this->input->post('MutePkey'),
'Codec' => $this->input->post('Codec'),
'PTime' => $this->input->post('PTime'),
'AudioMode' => $this->input->post('AudioMode'),
'SoftwareAEC' => $this->input->post('SoftwareAEC'),
'EchoTailLength' => $this->input->post('EchoTailLength'),
'PlaybackBuffer' => $this->input->post('PlaybackBuffer'),
'CaptureBuffer' => $this->input->post('CaptureBuffer'),
'JBPrefetchDelay' => $this->input->post('JBPrefetchDelay'),
'JBMaxDelay' => $this->input->post('JBMaxDelay'),
'SipToS' => $this->input->post('SipToS'),
'RTPToS' => $this->input->post('RTPToS'),
'LogLevel' => $this->input->post('LogLevel')
);
$this->load->helper('file');
$file = $path.$filename;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Inserting The Data into .ini File*/
write_php_ini($insert,$file);
/*Back to you index page id data is submmited*/
if(isset($_POST['submit'] ))
{
redirect('customer/upload_ini/index');
}
$this->data['subview'] = 'customer/upload/edit_ini';
$this->load->view('customer/_layout_main', $this->data);
}
I want to print the sections into file.
This is not a complete solution, but some corrections to do to your code
First thing : please avoid the ternary operator, your code must always be as clear as possible, also you haven't planned the case where your value is null/empty
please try as follow
foreach($val as $skey => $sval) {
$configPrefix = $skey . ' = ';
if (!is_null($sval) && !empty($sval)) {
if (is_numeric($sval)) {
$res[] = $configPrefix . $sval;
}
else if (is_string($sval)) {
$res[] = $configPrefix . "'" .
$sval . "'" ;
}
else {
// TODO Log/throw exception for your unhandled case ...
}
}
}
Also you didn't decomposed your $insert array by sections, so use this and adapt your code to write sections in your ini file
$insert = array(
'INIDetails' => array(
'SipUserName' => $this->input->post('SipUserName'),
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'UCServer' => $this->input->post('UCServer'),
'UCPassword' => $this->input->post('UCPassword')
),
'DialPlan' => array(
'DP_Exception' => $this->input->post('DP_Exception'),
'DP_Rule1' => $this->input->post('DP_Rule1'),
'DP_Rule2' => $this->input->post('DP_Rule2')
),
'Advanced' => array(
'OperationMode' => $this->input->post('OperationMode'),
'MutePkey' => $this->input->post('MutePkey'),
'Codec' => $this->input->post('Codec'),
'PTime' => $this->input->post('PTime'),
'AudioMode' => $this->input->post('AudioMode'),
'SoftwareAEC' => $this->input->post('SoftwareAEC'),
'EchoTailLength' => $this->input->post('EchoTailLength'),
'PlaybackBuffer' => $this->input->post('PlaybackBuffer'),
'CaptureBuffer' => $this->input->post('CaptureBuffer'),
'JBPrefetchDelay' => $this->input->post('JBPrefetchDelay'),
'JBMaxDelay' => $this->input->post('JBMaxDelay'),
'SipToS' => $this->input->post('SipToS'),
'RTPToS' => $this->input->post('RTPToS'),
'LogLevel' => $this->input->post('LogLevel')
)
);
parse_ini_file(), and work on the associative array.
sample:
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);
you have to pass true as second argument to get correct format.
I'm making a twitter bot using Codebird.
I want to sort the data status in php array without duplicates. Line by line (urls media /remote file links)
This my code:
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey("pubTRI3ik5hJqxxxxxxxxxx", "xxxxxS6Uj1t5GJPi6AUxxxxx");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("xxxxxxx-aVixxxxxxxxxX5MsEHEK", "Dol6RMhOYgxxxxxxFnDtJ6IzXMOLyt");
$statusimgs = array (
"/images.com/hfskehfskea33/jshdfjsh.jpeg",
"/pic.images.com/SDjhs33/sZddszf.jpeg",
"/pic.images.com/dfggfd/dgfgfgdg.jpeg",
"//pic.images.com/xgxg/xdgxg6.jpeg",
);
$params = array(
'status' => 'halo my ststus',
'media[]' => $statusimgs[array_rand($statusimgs)]
);
$reply = $cb->statuses_updateWithMedia($params);
Initially I use random array, but this can make duplicate photos.
I want to sort link remote files from first line to last. I have 1-100 link images to upload on twitter from remote file methot. One by one when script execute manual or with cron.
I want set cron every 60s , 60s 1 photo tweet.
I understand your question as "Remove duplicates from an array and sort it".So, you could try this:
Make $statusarray unique,
sort $statusarray,
add $statusarray to $params array (key = 'media').
Code
<?php
// Input array
$statusimgs = array (
"/images.com/hfskehfskea33/jshdfjsh.jpeg",
"/pic.images.com/SDjhs33/sZddszf.jpeg",
"/pic.images.com/dfggfd/dgfgfgdg.jpeg",
"/pic.images.com/dfggfd/dgfgfgdg.jpeg",
"/pic.images.com/xgxg/xdgxg6.jpeg",
"/pic.images.com/xgxg/xdgxg6.jpeg",
"/pic.images.com/xgxg/xdgxg6.jpeg",
);
// Make unique and sort
$statusimgs = array_unique($statusimgs, SORT_STRING);
sort($statusimgs,SORT_STRING);
// Create the resulting $params array
$params = array(
'status' => 'halo my ststus',
'media' => $statusimgs
);
// Display the result
echo '<pre>'; var_dump($params); '</pre>';
//$reply = $cb->statuses_updateWithMedia($params);
?>
Result
array(2) {
["status"]=>
string(14) "halo my ststus"
["media"]=>
array(4) {
[0]=> string(39) "/images.com/hfskehfskea33/jshdfjsh.jpeg"
[1]=> string(36) "/pic.images.com/SDjhs33/sZddszf.jpeg"
[2]=> string(36) "/pic.images.com/dfggfd/dgfgfgdg.jpeg"
[3]=> string(32) "/pic.images.com/xgxg/xdgxg6.jpeg"
}
}
Alternative Code
<?php
$statusimgs = array (
"/images.com/hfskehfskea33/jshdfjsh.jpeg",
"/pic.images.com/SDjhs33/sZddszf.jpeg",
"/pic.images.com/dfggfd/dgfgfgdg.jpeg",
"/pic.images.com/dfggfd/dgfgfgdg.jpeg",
"/pic.images.com/xgxg/xdgxg6.jpeg",
"/pic.images.com/xgxg/xdgxg6.jpeg",
"/pic.images.com/xgxg/xdgxg6.jpeg",
);
$statusimgs = array_unique($statusimgs, SORT_STRING);
sort($statusimgs,SORT_STRING);
session_start();
if (!isset($_SESSION['index'])) {
$_SESSION['index'] = 1;
} else {
$_SESSION['index'] = ($_SESSION['index']>=count($statusimgs)) ? 1 : $_SESSION['index']+1;
}
session_write_close();
$params = array(
'status' => 'halo my ststus',
'media' => $statusimgs
);
// echo '<pre>'; var_dump($params); '</pre>';
echo 'Choosen: ' . $params['media'][$_SESSION['index']-1] . '<br />';
//$reply = $cb->statuses_updateWithMedia($params);
?>
So here is the issue. I am pulling a CSV file from an API and need to place it into an array. Here is my current code:
$url = "https://www.*****************";
$myvars = 'username=*********&password=*************';
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text'));
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!curl_exec($ch)){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
$response = curl_exec($ch);
$exploded = nl2br($response);
//echo $response."<br>";
var_dump($exploded);
}
curl_close($ch);
The problem is I am getting the response:
string(245) ""Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"
"
This is two lines in the CSV, but comes out in a single string line. I tried exploding it, but it seems to have two delimiters and I tried splitting it, but it will not find the second delimiter. I want it to generate like this:
array(
"Number" => 1,
"Name" => "All Calls",
"Description" => "All Call Data",
"Type" => "Call",
"Fixed Width Boolean" => false,
"Quote Character" => "None",
"Delimiter Character" => ",",
"End of Line Sequence" => "\r\n",
"Header Boolean" => true,
"Column Count" => 14
);
The first line of the CSV is the headers and the data underneath is the data it needs to align to. Also future requests will have multiple lines of data and they need to match with the headers too. Any ideas?
If you're dealing with CSV, try using the built-in function for such. Then use array_combine to stick your headers in as keys:
$response = curl_exec($ch);
$csv_data = array_map('str_getcsv', explode("\n", $response));
$headers = array_shift($csv_data);
foreach ($csv_data as $v) {
$data[] = array_combine($headers, $v);
}
As an example:
$response = <<< CSV
"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\\r\\n","true","14"
CSV;
$csv_data = array_map('str_getcsv', explode("\n", $response));
$headers = array_shift($csv_data);
foreach ($csv_data as $v) {
$data[] = array_combine($headers, $v);
}
print_r($data);
Output:
Array
(
[0] => Array
(
[Number] => 1
[Name] => All Calls
[Description] => All Call Data
[Type] => Call
[Fixed Width Boolean] => false
[Quote Character] => None
[Delimiter Character] => ,
[End of Line Sequence] => \r\n
[Header Boolean] => true
[Column Count] => 14
)
)
You can also turn your csv string into a file pointer and use fgetcsv on it. Here is an example of how it works:
Josh:~$ php -a
Interactive shell
php > $data = <<<CSV
<<< > "col1","col2"
<<< > "d1",","
<<< > CSV;
php > echo $data;
"col1","col2"
"d1",","
php > $fp = fopen('data://text/plain,' . $data, 'r');
php > while (($row = fgetcsv($fp)) !== false) {
php { var_dump($row);
php { }
array(2) {
[0]=>
string(4) "col1"
[1]=>
string(4) "col2"
}
array(2) {
[0]=>
string(2) "d1"
[1]=>
string(1) ","
}
Using your example it would be similar to the following
$response = <<<CSV
"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count"
"1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"
CSV;
$fp = fopen('data://text/plain,' . $response, 'r');
$data = [];
$header = fgetcsv($fp); // first row is column headers
while (($row = fgetcsv($fp)) !== false) {
$data[] = array_combine($header, $row);
}
print_r($data); // list of rows with keys set to column names from $header
/*
Array
(
[0] => Array
(
[Number] => 1
[Name] => All Calls
[Description] => All Call Data
[Type] => Call
[Fixed Width Boolean] => false
[Quote Character] => None
[Delimiter Character] => ,
[End of Line Sequence] =>
[Header Boolean] => true
[Column Count] => 14
)
)
*/
Well, this is a bit "hacky" but it works....
PHP Fiddle
$response = '"Number","Name","Description","Type","Fixed Width Boolean","Quote Character","Delimiter Character","End of Line Sequence","Header Boolean","Column Count","1","All Calls","All Call Data","Call","false","None",",","\r\n","true","14"';
$response = preg_replace('/[,]/', "*", $response);
$response = str_replace('*"*"*', '*","*', $response);
$exploded = explode("*", $response);
$count = count($exploded)/2;
$newArray = [];
for($i=0; $i<$count; ++$i){
$newArray[$exploded[$i]] = $exploded[$i+$count];
}
print_r($newArray);
Which prints
Array
(
["Number"] => "1"
["Name"] => "All Calls"
["Description"] => "All Call Data"
["Type"] => "Call"
["Fixed Width Boolean"] => "false"
["Quote Character"] => "None"
["Delimiter Character"] => ","
["End of Line Sequence"] => "\r\n"
["Header Boolean"] => "true"
["Column Count"] => "14"
)
Long time lurker first time poster,
Im done pulling my hair out over this, so i figured i would swallow the pride and ask the experts,
I have read in excess of 20 similar issues here and tried all fixes solutions but im getting the same results.
Im using PHP for users to download items, however i have tried readfile and fopen but EVERY download is corrupt, sometimes 0 in size other times the correct(ish) size, But always damaged or corrupt
Can someone take a peek at this code and tell me whats wrong with it, ive scoured it so many times now im probably just missing something rediculously simple, ..... as usual
Any help would be greatly appreciated.
(contents of /loap.php can be shown if needed)
EDIT : Resolved
Just a quick update for anyone who stumbled across this, I managed to get this working ...... I had tried many different variations of certain commands, but it seems i had missed trying with "ob_clean()" and "ob_end_flush()" with fopen(),
.. It did the trick and as i expected it was a simple fix Thanks for the help Twisty, you poked at my inspiration ;)
<?php
require_once('../secura/load.php');
function get_remote_file_size($url, $readable = true){
$parsed = parse_url($url);
$host = $parsed["host"];
$fp = #fsockopen($host, 80, $errno, $errstr, 20);
if(!$fp) return false;
else {
#fputs($fp, "HEAD $url HTTP/1.1\r\n");
#fputs($fp, "HOST: $host\r\n");
#fputs($fp, "Connection: close\r\n\r\n");
$headers = "";
while(!#feof($fp))$headers .= #fgets ($fp, 128);
}
#fclose ($fp);
$return = false;
$arr_headers = explode("\n", $headers);
foreach($arr_headers as $header) {
$s = "Content-Length: ";
if(substr(strtolower ($header), 0, strlen($s)) == strtolower($s)) {
$return = trim(substr($header, strlen($s)));
break;
}
}
return $return;
}
function get_ext($name)
{
$fn = get_basename($name);
return (strpos($fn, '.') ? strtolower(substr(strrchr($fn, '.'), 1)) : '');
}
function get_basename($name)
{
return basename(str_replace('\\', '/', $name));
}
function get_filesize_unit($size)
{
$size = max(0, $size);
static $u = array(' B', 'KB', 'MB', 'GB');
for ($i=0; $size >= 1024 && $i < 4; $i++)
{
$size /= 1024;
}
return number_format($size, 1).' '.$u[$i];
}
///////////////////////////////////////////////////////////////////////////////////////////////
function find_mime_type($ext)
{
static $mime_types = array(
'application/andrew-inset' => array('ez'),
'application/mac-binhex40' => array('hqx'),
'application/mac-compactpro' => array('cpt'),
'application/mathml+xml' => array('mathml'),
'application/msword' => array('doc'),
'application/octet-stream' => array('bin', 'dms', 'lha',
'lzh', 'exe', 'class', 'so', 'dll', 'dmg'),
'application/oda' => array('oda'),
'application/ogg' => array('ogg'),
'application/pdf' => array('pdf'),
'application/postscript' => array('ai', 'eps', 'ps'),
'application/rdf+xml' => array('rdf'),
'application/smil' => array('smi', 'smil'),
'application/srgs' => array('gram'),
'application/srgs+xml' => array('grxml'),
'application/vnd.mif' => array('mif'),
'application/vnd.mozilla.xul+xml' => array('xul'),
'application/vnd.ms-excel' => array('xls'),
'application/vnd.ms-powerpoint' => array('ppt'),
'application/vnd.wap.wbxml' => array('wbxml'),
'application/vnd.wap.wmlc' => array('wmlc'),
'application/vnd.wap.wmlscriptc' => array('wmlsc'),
'application/voicexml+xml' => array('vxml'),
'application/x-bcpio' => array('bcpio'),
'application/x-cdlink' => array('vcd'),
'application/x-chess-pgn' => array('pgn'),
'application/x-cpio' => array('cpio'),
'application/x-csh' => array('csh'),
'application/x-director' => array('dcr', 'dir', 'dxr'),
'application/x-dvi' => array('dvi'),
'application/x-futuresplash' => array('spl'),
'application/x-gtar' => array('gtar'),
'application/x-hdf' => array('hdf'),
'application/x-javascript' => array('js'),
'application/x-koan' => array('skp', 'skd', 'skt', 'skm'),
'application/x-latex' => array('latex'),
'application/x-netcdf' => array('nc', 'cdf'),
'application/x-sh' => array('sh'),
'application/x-shar' => array('shar'),
'application/x-shockwave-flash' => array('swf'),
'application/x-stuffit' => array('sit'),
'application/x-sv4cpio' => array('sv4cpio'),
'application/x-sv4crc' => array('sv4crc'),
'application/x-tar' => array('tar'),
'application/x-tcl' => array('tcl'),
'application/x-tex' => array('tex'),
'application/x-texinfo' => array('texinfo', 'texi'),
'application/x-troff' => array('t', 'tr', 'roff'),
'application/x-troff-man' => array('man'),
'application/x-troff-me' => array('me'),
'application/x-troff-ms' => array('ms'),
'application/x-ustar' => array('ustar'),
'application/x-wais-source' => array('src'),
'application/xhtml+xml' => array('xhtml', 'xht'),
'application/xslt+xml' => array('xslt'),
'application/xml' => array('xml', 'xsl'),
'application/xml-dtd' => array('dtd'),
'application/zip' => array('zip'),
'audio/basic' => array('au', 'snd'),
'audio/midi' => array('mid', 'midi', 'kar'),
'audio/mpeg' => array('mpga', 'mp2', 'mp3'),
'audio/x-aiff' => array('aif', 'aiff', 'aifc'),
'audio/x-mpegurl' => array('m3u'),
'audio/x-pn-realaudio' => array('ram', 'ra'),
'application/vnd.rn-realmedia' => array('rm'),
'audio/x-wav' => array('wav'),
'chemical/x-pdb' => array('pdb'),
'chemical/x-xyz' => array('xyz'),
'image/bmp' => array('bmp'),
'image/cgm' => array('cgm'),
'image/gif' => array('gif'),
'image/ief' => array('ief'),
'image/jpeg' => array('jpeg', 'jpg', 'jpe'),
'image/png' => array('png'),
'image/svg+xml' => array('svg'),
'image/tiff' => array('tiff', 'tif'),
'image/vnd.djvu' => array('djvu', 'djv'),
'image/vnd.wap.wbmp' => array('wbmp'),
'image/x-cmu-raster' => array('ras'),
'image/x-icon' => array('ico'),
'image/x-portable-anymap' => array('pnm'),
'image/x-portable-bitmap' => array('pbm'),
'image/x-portable-graymap' => array('pgm'),
'image/x-portable-pixmap' => array('ppm'),
'image/x-rgb' => array('rgb'),
'image/x-xbitmap' => array('xbm'),
'image/x-xpixmap' => array('xpm'),
'image/x-xwindowdump' => array('xwd'),
'model/iges' => array('igs', 'iges'),
'model/mesh' => array('msh', 'mesh', 'silo'),
'model/vrml' => array('wrl', 'vrml'),
'text/calendar' => array('ics', 'ifb'),
'text/css' => array('css'),
'text/html' => array('html', 'htm'),
'text/plain' => array('asc', 'txt'),
'text/richtext' => array('rtx'),
'text/rtf' => array('rtf'),
'text/sgml' => array('sgml', 'sgm'),
'text/tab-separated-values' => array('tsv'),
'text/vnd.wap.wml' => array('wml'),
'text/vnd.wap.wmlscript' => array('wmls'),
'text/x-setext' => array('etx'),
'video/mpeg' => array('mpeg','3gp','mp4', 'mpg', 'mpe'),
'video/quicktime' => array('qt', 'mov'),
'video/vnd.mpegurl' => array('mxu', 'm4u'),
'video/x-msvideo' => array('avi'),
'video/x-sgi-movie' => array('movie'),
'x-conference/x-cooltalk' => array('ice')
);
foreach ($mime_types as $mime_type => $exts)
{
if (in_array($ext, $exts))
{
return $mime_type;
}
}
return 'text/plain';
}
$id = $_GET['id'];
$error = false;
$error = (!$product->is_product($id)?$products->error:$error);
$error =(!$purchases->is_purchased($_SESSION['uid'],$id)?$purchases->error:$error);
if(!$error){
$file = $product->details($id);
$filepath = $file['file'];
$fname=get_basename($filepath);
if (fopen($filepath,r) || (file_exists($filepath)) ){
if (#filesize($filepath)){
$fsize =filesize($filepath);
}
else
{
$fsize = get_remote_file_size($filepath);
}
$ext= get_ext($fname);
$ctype= find_mime_type($ext);
header('Content-Type:'. $ctype );
header('Content-Length: ' . $fsize);
header('Content-Disposition: attachment; filename=' . $fname);
ob_clean();
$file = fopen($filepath,'r');
ob_end_flush();
fpassthru($file);
set_time_limit(0);
}else{
return 'File Doesn\'t Exist'; } // exist fxn....
}
echo $error;
?>
Just a quick update for anyone who stumbled across this, I managed to get this working ......
I had tried many different variations of certain commands,
but it seems i had missed trying with ob_clean() and ob_end_flush() with fopen() , ..
It did the trick and as i expected it was a simple fix
Thanks for the help Twisty, you poked at my inspiration ;)
The corrected and working code has been updated in the OP
Make sure you do not have any code executed after the last line readfile(FILE_NAME)
In my case, I had to add die(); or exit(); as the last line, because MVC framework continues to render the view after readfile