2 space Text File STORAGE with LARAVEL - php

I created a Text Plane File .txt from Storage with Laravel, but it is always in the first Row, put 2 spaces, I haven't been able to delete it.
I used trim(), ltrim(), replace() etc with php.
Thanks you.
To result of text plain:
$ruta = 'pila/' . $anio . '/' . $mes;
$nombreArchivo = date('Y-m-d H:i:s') . '_' . $datosEmpresa['TIDE'] . '_' . $datosEmpresa['IDEM'] . '_' . $datosEmpresa['OPERADOR'] . '_' . $datosEmpresa['PERIODO'] . '_' . $datosEmpresa['TIPOPLANILLA'] . '_TIPO_2.txt';
$archivo = $ruta . '/' . $nombreArchivo;
$contenido = null;
/* - - - - - - - - - - - - - - - - - *
* REGISTRO TIPO 1 *
* - - - - - - - - - - - - - - - - - */
$campo1 = '01';
$campo2 = str_pad($datosEmpresa['MPLA'], 1);
$campo3 = str_pad('0001', 4);
$campo4 = str_pad($datosEmpresa['RASO'], 200);
$campo5 = str_pad($datosEmpresa['TIDE'], 2);
$campo6 = str_pad($datosEmpresa['IDEM'], 16);
$campo7 = str_pad($datosEmpresa['DIGV'], 1);
$campo8 = str_pad($datosEmpresa['TIPOPLANILLA'], 1);
$campo9 = str_pad($datosEmpresa['PLANILLAANTERIOR'], 10);
$campo10 = str_pad($datosEmpresa['FECHAPLANILLAANT'], 10);
$campo11 = str_pad($datosEmpresa['PRESENTACION'], 1);
$campo12 = str_pad($datosEmpresa['CODSUCURSAL'], 10);
$campo13 = str_pad($datosEmpresa['NOMSUCURSAL'], 40);
$campo14 = str_pad($datosEmpresa['CARL'], 6);
$campo15 = str_pad($datosEmpresa['PERIODO'], 7);
$campo16 = str_pad($datosEmpresa['PERIODOSALUD'], 7);
$campo17 = str_pad(" ", 10); //PLANILLA
$campo18 = str_pad(" ", 10); //FECHA PAGO
$campo19 = str_pad(count($datosTrabajador), 5, '0', STR_PAD_LEFT);
$campo20 = str_pad($datosEmpresa['TOTALNOMINA'], 12, '0', STR_PAD_LEFT);
$campo21 = str_pad($datosEmpresa['TAPO'], 2);
$campo22 = str_pad($datosEmpresa['OPERADOR'], 2);
$contenido .= $campo1 . $campo2 . $campo3 . $campo4 . $campo5 . $campo6 . $campo7 . $campo8 . $campo9 . $campo10 . $campo11 . $campo12 . $campo13 . $campo14 . $campo15 . $campo16 . $campo17 . $campo18 . $campo19 . $campo20 . $campo21 . $campo22;
Storage::append($archivo, $contenido);
I attach my source code:
enter image description here
Only for the first row, the others one it's OK.

Related

Only first pdf file filled with fpdm can be opened

