Copy of PDF then merge breaks output PDF - php

I am trying to figure out why the following piece of code breaks the outputted PDF..
I am copying several PDF files, and they get combined just fine, and the PDF forms get filled out, but when I enable to code below I only get a blank PDF (Nothing filled in) and this shows up on the error log.
Warning: input PDF is not an acroform, so its fields were not filled.
for ($i = 1; $i <= $totesi; $i++) {
$pgnum = ($i + 1);
if(!copy('../attachment2.pdf', $pgnum . '.pdf')) {
echo 'Failed to Copy';
}
$pdfarr[] .= $pgnum . '.pdf';
}
I build the array so I delete only those files afterwards.
This is the command that combines them, maybe I am missing something?
pdftk *.pdf cat output file.pdf
And again as said with the code above, it doesn't work.
Update:
I tried it with splitting the archive with pdftk it works fine for 1 page, if the array contains less than 10 meters, anything more it will error out.
if ($totesi >= 1) {
for ($i = 1; $i <= $totesi; $i++) {
if(strpos($type, 'Nodal') !== FALSE) {
$tempstr .= ' 6';
} elseif(strpos($type, 'All Inc') !== FALSE) {
$tempstr .= ' 5';
}
}
shell_exec("pdftk 1.pdf cat ".$pdffile." ". $tempstr ." output 1111111.pdf");
unlink('1.pdf');
}
Warning: input PDF is not an acroform, so its fields were not filled.
pdftk 1.pdf cat 1-4 5 5 output 1111111.pdf
This doesn't work either.

Related

Display pictures from a folder in the specific way - PHP

I am trying to create a dynamic gallery in php with specific order of pictures on the page, but I can't find the function or piece of php code to do so.
Conditions:
The gallery must be dynamic, pictures will be coming from a folder via php, because when I'll add/upload more pictures in the folder they must be displayed on the page without adding manually the html tags in. ( this part is easy, problem is the condition 2 ).
The first row will have 5 pictures, the second - 4 pictures (important for the specific effect).
My code:
$files = glob("layout/gallery/*.jpg");
rsort($files, SORT_NATURAL);
for ($i=0; $i < count($files); $i++) {
for( ; $i<5; $i++){
$one = $files[$i];
echo '<img src="'.$one.'">' . '<br><br>';
}
echo '<br>';
for( ; $i<9; $i++){
$two = $files[$i];
echo '<img src="'.$two.'">' . '<br><br>';
}
}
The code works well, but it just displays 9 pictures obviously. I was unable to make it dynamic displaying 5 pictures first, 4 pictures after and stay this way in a loop till displays all pictures from that folder.
You can take advantage of the array_splice function that removes elements from the array everytime it returns those elements :
$files = glob("layout/gallery/*.jpg");
rsort($files, SORT_NATURAL);
// split the files in rows
$rows = [];
while(count($files) != 0) {
// even rows have 5 elements, odd ones have 4
$num_files_to_splice = count($rows) % 2 == 0 ? 5 : 4;
$rows[] = array_splice($files, 0, $num_files_to_splice);
}
// display them accordingly
foreach($rows as $row) {
foreach($row as $file) {
echo '<img src="'.$file.'">';
}
echo '<br><br>';
}

how to use php to read one specific line from a text file that occurs after a tag

