php readfile() and fopen() damaged/corrupt download - php

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

Related

How to convert Pdf file to byte array in php and send?

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) :)

twitter post video using chanked api using php is not working

hear is my code it's showing me error when i am uploading video on twitter
<?php
$video = 'images/video1.mp4'; /// video size is 2 mb and it's time duration around 20 seconeds
$code = $twitter->upload('media/upload',
["command" => "INIT",
"total_bytes" => (int)filesize($video),
'media_type' => 'video/mp4']
);
var_dump($code);
$video_media_id = $code->media_id_string;
$fp = fopen($video, 'r');
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
$twitter->upload('media/upload',
["command" => "APPEND",
"media_id" => $video_media_id,
"media_data" => base64_encode($chunk),
"segment_index" => $segment_id]
);
$segment_id++;
}
$final=$twitter->upload('media/upload',
["command" => "FINALIZE",
"media_id" => $video_media_id]
);
var_dump($final);
$parameters = [
'status' => 'hear is my video twittsvbn',
'media_id' => $video_media_id
];
print_r($parameters);
$tweet= $twitter->post('statuses/update', $parameters);
echo json_encode($tweet);
?>
it was showing me error
object(stdClass)#933 (2) {
["request"]=>
string(22) "/1.1/media/upload.json"
["error"]=>
string(51) "Segments do not add up to provided total file size."
}

Searching for numbers with a comma as a decimal point in an array

I have to search through an Excel file and get the numbers that have a comma as a decimal point and convert it to a decimal point.(ex: 23,56 -> 23.56, 23123,566 -> 23123.566). I have already exported the excel file to .csv and put all contents into arrays but I have trouble finding the numbers with comma.
This is how one of my array looks like:
Array
(
[A1] => 1
[A2] => 123123
[A3] => dasdadwa
[A4] => 6,7
[A5] => 24f,5
[A6] => f5,5
[A7] => dasdad,fsdfsdfsfsasada dasdasd
[A8] => aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
[A9] => dasdasd
[A10] => q231e
[A11] =>
[A12] => 0
[A13] =>
[A14] =>
[A15] => 1
[A16] => 123123
[A17] => dasdadwa
[A18] => 6,7
[A19] => 24f,5
[A20] => f5,5
[A21] => dasdad,fsdfsdfsfsasada dasdasd
[A22] =>
[A23] =>
[A24] => q231e
[A25] =>
[A26] => 0
[A27] =>
[A28] =>
[A29] => 1
[A30] => 123123
[A31] => dasdadwa
[A32] => 6,7
[A33] => 24f,5
[A34] => f5,5
[A35] => dasdad,fsdfsdfsfsasada dasdasd
[A36] =>
[A37] =>
[A38] => q231e
[A39] =>
[A40] =>
[A41] =>
[A42] =>
)
I'm only interested in the characters that have only numbers and a comma but it is troublesome because those entries are strings. I have tried messing with regex but I just could not get it to work.
Here is what i have so far:
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$contents = csv_to_array($filename.'.csv');
foreach($contents as $val)
{
//If $val is a number separated by comma
//Replace comma with . (str_replace(',','.');, $val);)
}
Just simple pattern which will replace only your pattern:
//rest od your code and now:
foreach($contents as $key => $val)
{
$contents[$key] = preg_replace('/^(\d+),(\d+)$/', '\1.\2', $val);
}
This code will touch only strings like 2,3. Strings like this ff,333 will not be touch
Since you would like to extract only decimals, I suggest using regex, like this:
foreach($contents as $val) {
// if $val is a number separated by comma
if (preg_match('/^[0-9]+,[0-9]+$/', $val) == 1) {
// transform into float with two decimals and dot as decimal separator
$float = number_format($val, 2, '.');
}
}
Edit: updated regex pattern following comments.
Like this?
foreach($contents as $val)
{
if (strpos($val, ',') !== false) {
$val = str_replace(',', '.', $val);
}
}

PHP french letters enconding