this is my first question here so please excuse if this is incomprehensible.
I've got a little web tool on PHP for registering examinees to an examination. At the end I want to fill a PDF form with FPDM with data from the database in a foreach. The frist file which is created is perfect. The others are created but when I want to open with Acrobat or Chrome the loading is failed. I can fill every set of data separately but when I call the filling function twice or multiple times, the second file can not be opened.
MS Edge is able to open the currupt files but doesn't show the fonts correctly. So FPDM seems to fill all forms correctly but the files are somehow broken.
I'm searching for solutiones sincs days but no idea where is the problem. The code should be correct.
Can anybody help??
Here is the code:
require_once('libs/fpdm.php');
$statement = $pdo->prepare("SELECT * FROM `examinations` WHERE uid = :uid");
$result = $statement->execute(array('uid' => $_GET['prepareExamination']));
$examinationToPrepare = $statement->fetch();
$statement = $pdo->prepare("SELECT * FROM `examinees` WHERE examination = :examination");
$result = $statement->execute(array('examination' => $_GET['prepareExamination']));
$examinees = $statement->fetchAll();
$i = 1;
function mergePDF($template, $fields, $outfilename) {
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename=" . basename($outfilename) . "");
$pdf = new FPDM($template);
$pdf->Load($fields, true);
$pdf->Merge();
$pdf->Output($outfilename, "F")
}
foreach ($examinees as $examinee => $data) {
if ($examinationToPrepare['department'] == 1) {
$examiner1Name = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'FirstExaminer'], 'firstName')) . ' ' . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'FirstExaminer'], 'lastName'));
$examiner1Description = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'FirstExaminer'], 'graduation')) . "\n" . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'FirstExaminer'], 'function'));
$examiner2Name = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'SecondExaminer'], 'firstName')) . ' ' . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'SecondExaminer'], 'lastName'));
$examiner2Description = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'SecondExaminer'], 'graduation')) . "\n" . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['group' . strval(intval($data['subDepartment']) - 1) . 'SecondExaminer'], 'function'));
} else {
$examiner1Name = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['firstExaminer'], 'firstName')) . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['firstExaminer'], 'lastName'));
$examiner1Description = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['firstExaminer'], 'graduation')) . '\n' . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['firstExaminer'], 'function'));
$examiner2Name = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['secondExaminer'], 'firstName')) . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['secondExaminer'], 'lastName'));
$examiner2Description = utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['secondExaminer'], 'graduation')) . '\n' . utf8_encode(findByUid($_SESSION['examiners'], $examinationToPrepare['secondExaminer'], 'function'));
}
$fields = array(
'name' => utf8_encode($data['firstName']) . ' ' . utf8_encode($data['lastName']),
'graduierung' => utf8_encode(findByUid($_SESSION['graduations'], $data['graduation'], 'name')) . ' ' . utf8_encode(findByUid($_SESSION['systems'], $data['system'], 'name')),
'ort' => utf8_encode($examinationToPrepare['location']),
'registrierung' => utf8_encode($examinationToPrepare['registration']),
'datum' => utf8_encode($examinationToPrepare['date']),
'pruefer1' => $examiner1Name,
'pruefer1-grad' => $examiner1Description,
'pruefer2' => $examiner2Name,
'pruefer2-grad' => $examiner2Description
);
if (!file_exists('documents/' . utf8_encode($examinationToPrepare['title']))) {
mkdir('documents/' . utf8_encode($examinationToPrepare['title']), 0777, true);
}
if ($examinationToPrepare['department'] == 1 && !file_exists('documents/' . $examinationToPrepare['title'] . '/' . findById($_SESSION['subDepartments'], $data['subDepartment'], 'name'))) {
mkdir('documents/' . $examinationToPrepare['title'] . '/' . findById($_SESSION['subDepartments'], $data['subDepartment'], 'name'), 0777, true);
}
mergePDF('pdf/Urkunde1.pdf', $fields, 'documents/' . $examinationToPrepare['title'] . '/' . ($examinationToPrepare['department'] == 1 ? findById($_SESSION['subDepartments'], $data['subDepartment'], 'name') . '/' : '') . utf8_encode($data['firstName']) . ' ' . utf8_encode($data['lastName']). '.pdf');
$i++;
}

file_get_contents How to not show if does not have array needed