I am trying to read data from a plain text file from an industrial machine recipe. The file is generated automatically by the tool. I want to access a specific parameter in a specific section of the file.
The parameter is called "LightSrcRef_NominalGL" The problem is that there are some number of parameters named as such in the file. I specifically want the first one, and only the one, that occurs after the tag "[Scan2d]"
Note that the parameter I need does not always show on the same line number and that [Scan2d] does not always show up in the same place, but I need the parameter in the Scan2d section. It also appears that the LightSrcRef_NominalGL parameter is not always the same number of lines after [Scan2d].
What I had hoped was to read the file line by line. When I get to [Scan2d], set a flag, then when I get to the parameter, set my variable, then get out.
This is not happening. Instead, it is taking the first LightSrcRef_NominalGL in the file.
We have similar recipe analyzers, but this is the first one with this unique recipe structure. I have looked for a way to read the file in differently, but none produce different results.
When I print the actual line, it shows that the text file is reading it line by line. I do not understand why it is not behaving as expected.
Here is example of text file. In this case it is at the end of the file. In others, there will be another section after. I had to add an extra carriage return in the text file because this was not displaying them as separate lines. They are being read in by lines because if I have it print $line, it shows exactly one line.
[Scan2d]
CameraTypeName=2D
FocusPosAboveChuck=-2.59084174217116
Mag=5
CameraName=HighMag
DifRingPos=2
Gamma=-1
LightSrcDif_ColorFilter=Gray
LightSrcDif_NominalGL=0
LightSrcRef_ColorFilter=Cyan
LightSrcRef_NominalGL=195.424629214628
$catcher = 0; //used to verify the parameter only in scan2d section
$lines = file($dir.$default_directory."/".$current_recipe_file);
foreach($lines as $line)
{ $line_count ++;
if(preg_match("/[Scan2d]\b/i", $line))
{
$catcher = $line_count; //used to only catch the parameter in the Scan2D section
}
if(preg_match("/\bLightSrcRef_NominalGL=\b/i", $line))
{
$illumination_split_temp1 = preg_split("/\=/", $line);
$recipe_illum = $illumination_split_temp1[1];
if ($catcher >0)
{print $line . " ". $catcher . "<br>";
$Tool_Ins150_Stats->Add_Recipe_Tag("Illumination Level", $recipe_illum);
$catcher= 0;
break;
}
}
}
It is taking the first LightSrcRef_NominalGL in the file, not the one after Scan2d.
If the tags you are looking for are at the start of the lines in the file this can be made even simpler. I changed what you had slightly so that when the section you are interested in is found the foreach goes to the next record.
$catcher = 0;
foreach($lines as $line) {
if(preg_match("/[Scan2d]\b/i", $line)) {
$catcher = 1;
continue;
}
if(preg_match("/\bLightSrcRef_NominalGL=\b/i", $line)) {
if (!$catcher) {
continue; // we haven't found the right section yet
}
$illumination_split_temp1 = preg_split("/\=/", $line);
$recipe_illum = $illumination_split_temp1[1];
print $line . " ". $catcher . "<br>";
$Tool_Ins150_Stats->Add_Recipe_Tag("Illumination Level", $recipe_illum);
$catcher= 0;
break;
}
}
$lines = file($dir.$default_directory."/".$current_recipe_file);
$catcher = 0; //used to verify the parameter only in scan2d section
foreach($lines as $line)
{
if(preg_match("/\[Scan2d]/", $line))
{
$catcher = 1; //used to only catch the parameter in the Scan2D section
}
if (!$catcher)
{
continue; // haven't found the right one yet, skip the rest
}
else
{
if(preg_match("/LightSrcRef_NominalGL=/", $line))
{
$illumination_split_temp1 = preg_split("/\=/", $line);
$recipe_illum = $illumination_split_temp1[1];
$Tool_Ins150_Stats->Add_Recipe_Tag("Illumination Level", $recipe_illum);
$catcher = 0;
continue;
}
}
}
This worked, but many thanks to Dave who certainly put me on the right track!! The use of Else worked when I still do not fully understand why the second preg_match was executing if $catcher was not set (and it wasn't, I printed it to be sure).
The sample your provided seems to be a file in ini format. If this is really the case, there is a very simple solution using the parse_ini_file function
<?php
$values = parse_ini_file('sample.txt', true, INI_SCANNER_TYPED);
echo "The value is " . $values["Scan2d"]["LightSrcRef_NominalGL"] . "\n";
I tried against this sample.txt file
[test]
LightSrcRef_NominalGL=0
[Scan2d]
CameraTypeName=2D
FocusPosAboveChuck=-2.59084174217116
Mag=5
CameraName=HighMag
DifRingPos=2
Gamma=-1
LightSrcDif_ColorFilter=Gray
LightSrcDif_NominalGL=0
LightSrcRef_ColorFilter=Cyan
LightSrcRef_NominalGL=195.424629214628
[test2]
LightSrcRef_NominalGL=1
And the result is:
The value is 195.42462921463
Of course, this will work only if your entire file respects the ini format as in your sample data.

Unable to save PHP output into text file?

I have created a script that extract certain length of array from a given and print_r the result. This is my code.
<?php
header("Content-Type:text/html");
$i=0;
$file= fopen("list.txt","r");
$get=0;
while (!feof($file)) {
$get.= fgets($file);
}
$explode= explode(" ", $get);
for($i=0; $i<sizeof($explode); $i++)
{
if(strlen($explode[$i])==17)
{
$result = print_r($explode[$i]);
file_put_contents('result.txt',$result);
}
}
?>
Everything is going good but I want output in a text file. For that I'm using file_put_contents() Function but it is display binary number (1,2) in the text file. Can anyone tell me how to save my output into text file?
Please, be specific, try to use my code and tell me the best one! Just tell me what should I do with this section of code below:
> if(strlen($explode[$i])==17)
> {
> $result = print_r($explode[$i]);
>
> file_put_contents('result.txt',$result);
>
> }
This will open the list.txt and save it all to $data.
Look for Mac addresses and save them to the array $macs.
Then arrange them with new lines and save them to result.txt.
Three lines of code instead of sixteen.
$data = file_get_contents("list.txt");
Preg_match_all("/([0-9A-Fa-f:-]{17})/", $data, $macs);
File_put_contents("result.txt", implode(PHP_EOL, $macs[1]));
To save the file that is being displayed on the screen, just put the same $explode[$i] inside the file_put_contents:
if(strlen($explode[$i])==17)
{
$result = print_r($explode[$i]);
file_put_contents('result.txt',$explode[$i]);
}

Xampp ERR_CONNECTION_RESET for 1 file

Currently have a file that is set to read a CSV file. The CSV file contains 1600 api queries. Then each api query then returns more queries that need to be run. I am using Xampp v3.2.2 on windows 10 and running php v5.6.15. When running the file through my browser it ran fine for the first 800+ records in the CSV before timing out. When I rerun the file now I get an error "Site can't be reach ERR_CONNECTION_RESET". Not sure what could be causing this. abbreviated version of the code is included below
<?php
error_reporting(E_ERROR | E_PARSE);
set_time_limit (28800);
$csv = array_map('str_getcsv', file('file.csv'));
for($i = 0; $i < count($csv); $i++){
if($csv[$i][2] == 1){ //this item in csv is flag to check if this item has been run yet
if($csv[$i][3] != 'NULL' && trim($csv[$i][3]) != ''){ // check to make sure there is a URL
$return = file_get_contents(trim($csv[$i][3])); //Get the contents that links to new api calls
if($return){
$isCall = array(); // array to store all new calls
$data = array(); // array to store all data to put in csv
$doc = new DOMDocument('1.0'); // create new DOM object
$doc->loadHTML($return); // load page string into DOM object
$links = $doc->getElementsByTagName('a'); // get all <a> tags on the page
if($links->length > 0){ // if there is at least one <a> tag on page
for($j = 0; $j < $links->length; $j++){ // loop through <a> tags
$isCall[]= $links->item($j)->getAttribute('href'); // get href attribute from <a> tag and push into array
}
for($x = 0; $x < count($isCall); $x++){ // loop through all the calls and search for data
$string = file_get_contents($isCall[$x]);
if($string) {
$thispage = new DOMDocument('1.0');
$thispage->loadHTML($string);
$pagedata = $thispage->getElementsByTagName('div');
if ($pagedata->length > 0) {
for($j = 0; $j < $pagedata->length; $j++) {
$data[] = $pagedata->item($j)->C14N();
}
}
}
if(count($data) >= 5) break; // limiting to 5 data points to be added to csv
}
}
if(!empty($data)) $csv[$i] = array_merge($csv[$i], $data); // if we have data points lets add them to the row in the csv
}
}
$csv[$i][2] = 2; // set the flag to 2
$fp = fopen('file.csv', 'w'); // write the contents to the csv each time through loops so if it fails we start at last completed record
foreach ($csv as $f) {
fputcsv($fp, $f);
}
fclose($fp);
}
}
?>
Usually ERR_CONNECTION_RESET is an error that occurs when the site you are trying to connect to is unable to establish that connection. This usually happens due to reasons like firewall blocking on issues with ISP cache etc.
However in your case, I feel that the site you are connecting to is voluntarily closing connection attempts because what you are trying to do is loop over and hit that API site 1600 times continuously.
The API site is allowing the first 800-odd attempts but after that it gets worried that you are perhaps a malicious script trying to harm it. Like a classical example of DOS (Denial Of Service) attempt.
You should check if there is any restriction to the number of attempts a client can make to the API site with a fixed time (like say 500 hits every 24 hours) or you should try to sleep N seconds after each hit to the site or after each X number of hits to the site.

save info in a specific way into txt file with php [duplicate]

This question already has answers here:
Append to next line in text file using php [duplicate]
(3 answers)
Closed 7 years ago.
I'm working with a txt file and PHP and I need to save data into this txt file, save and open the file is not a problem with file_get_contents and file_put_contents but I have a doubt please help me if you can:
I present the info in this order:
issue info 1
issue info 2
issue info 3
as you can see I show to the user the issues in different lines, but that works when I display that info in the browser but if I open the txt file it shows this:
issue info 1issue info 2issue info3
all in the same line, how can I do in order to save the info into the txt file with the order:
issue info 1
issue info 2
issue info 3
thanks in avance, this is my code by the moment:
$filename = "C:/Users/usuario/Videos/Desktop/prueba.txt";
if(file_exists($filename)) {
$filestring = file_get_contents($filename, NULL, NULL);
$convert = explode("\n", $filestring);
for ($i=0;$i<count($convert);$i++)
{
echo $convert[$i]. "</br>";
}
echo "</br>";
$filestring.= "issue 1"."</br>";
file_put_contents($filename, $filestring);
echo "</br>";
}
else{
die("ese file no existe");
}
Use \n in your code, see this example:
<?php
$string = '';
for($i = 1; $i <= 3; $i++) {
$string .= 'issue info ' . $i . "\n";
}
file_put_contents('11.txt', $string);
?>
Output:
issue info1
issue info2
issue info3
Why not just add a new line characters to your strings (before and after the BR tags)?
"\r\n"
This way, you'll get the line breaks in HTML and in text files.
Also, make sure to double-quote the newline characters, or else PHP will not evaluate them properly.

Categories