Currently, I'm working with PHP, and i'm parsing a CSV and saving it to DB.
I don't have any problem with that, just I have some french characters, that it's not showing correctly.
I took a look in all previous questions and I tried all suggested solutions, but no one solved my problem ....
Also, with "utf8_encode", it becomes more unreadable.
Here you can find all the code of the function:
if(date('l') == 'Thursday' or date('d') == 1)
{
$row = 1;
if (($handle = fopen("C:/Users/ASUS/Downloads/Exemple_extraction.csv", "r")) !== FALSE)
{
$this->createTable();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if($row == 1){ $row++; continue; }
$num = count($data);
for ($c = 0; $c < $num; $c++)
{
$dataa = (explode(';', $data[$c]));
$dest = str_replace(' ', '', $dataa['27']);
echo($dataa['27']);echo '<br>';
switch($dest)
{
case 'Investissement':
$destination = 'Investir';
break;
case 'Non défini':
$destination = '';
break;
case 'Résidence principale':
$destination = 'Habiter';
break;
case 'Résidence secondaire':
$destination = 'Habiter';
break;
default:
$destination = '';
}
$tLogt = str_replace(' ', '', $dataa['26']);
switch($tLogt)
{
case 'Studio':
$tLogt = 'studio';
break;
case '1/2 pièces':
$tLogt = '2P';
break;
case '2/3 pièces':
$tLogt = '3P';
break;
case '3/4 pièces':
$tLogt = '4P';
break;
default:
if($tLogt == '4/5 pièces' || $tLogt == '5/6 pièces' || $tLogt == '5P DUPLEX')
{
$tLogt = '5P+';
}
}
if(str_replace(' ', '', $dataa['9']) != '')
{
$cp = substr(str_replace(' ', '', $dataa['9']), 0, 2);
}
else
{
$cp = '';
}
DB::table(date('l') . '_' . date("d_m_Y"))
->insert(['flReservataire' => $dataa['0'],
'flClient' => $dataa['1'],
'idProspect' => $dataa['2'],
'civility' => $dataa['3'],
'firstname' => $dataa['4'],
'lastname' => $dataa['5'],
'address1' => $dataa['6'],
'address2' => $dataa['7'],
'address3' => $dataa['8'],
'zipcode' => $dataa['9'],
'city' => $dataa['10'],
'codeInsee' => $dataa['11'],
'country' => $dataa['12'],
'flNpai' => $dataa['13'],
'phone' => $dataa['14'],
'workphone' => $dataa['15'],
'cellphone' => $dataa['16'],
'email1' => $dataa['17'],
'email2' => $dataa['18'],
'flStopMarketing' => $dataa['19'],
'age' => $dataa['20'],
'program' => $dataa['21'],
'region' => $dataa['22'],
'department' => $dataa['23'],
'seller' => $dataa['24'],
'typeLogt' => $dataa['25'],
'tailleLogt' => $dataa['26'],
'destination' => $dataa['27'],
'apport' => $dataa['28'],
'budget' => $dataa['29'],
'timelimit' => $dataa['30'],
'idOrigine' => $dataa['31'],
'typeContact' => $dataa['32'],
'typeAction' => $dataa['33'],
'dateAction' => $dataa['34'],
'comment' => $dataa['35'],
'typeActionFuture' => $dataa['36'],
'dateActionFuture' => $dataa['37'],
'levier' => $dataa['38'],
'support' => $dataa['39'],
'enreg' => $dataa['40'],
'destination_good' => $destination,
'typologie_good' => $tLogt,
'cp_good' => $cp,]);
}
}
fclose($handle);
$this->sendMail('emailSuccess');
}
else
{
$this->sendMail('emailError');
}
}
In all the "echo", I got the problem..
Any other suggestion plz?
Thanks alot
Kind Regards
My assumption would be that the CSV file uses a local encoding. To load it into correct internal representation you have to use iconv() from the local encoding (probably some ISO-8859 or WIN-12xx) to UTF8.
Also, to find out the correct encoding, use some decent text editor that supports switching encodings. Then simply find an option that makes the source readable.

How to parse and write .ini file in codeigniter PHP?

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.

Categories