I am trying to get my code to work when the url its sent to does not have the variables needed.
this is the error:
E_WARNING : type 2 -- file_get_contents(the link): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found -- at line 23
Ex my code goes to this users page and everything okay:
https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/24267598/ranked?season=SEASON2016&api_key=e9044828-20e3-46cc-9eb5-545949299803
But when it goes to this users page it gives a error:
https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/77828400/ranked?season=SEASON2016&api_key=e9044828-20e3-46cc-9eb5-545949299803
What im after doing if when there is no content in url for it not to show anything and when there is to show it. But for some reason I cant get it to work with both.
Here is my code:
<?php
$apiKey = 'APIKEY';
$summonerName = 'raget deathdex';
$new = rawurlencode($summonerName);
$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);
$result = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
$summoner = json_decode($result)->$str;
$id = $summoner->id;
?>
<?php
$claw = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
$gaza = json_decode($claw);
?>
<?php
$entriesz = $gaza->champions;
usort($entriesz, function($ac,$bc){
return $bc->stats->totalSessionsPlayed-$ac->stats->totalSessionsPlayed;
});
foreach($entriesz as $statSummaryz) if ($tmp++ < 11){
$getLeagueNamelistside = $statSummaryz->id;
$getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
$getMiniomskillsNamelistside = $statSummaryz->stats->totalMinionKills;
$getkillsNamelistside = $statSummaryz->stats->totalChampionKills;
$getassistssNamelistside = $statSummaryz->stats->totalAssists;
$getdeathsNamelistside = $statSummaryz->stats->totalDeathsPerSession;
$getlosseslistside = $statSummaryz->stats->totalSessionsLost;
$getwinslistside = $statSummaryz->stats->totalSessionsWon;
$Percentkillrateside = $getkillsNamelistside / $getsessionsplayedNamelistside;
$Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
$Percentdeathrateside = $getdeathsNamelistside / $getsessionsplayedNamelistside;
$KDAside = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
$KDAMinniomsSide = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
$PercentWinRateSide = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;
if ($getLeagueNamelistside >=1){
$resultz = file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/'.$getLeagueNamelistside.'?api_key=' . $apiKey);
$summonerz = json_decode($resultz, true);
$getLeagueNamelistsidez = $summonerz['name'];
$getLeagueKeyNamelistsidez = $summonerz['key'];
echo '<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/' .$getLeagueKeyNamelistsidez. '.png"></p>'.$getLeagueNamelistsidez. '<p> Kills '.number_format((float)$Percentkillrateside, 1, '.', '').'</p><p> Deaths '.number_format((float)$Percentdeathrateside, 1, '.', '').'</p><p> Assists '.number_format((float)$Percentassistrateside, 1, '.', '').'</p><p> KDA '.number_format((float)$KDAside, 2, '.', '').':1 KDA</p><p> CS '.number_format((float)$KDAMinniomsSide, 1, '.', '').' CS</p><p> Games Played '.$getsessionsplayedNamelistside.'</p><p> Win Rate '.number_format((float)$PercentWinRateSide, 0, '.', '').'%</p>';
}
elseif($getLeagueNamelistside =0){
return DO_NOTHING;
}
}
?>
Try this ;)
$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);
$result = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
$summoner = json_decode($result)->$str;
$id = $summoner->id;
$claw = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
$gaza = json_decode($claw);
if (isset($gaza->champions)) {
$entriesz = $gaza->champions;
usort($entriesz, function($ac, $bc) {
return $bc->stats->totalSessionsPlayed - $ac->stats->totalSessionsPlayed;
});
foreach ($entriesz as $statSummaryz) {
if ($tmp++ < 11) {
$getLeagueNamelistside = $statSummaryz->id;
$getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
$getMiniomskillsNamelistside = $statSummaryz->stats->totalMinionKills;
$getkillsNamelistside = $statSummaryz->stats->totalChampionKills;
$getassistssNamelistside = $statSummaryz->stats->totalAssists;
$getdeathsNamelistside = $statSummaryz->stats->totalDeathsPerSession;
$getlosseslistside = $statSummaryz->stats->totalSessionsLost;
$getwinslistside = $statSummaryz->stats->totalSessionsWon;
$Percentkillrateside = $getkillsNamelistside / $getsessionsplayedNamelistside;
$Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
$Percentdeathrateside = $getdeathsNamelistside / $getsessionsplayedNamelistside;
$KDAside = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
$KDAMinniomsSide = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
$PercentWinRateSide = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;
if ($getLeagueNamelistside >= 1) {
$resultz = file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/' . $getLeagueNamelistside . '?api_key=' . $apiKey);
$summonerz = json_decode($resultz, true);
$getLeagueNamelistsidez = $summonerz['name'];
$getLeagueKeyNamelistsidez = $summonerz['key'];
echo '<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/' . $getLeagueKeyNamelistsidez . '.png"></p>' . $getLeagueNamelistsidez . '<p> Kills ' . number_format((float) $Percentkillrateside, 1, '.', '') . '</p><p> Deaths ' . number_format((float) $Percentdeathrateside, 1, '.', '') . '</p><p> Assists ' . number_format((float) $Percentassistrateside, 1, '.', '') . '</p><p> KDA ' . number_format((float) $KDAside, 2, '.', '') . ':1 KDA</p><p> CS ' . number_format((float) $KDAMinniomsSide, 1, '.', '') . ' CS</p><p> Games Played ' . $getsessionsplayedNamelistside . '</p><p> Win Rate ' . number_format((float) $PercentWinRateSide, 0, '.', '') . '%</p>';
} elseif ($getLeagueNamelistside == 0) {
return DO_NOTHING;
}
}
}
}
You should be able to check the file contents in order to determine it has the required data.
<?php
$claw = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
if(false === empty($claw)) {
$gaza = json_decode($claw);
if(true === empty($gaza->champion)) {
return 'Invalid data received';
}
} else {
return 'No data found';
}
?>
It also looks like you have a syntax error on your comparison condition which is using an assignment operator which will always evaluate to true. But unsure if that portion of your code is used or not.
elseif($getLeagueNamelistside =0){
Should just be
else {
which will function as if ($getLeagueNamelistside <= 0) return DO_NOTHING;
UPDATE
To prevent the file not found error, and others from being displayed, you can disable the display of error messages. Which should be the case in production code anyways.
ini_set('display_errors', 'off');
Or filter the display of only certain error messages.
ini_set('error_reporting', E_ERROR | E_PARSE);
You can also bypass error reporting of specific commands by prepending #
#file_get_contents('https://example.com/index.php');
Last but not least, and my preferred method, is to use output buffering to prevent undesired content from outputting to the client.
ob_start();
echo file_get_contents('https://example.com/index.php');
$content = ob_get_clean();
echo false === strpos($content, '404') ? $content : 'OOps';
Is this what you're trying to do?
PHP treats strings like a byte array. Instead of checking if a string is empty of if the strings length is greater than 0, I like to check to see if the first byte is set. Some people consider it less humanly readable, but thats just some people.
Use isset($mystring[0]) to see if a string is at least one character in length.
The # symbol before the file_get_contents is for error suppression. The # prevents an error from appearing in your browser if the file can't be found.
<?php
$apiKey = 'e9044828-20e3-46cc-9eb5-545949299803';
$summonerName = 'raget deathdex';
$new = rawurlencode($summonerName);
$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);
$result = #file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
if(!isset($result[0])) {
die(); // die('Nothing found in \'result\' file.');
}
$summoner = json_decode($result)->$str;
if(!$summoner) {
die(); // die('Nothing found in \'result\' content.');
}
$id = $summoner->id;
?>
<?php
$claw = #file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
if(!isset($claw[0])) {
die(); // die('Nothing found in \'claw\' file.');
}
$gaza = json_decode($claw);
if(!$gaza) {
die(); // die('Nothing found in \'claw\' content.');
}
?>
<?php
$entriesz = $gaza->champions;
usort($entriesz, function($ac,$bc){
return $bc->stats->totalSessionsPlayed-$ac->stats->totalSessionsPlayed;
});
foreach($entriesz as $statSummaryz) if ($tmp++ < 11){
$getLeagueNamelistside = $statSummaryz->id;
$getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
$getMiniomskillsNamelistside = $statSummaryz->stats->totalMinionKills;
$getkillsNamelistside = $statSummaryz->stats->totalChampionKills;
$getassistssNamelistside = $statSummaryz->stats->totalAssists;
$getdeathsNamelistside = $statSummaryz->stats->totalDeathsPerSession;
$getlosseslistside = $statSummaryz->stats->totalSessionsLost;
$getwinslistside = $statSummaryz->stats->totalSessionsWon;
$Percentkillrateside = $getkillsNamelistside / $getsessionsplayedNamelistside;
$Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
$Percentdeathrateside = $getdeathsNamelistside / $getsessionsplayedNamelistside;
$KDAside = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
$KDAMinniomsSide = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
$PercentWinRateSide = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;
if ($getLeagueNamelistside >=1){
$resultz = #file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/'.$getLeagueNamelistside.'?api_key=' . $apiKey);
if(!isset($resultz[0])) {
die(); // die('Nothing found in league file:' . $getLeagueNamelistside);
}
$summonerz = json_decode($resultz, true);
if(!summonerz) {
die(); // die('Nothing found in league content:' . $getLeagueNamelistside);
}
$getLeagueNamelistsidez = $summonerz['name'];
$getLeagueKeyNamelistsidez = $summonerz['key'];
echo '<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/' .$getLeagueKeyNamelistsidez. '.png"></p>'.$getLeagueNamelistsidez. '<p> Kills '.number_format((float)$Percentkillrateside, 1, '.', '').'</p><p> Deaths '.number_format((float)$Percentdeathrateside, 1, '.', '').'</p><p> Assists '.number_format((float)$Percentassistrateside, 1, '.', '').'</p><p> KDA '.number_format((float)$KDAside, 2, '.', '').':1 KDA</p><p> CS '.number_format((float)$KDAMinniomsSide, 1, '.', '').' CS</p><p> Games Played '.$getsessionsplayedNamelistside.'</p><p> Win Rate '.number_format((float)$PercentWinRateSide, 0, '.', '').'%</p>';
}
elseif($getLeagueNamelistside == 0){
die();
}
}
?>
<?php
$apiKey = 'e9044828-20e3-46cc-9eb5-545949299803';
$summonerName = 'raget deathdex';
// =====
$results = #file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . rawurlencode($summonerName) . '?api_key=' . $apiKey);
if(!isset($results[0]))
die();
$summoner = json_decode($results)->strtolower(str_replace(' ', '', $summonerName));
if(!$summoner)
die();
$results = #file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/' . $summoner->id . '/ranked?season=SEASON2016&api_key=' . $apiKey);
if(!isset($results[0]))
die();
$gaza = json_decode($results);
if(!$gaza)
die();
// =====
$entriesz = $gaza->champions;
usort($entriesz, function($ac, $bc){
return $bc->stats->totalSessionsPlayed-$ac->stats->totalSessionsPlayed;
});
// =====
foreach($entriesz as $statSummaryz) {
if($tmp++ < 11) {
$getLeagueNamelistside = $statSummaryz->id;
$getsessionsplayedNamelistside = $statSummaryz->stats->totalSessionsPlayed;
$getMiniomskillsNamelistside = $statSummaryz->stats->totalMinionKills;
$getkillsNamelistside = $statSummaryz->stats->totalChampionKills;
$getassistssNamelistside = $statSummaryz->stats->totalAssists;
$getdeathsNamelistside = $statSummaryz->stats->totalDeathsPerSession;
$getlosseslistside = $statSummaryz->stats->totalSessionsLost;
$getwinslistside = $statSummaryz->stats->totalSessionsWon;
$Percentkillrateside = $getkillsNamelistside / $getsessionsplayedNamelistside;
$Percentassistrateside = $getassistssNamelistside / $getsessionsplayedNamelistside;
$Percentdeathrateside = $getdeathsNamelistside / $getsessionsplayedNamelistside;
$KDAside = ($getkillsNamelistside + $getassistssNamelistside) / $getdeathsNamelistside;
$KDAMinniomsSide = $getMiniomskillsNamelistside / $getsessionsplayedNamelistside;
$PercentWinRateSide = 100 / ($getlosseslistside + $getwinslistside) * $getwinslistside;
if($getLeagueNamelistside >= 1) {
$results = #file_get_contents('https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion/' . $getLeagueNamelistside . '?api_key=' . $apiKey);
if(!isset($results[0]))
die();
}
$summonerz = json_decode($results, true);
if(!$summonerz)
die();
$getLeagueNamelistsidez = $summonerz['name'];
$getLeagueKeyNamelistsidez = $summonerz['key'];
echo
'<p><img src="http://lolchecker.esy.es/LOLGGWP/img/champion/', $getLeagueKeyNamelistsidez, '.png"></p>',
$getLeagueNamelistsidez,
'<p> Kills ', number_format((float)$Percentkillrateside, 1, '.', ''),
'</p><p> Deaths ', number_format((float)$Percentdeathrateside, 1, '.', ''),
'</p><p> Assists ', number_format((float)$Percentassistrateside, 1, '.', ''),
'</p><p> KDA ', number_format((float)$KDAside, 2, '.', ''),
':1 KDA</p><p> CS ', number_format((float)$KDAMinniomsSide, 1, '.', ''),
' CS</p><p> Games Played ', $getsessionsplayedNamelistside,
'</p><p> Win Rate ', number_format((float)$PercentWinRateSide, 0, '.', ''),
'%</p>', "\n";
}
elseif($getLeagueNamelistside == 0)
die();
}

Formatting String in PHP

I am trying to display numbers retrieved from the database, in a specific format in a text box.
There are two ways in which the numbers can be displayed.
When the total numbers are 10
in database (4608061019) Expected output 46-0806-1019
When the total numbers are 13
in database (4608061019100) Expected output 46-0806-1019-100
My progress so far:
While saving the value into the database I am using
preg_replace("/[^0-9]/","",$string); // to make sure all hardcoded "-" are removed while storing.
One possible (regex-using) approach:
$str = '4608061019';
$formatted = preg_replace(
'/(^\d{2}|\d{4})(?!$)/', '$1-', $str);
// 46-0806-1019
Demo. This function doesn't check the string's length - it just adds a hyphen after each relevant sequence of symbols (2 right after the beginning, 4 afterwards).
Easy! If you are sure that there are only these two options, then you can do this way:
Convert the number to an array of numbers:
$number = str_split($number);
Check the length:
if (count($number) == 10)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9];
else if (count($number) == 13)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9] . "-" . $number[10] . $number[11] . $number[12];
Return the number:
return $number;
The full function here:
function tokenize($number)
{
$number = str_split($number);
if (count($number) == 10)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9];
else if (count($number) == 13)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9] . "-" . $number[10] . $number[11] . $number[12];
return $number;
}
Output
echo tokenize(4608061019);
echo tokenize(4608061019100);
Output
46-0806-1019
46-0806-1019-100
Fiddle: http://codepad.viper-7.com/EVWeFR
Another alternative solution:
$parts = array(2,4,4,3);
$string = "4608061019100";
$i = 0;
$newString = '';
foreach ($parts as $part) {
$newString.=substr($string, $i, $part) ."-";
$i = $i+$part;
}
$newString = rtrim($newString, "-");
Output is:
string '46-0806-1019-100' (length=16)
Works for 46-0806-1019 too.
try it:
//$number = '4608061019';
$number = '4608061019100';
function formatImportantNumber($theNumber){
$formatedNumber = '';
if(strlen($theNumber)==10){
//46-0806-1019
$formatedNumber = substr($theNumber, 0, 2).'-'.substr($theNumber, 2, 4).'-'.substr($theNumber, 6, 4);
}elseif(strlen($theNumber)==13){
//46-0806-1019-100
$formatedNumber = substr($theNumber, 0, 2).'-'.substr($theNumber, 2, 4).'-'.substr($theNumber, 6, 4).'-'.substr($theNumber, 10, 3);
}else{
die('Invalid number formated')
}
return $formatedNumber;
}
echo formatImportantNumber($number);

Microsoft Azure and SAS for PHP

i trying to create SAS link to blob resource using PHP. Unfortunately currently in azure SDK there is no method for creating SAS signature.
I wrote a code for generating SAS but when i'm trying to get a resource by the link generated by this method i'm getting this message: Signature fields not well formed.
public function getSharedAccessSignatureURL($container, $blob)
{
$signedStart = date('c', strtotime('-1 day'));
$signedExpiry = date('c', strtotime('+1 day'));
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$responseContent = "file; attachment";
$responseType = "binary";
$canonicalizedResource = '/'.$this->account['accountName'].'/'.$container.'/'.$blob;
$signedVersion = '2014-02-14';
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion;
$signature = base64_encode(
hash_hmac(
'sha256',
urldecode(utf8_encode($stringToSign)),
$this->account['primaryKey'],
true
)
);
$arrayToUrl = [
'sv='.urlencode($signedVersion),
'st='.urlencode($signedStart),
'se='.urlencode($signedExpiry),
'sr='.urlencode($signedResource),
'sp='.urlencode($signedPermission),
'rscd='.urlencode($responseContent),
'rsct='.urlencode($responseType),
'sig='.urlencode($signature)
];
$url = 'https://'.$this->account['accountName'].'.blob.core.windows.net'.'/'
.$container.'/'
.$blob.'?'.implode('&', $arrayToUrl);
return $url;
}
Any suggest what i am doing wrong? I am commpletle newbie at Microsoft Azure
I believe there's an issue with your $stringToSign variable. Based on the documentation here: http://msdn.microsoft.com/en-US/library/azure/dn140255.aspx, your string to sign should be constructed like the following:
StringToSign = signedpermissions + "\n"
signedstart + "\n"
signedexpiry + "\n"
canonicalizedresource + "\n"
signedidentifier + "\n"
signedversion + "\n"
rscc + "\n"
rscd + "\n"
rsce + "\n"
rscl + "\n"
rsct
considering you're including rscd and rsct in your SAS querystring. Please try the following and see if that makes the difference:
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion."\n".
"\n".
$responseContent."\n".
"\n".
"\n".
$responseType;
UPDATE
Please try the code below. Replace the account name/key, container name and blob name with appropriate values:
<?php
$signedStart = gmdate('Y-m-d\TH:i:s\Z', strtotime('-1 day'));
echo $signedStart."\n";
$signedExpiry = gmdate('Y-m-d\TH:i:s\Z', strtotime('+1 day'));
echo $signedExpiry."\n";
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$accountName = "[account name]";
$accountKey = "[account key]";
$container = "[container name]";
$blob = "[blob name]";
$canonicalizedResource = '/'.$accountName.'/'.$container.'/'.$blob;
$signedVersion = '2014-02-14';
echo $canonicalizedResource."\n";
$rscc = '';
$rscd = 'file; attachment';//Content disposition
$rsce = '';
$rscl = '';
$rsct = 'binary';//Content type
$stringToSign =
$signedPermission."\n".
$signedStart."\n".
$signedExpiry."\n".
$canonicalizedResource."\n".
$signedIdentifier."\n".
$signedVersion."\n".
$rscc."\n".
$rscd."\n".
$rsce."\n".
$rscl."\n".
$rsct;
echo $stringToSign."\n";
$signature = base64_encode(
hash_hmac(
'sha256',
$stringToSign,
base64_decode($accountKey),
true
)
);
echo $signature."\n";
$arrayToUrl = [
'sv='.urlencode($signedVersion),
'st='.urlencode($signedStart),
'se='.urlencode($signedExpiry),
'sr='.urlencode($signedResource),
'sp='.urlencode($signedPermission),
'rscd='.urlencode($rscd),
'rsct='.urlencode($rsct),
'sig='.urlencode($signature)
];
$url = 'https://'.$accountName.'.blob.core.windows.net'.'/'
.$container.'/'
.$blob.'?'.implode('&', $arrayToUrl);
echo $url."\n";
?>
Essentially there were two issues (apart from incorrect $stringToSign variable):
Start/End date time were not properly formatted.
We would need to base64_decode the account key for calculating signature.
I run into exactly the same problem. But now you can use MicrosoftAzure\Storage\Common\SharedAccessSignatureHelper which can handle a lot of problems for you. I has been added to the common libary 2 years ago in this PR (https://github.com/Azure/azure-storage-php/pull/73/files).
And it should be solved very simple like this:
$sasHelper = new SharedAccessSignatureHelper(
'nameofyouraccount',
'H...your-token...=='
);
$sas = $sasHelper->generateAccountSharedAccessSignatureToken(
'2018-11-09',
'rwl',
'b',
'sco',
(new \DateTime())->modify('+10 minute'),
(new \DateTime())->modify('-5 minute'),
'',
'https'
);
$connectionString = "BlobEndpoint=https://nameofyouraccount.blob.core.windows.net/;SharedAccessSignature={$sas}";
And you got your connection string!
modified and turned in to a function from #Gaurav Mantri
function generateSasToken($bucket,$key, $accountName, $accountKey){
$signedStart = gmdate('Y-m-d\TH:i:s\Z', time());
$signedExpiry = gmdate('Y-m-d\TH:i:s\Z', time()+3600);
$signedResource = 'b';
$signedPermission = 'r';
$signedIdentifier = '';
$canonicalizedResource = '/' . $accountName . '/' . $bucket . '/' . $key;
$signedVersion = '2014-02-14';
$rscc = '';
$rscd = 'file; attachment';//Content disposition
$rsce = '';
$rscl = '';
$rsct = 'binary';//Content type
$stringToSign =
$signedPermission . "\n" .
$signedStart . "\n" .
$signedExpiry . "\n" .
$canonicalizedResource . "\n" .
$signedIdentifier . "\n" .
$signedVersion . "\n" .
$rscc . "\n" .
$rscd . "\n" .
$rsce . "\n" .
$rscl . "\n" .
$rsct;
$signature = base64_encode(
hash_hmac(
'sha256',
$stringToSign,
base64_decode($accountKey),
true
)
);
$arrayToUrl = [
'sv=' . urlencode($signedVersion),
'st=' . urlencode($signedStart),
'se=' . urlencode($signedExpiry),
'sr=' . urlencode($signedResource),
'sp=' . urlencode($signedPermission),
'rscd=' . urlencode($rscd),
'rsct=' . urlencode($rsct),
'sig=' . urlencode($signature)
];
$url = 'https://' . $accountName . '.blob.core.windows.net' . '/'
. $bucket . '/'
. $key . '?' . implode('&', $arrayToUrl);
return $url;
}

Could this php-iteration be written any shorter/better?

The code works perfect, but since I'm repeating myself (which I like to avoid while programming), I was wondering if this could be written any shorter/better?
$start = getLocaleDate($item[0]['start_day']);
$start = $start['day_int'] . ' ' . $start['month_string'];
if ($item[0]['start_houre'] !== '00:00:00') {
$houre = stripLeadingZero(substr($item[0]['start_houre'], 0, 2));
$minute = substr($item[0]['start_houre'], 3, 2);
$start .= ' at' . $houre . 'u' . $minute;
}
$end = getLocaleDate($item[0]['end_day']);
$end = $end['day_int'] . ' ' . $end['month_string'];
if ($item[0]['end_houre'] !== '00:00:00') {
$houre = stripLeadingZero(substr($item[0]['end_houre'], 0, 2));
$minute = substr($item[0]['end_houre'], 3, 2);
$end .= ' at' . $houre . 'u' . $minute;
}
Without changing any of the functionality, you could make it into a function:
function getTime($item, $which) {
$time = getLocaleDate($item[0][$which . '_day']);
$time = $time['day_int'] . ' ' . $time['month_string'];
if ($item[0][$which . '_houre'] !== '00:00:00') {
$houre = stripLeadingZero(substr($item[0][$which . '_houre'], 0, 2));
$minute = substr($item[0][$which . '_houre'], 3, 2);
$time .= ' at' . $houre . 'u' . $minute;
}
return $time;
}
$start = getTime($item, 'start');
$end = getTime($item, 'end');
* It should be noted that this code doesn't do any error checking/prevention though, so if there is no index 0 in the $item, you will have an error (same goes for $item[0]['start_day'], $item[0]['end_day'], etc). To handle a simple-case, you could add if (!isset($item[0])) return ''; to the beginning of the function, if it's a concern.
sure could you can write a function where you pass in your item and the key to use
function your_function($item, $key) {
$h = $item[$key.'_houre'];
$time = getLocaleDate($item[$key. '_day']);
$time = $end['day_int'] . ' ' . $end['month_string'];
if ($h !== '00:00:00') {
$houre = stripLeadingZero(substr($h , 0, 2));
$minute = substr($h , 3, 2);
$time .= ' at' . $houre . 'u' . $minute;
return $time;
}
}
your_function($item[0], 'end');
your_function($item[0], 'start');

Categories