php info gives me error_reporting local value 4177 [duplicate] - error-reporting

In my local dev env, I use PHP Version 5.3.3-1ubuntu9.2.
Now when I see error_reporting, the value is 22527.
What is 22527?
I checked http://www.php.net/manual/en/errorfunc.constants.php, but I could not find the number.
Could anyone tell me what it is?
Do I need to change it to E_ALL | E_STRICT ?
Thanks in advance.

This value is actually bitmap mask, a sum of constants.
So, 22527 is
16384 E_USER_DEPRECATED
+
4096 E_RECOVERABLE_ERROR
+
etc...
In your case it's E_ALL & ~E_DEPRECATED, it will display every error, except E_DEPRECATED.
PHP versions below 5.4 will also exclude E_STRICT errors (since E_STRICT is not included in E_ALL before that version)

This value is one or more of these constants bitwise-ored together.
phpinfo() usually displays the numeric value instead of the constants or shorthands used inside INI files. Here is an example to map the value back to constants:
<?php
$error_reporting_value = 22527;
$constants = array(
"E_ERROR",
"E_WARNING",
"E_PARSE",
"E_NOTICE",
"E_CORE_ERROR",
"E_CORE_WARNING",
"E_COMPILE_ERROR",
"E_COMPILE_WARNING",
"E_USER_ERROR",
"E_USER_WARNING",
"E_USER_NOTICE",
"E_STRICT",
"E_RECOVERABLE_ERROR",
"E_DEPRECATED",
"E_USER_DEPRECATED",
"E_ALL"
);
$included = array();
$excluded = array();
foreach ($constants as $constant) {
$value = constant($constant);
if (($error_reporting_value & $value) === $value) {
$included[] = $constant;
} else {
$excluded[] = $constant;
}
}
echo "error reporting " . $error_reporting_value . PHP_EOL;
echo "includes " . implode(", ", $included) . PHP_EOL;
echo "excludes " . implode(", ", $excluded) . PHP_EOL;
Output:
error reporting 22527
includes E_ERROR, E_WARNING, E_PARSE, E_NOTICE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_RECOVERABLE_ERROR, E_USER_DEPRECATED
excludes E_STRICT, E_DEPRECATED, E_ALL

NEVER use the numeric value to set your error reporting, as the meaning of that value can change but the meaning of the constants (like E_ALL, E_STRICT, etc) likely will not:
The new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.
(and note that as of PHP 5.4, E_ALL now includes E_STRICT)
IF you want the strictest reporting forever and ever, you could set error_reporting to a very large number in order to guarantee(?) that you will report all errors forever :
Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL).
Check your php.ini for the value of error_reporting in human-readable PHP constants format. The phpinfo() function appears to always show the numeric value rather than showing the constants.
But, personally, I leave php.ini with the default values for error reporting. Instead I just put the error reporting function at the top of whatever php script I'm working on to override the defaults. e.g.:
error_reporting(E_ALL | E_STRICT);

$ php -i | grep error_reporting
o/p is 22527
Go To
https://maximivanov.github.io/php-error-reporting-calculator/
Enter 22527 in Resulting Error Level box.
O/p is E_ALL & ~E_STRICT & ~E_DEPRECATED
OR
$arr = array_flip(array_slice(get_defined_constants(true)['Core'], 0,15));
$needToRemove = array('E_ALL','E_STRICT','E_DEPRECATED');
$filtered = array_diff($arr, $needToRemove);
print_r($filtered);
echo array_sum(array_flip($filtered));
o/p is
Array
(
[1] => E_ERROR
[4096] => E_RECOVERABLE_ERROR
[2] => E_WARNING
[4] => E_PARSE
[8] => E_NOTICE
[16] => E_CORE_ERROR
[32] => E_CORE_WARNING
[64] => E_COMPILE_ERROR
[128] => E_COMPILE_WARNING
[256] => E_USER_ERROR
[512] => E_USER_WARNING
[1024] => E_USER_NOTICE
[16384] => E_USER_DEPRECATED
)
22527

Related

How to generate multiple qr codes in laravel

I am working on a project in which i have to generate QR codes based on number of members in database. Each qrcode will have a unique string so i am generating a random string of 30 chracters. As of now i have 5000 members in database and i need to generate 5000 QR Codes.
When i run the application it fetches total number of records from database and in foreach loop i am generating QR Code, but the server responds to 503 error after 40-50 seconds though i set the limit in php ini setting for max execution time at 3600. below is the my code. I need advice on how can i achieve my goal what is best practice and how i can generate QR code in bulk with unique string and avoid duplicating qr code and store the qr image in storage folder as well its filename in database for later use to print it.
$data = \DB::connection('mysql2')->table('basicinfo')->where('is_approved','=','1')->whereIn('classOfMembership',$member_arr)->get(); //this return 4808 records
foreach($data as $d){
$randomStr = Str::random(33);
$image = QrCode::format('png')
->size(200)->errorCorrection('H')
->generate('https://example.com/'.$randomStr);
$time_now = time();
$output_file = '/qr-code/election-'.$request->election_year.'/img-' . $time_now . '.png';
$image_name = 'img-' . $time_now . '.png';
$insert_arr[] = [
'election_year' => $request->election_year,
'position' => $request->post,
'qr_hash' => $randomStr,
'qr_code_image' => $image_name
];
Storage::disk('local')->put($output_file, $image);
}
Ballot::insert($insert_arr);

get random password with puppet function

I have a function that allow me to generate random password. My function is working well without a puppetmaster. When I tried with a master an error appear when I called the function :
Error 400 on SERVER: bad value for range
Here is my function:
module Puppet::Parser::Functions
newfunction(:get_random_password, :type => :rvalue, :doc => <<-EOS
Returns a random password.
EOS
) do |args|
raise(Puppet::ParseError, "get_random_password(): Wrong number of arguments " +
"given (#{args.size} for 1)") if args.size != 1
specials = ((33..33).to_a + (35..38).to_a + (40..47).to_a + (58..64).to_a + (91..93).to_a + (95..96).to_a + (123..125).to_a).pack('U*').chars.to_a
numbers = (0..9).to_a
alphal = ('a'..'z').to_a
alphau = ('A'..'Z').to_a
length = args[0]
CHARS = (alphal + specials + numbers + alphau)
pwd = CHARS.sort_by { rand }.join[0...length]
return pwd
end
end
The function is called in both case with $pwd = get_random_password(10).
When I specified the length directly in the function to 10 for example. The password is well generated in master mode.
Have you any idea why I can't specify the length value?
It's unclear why this works for puppet apply (if that's what you're insinuating), but the error is most likely a typing issue.
Try
length = args[0].to_i
To my Knowledge,For situations like this I use the puppet generate() function to create the random password and store it in a persistent data store on the master.
For instance,an SQLITE database or something. This way, the password is generated randomly if it does not exist and the same password is used if it does already exist.
It's important to have the resource always be managed, that way if the password is changed on the managed node Puppet will realize this, change it to the value you're managing, and report that it did so.

Single quotes, double quotes and passwords containing $ in Windows and Unix

I'm writing a PHP script to automate a mysqldump command. The method I've selected is using exec( $exec_string . ' 2>&1' ). This script must work on Windows and *nix platforms.
Sadly, some passwords contain the dreaded $ symbol, and so the `-p'passwordcontaining$' must be quoted.
Here are the challenges I've noted so far:
On *nix, you must use the single quote, otherwise it will expand the
$ as a variable.
On Windows, you must use the double quote, because single quotes are treated literally
Escaping the $ is not an option, because on Windows the backslash is only interpreted as the escape character when preceding the double quote (\"), so \$ would be interpreted literally
I don't know how to reliably detect OS to be able to "interactively" switch between single and double quotes.
Is there a trick I am missing that will work cross-platform?
You can dump from within a pdo PHP script :
<?php
$dumpSettings = array(
'include-tables' => array('table1', 'table2'),
'exclude-tables' => array('table3', 'table4'),
'compress' => CompressMethod::GZIP, /* CompressMethod::[GZIP, BZIP2, NONE] */
'no-data' => false, /* http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_no-data */
'add-drop-table' => false, /* http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_add-drop-table */
'single-transaction' => true, /* http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction */
'lock-tables' => false, /* http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_lock-tables */
'add-locks' => true, /* http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_add-locks */
'extended-insert' => true /* http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_extended-insert */
);
$dump = new MySQLDump('database','database_user','database_pass','localhost', $dumpSettings);
$dump->start('forum_dump.sql.gz');
See https://github.com/clouddueling/mysqldump-php
Not crazy about the approach I ended up adopting (MySQLDump class seems to be a more robust approach than exec() ), but here it is in case it helps anyone.
Even though I didn't want to do OS detection, at first blush it doesn't seem that I can resolve the issues in quote interpretation. Happily, OS detection is relatively easy, if you're prepared to make some assumptions, such as "if it ain't running on Windows, then it's on some kind of *nix server".
Here's my basic approach, which I'm sure will get flamed.
// Inside class
protected $os_quote_char = "'"; // Unix default quote character
// Inside constructor
// Detect OS and set quote character appropriately
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
$this->os_quote_char = '"';
// Method for adding quotes
/**
* Adds the OS non-interpreted quote character to the string(s), provided each string doesn't already start with said quote character.
*
* The quote character is set in the constructor, based on detecting Windows OSes vs. any other (assumed to be *nix).
* You can pass in an array, in which case you will get an array of quoted strings in return.
*
* #param string|array $string_or_array
* #return string|array
*/
protected function os_quote( $string_or_array ){
$quoted_strings = array();
$string_array = (array) $string_or_array;
foreach ( $string_array as $string_to_quote ){
// don't quote already quoted strings
if ( substr( $string_to_quote, 0, 1 ) == $this->os_quote_char )
$quoted_strings[] = $string_to_quote;
else
$quoted_strings[] = $this->os_quote_char . $string_to_quote . $this->os_quote_char;
}
if ( is_array( $string_or_array ) )
return $quoted_strings;
else
return $quoted_strings[0];
}
// Actual usage example:
if ( function_exists( 'exec' ) ){
list( $user, $pwd, $host, $db, $file ) = $this->os_quote( array( DB_USER, DB_PASSWORD, DB_HOST, DB_NAME, $backup_file.'.sql' ) );
$exec = $this->get_executable_path() . 'mysqldump -u' . $user . ' -p' . $pwd . ' -h' . $host . ' --result-file=' . $file . ' ' . $db . ' 2>&1';
exec ( $exec, $output, $return );
}
It's hard to guess, what limitations you are talking about, but I suspect some of them are false
passthru('mysqldump -uddd -p"pass\'word$" ddd');
Worked for me under Windows and FreeBSD, as well as the command itself in the respective shells

Scraping multiple items off of a Page into a Neat Row

As an example:
I load in the input from a .txt:
Benjamin,Schuvlein,Germany,1912,M,White
I do some code that I will not post here for brevity and get to the link:
https://familysearch.org/pal:/MM9.1.1/K3BN-LLJ
I want to scrape multiple things from that page. In the code below, I only do 1.
I'd also like to make each item be separated by a , in the output .txt.
And, I'd like the output to be preceded by the input.
I'm using the following packages in the code:
use strict;
use warnings;
use WWW::Mechanize::Firefox;
use Data::Dumper;
use LWP::UserAgent;
use JSON;
use CGI qw/escape/;
use HTML::DOM;
Here's the relevant code:
my $ua = LWP::UserAgent->new;
open(my $o, '>', 'out2.txt') or die "Can't open output file: $!";
# Here is the url, although in practice, it is scraped itself using different code
my $url = 'https://familysearch.org/pal:/MM9.1.1/K3BN-LLJ';
print "My URL is <$url>\n";
my $request = HTTP::Request->new(GET => $url);
$request->push_header('Content-Type' => 'application/json');
my $response = $ua->request($request);
die "Error ".$response->code if !$response->is_success;
my $dom_tree = new HTML::DOM;
$dom_tree->write($response->content);
$dom_tree->close;
my $str = $dom_tree->getElementsByTagName('table')->[0]->getElementsByTagName("td")->[10]->as_text();
print $str;
print $o $str;
Desired Output (from that link) is something like:
Benjamin,Schuvlein,Germany,1912,M,White,Queens,New York,Married,Same Place,Head, etc ....
(How much of that output section is scrapable?)
Any help on how to get the link within the link would be much appreciated!
This is fairly simply done using HTML::TreeBuilder::XPath to access the HTML. This program builds a hash of the data using the labels as keys, so any of the desired information can be extracted. I have enclosed in quotes any fields that contain commas or whitespace.
I don't know whether you have the permission of this web site to extract data this way, but I should draw your attention to this X-Copyright header in the HTTP responses. This approach clearly falls under the header of programmatic access.
X-Copyright: COPYRIGHT WARNING Data accessible through the FamilySearch API is protected by copyright. Any programmatic access, reformatting, or rerouting of this data, without permission, is prohibited. FamilySearch considers such unauthorized use a violation of its reproduction, derivation, and distribution rights. Contact devnet (at) familysearch.org for further information.
Am I to expect an email from you? I replied to your first mail but haven't heard since.
use strict;
use warnings;
use URI;
use LWP;
use HTML::TreeBuilder::XPath;
my $url = URI->new('https://familysearch.org/pal:/MM9.1.1/K3BN-LLJ');
my $ua = LWP::UserAgent->new;
my $resp = $ua->get($url);
die $resp->status_line unless $resp->is_success;
my $tree = HTML::TreeBuilder::XPath->new_from_content($resp->decoded_content);
my #results = $tree->findnodes('//table[#class="result-data"]//tr[#class="result-item"]');
my %data;
for my $item (#results) {
my ($key, $val) = map $_->as_trimmed_text, $item->content_list;
$key =~ s/:$//;
$data{$key} = $val;
}
my $record = join ',', map { local $_ = $data{$_}; /[,\s]/ ? qq<"$_"> : $_ }
'name', 'birthplace', 'estimated birth year', 'gender', 'race (standardized)',
'event place', 'marital status', 'residence in 1935',
'relationship to head of household (standardized)';
print $record, "\n";
output
"Benjamin Schuvlein",Germany,1912,Male,White,"Assembly District 2, Queens, New York City, Queens, New York, United States",Married,"Same Place",Head
Try this
use LWP::Simple;
use LWP::UserAgent;
use HTML::TableExtract;
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
$ua = LWP::UserAgent->new;
$ua->agent("Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.91 Safari/537.11");
$req = HTTP::Request->new(GET => "https://familysearch.org/pal:/MM9.1.1/K3BN-LLJ");
$res = $ua->request($req);
$content = $res->content;
#$content = get("https://familysearch.org/pal:/MM9.1.1/K3BN-LLJ") or die "Couldn't get it! $!";
$te = HTML::TableExtract->new( attribs => { 'class' => 'result-data' } );
# $te = HTML::TableExtract->new( );
$te->parse($content);
$table = $te->first_table_found;
# print $content; exit;
# $te->tables_dump(1);
#print Dumper($te);
#print Dumper($table);
print $table->cell(4,0) . ' = ' . $table->cell(4,1), "\n"; exit;
Which prints out
event place: = Assembly District 2, Queens, New York City, Queens, New York, United States
I also noticed this header:
X-Copyright:COPYRIGHT WARNING Data accessible through the FamilySearch API is protected by copyright. Any programmatic access, reformatting, or rerouting of this data, without permission, is prohibited. FamilySearch considers such unauthorized use a violation of its reproduction, derivation, and distribution rights. Contact devnet (at) familysearch.org for further information.
See also http://metacpan.org/pod/HTML::Element#SYNOPSIS
I thought I had answered your question.
The problem is that you are trying to fetch the webpage with LWP. Why are try to doing that if you already have WWW::Mechanize::Firefox?
Did you tried this?
It will retrieve and save each link for further analyses. A small change and you 'get' the DOM tree. Sorry, I do not have acccess to this page, so I just hope it will work.
my $i=1;
for my $link (#links) {
print Dumper $link->url;
print Dumper $link->text;
my $tempfile = './$i.html';$i++;
$mech->get( $link, ':content_file' => $tempfile, synchronize => 1 );
my $dom_tree = $mech->document();
my $str = $dom_tree->getElementsByTagName('table')->[0]->getElementsByTagName("td")->[9]->as_text();
}
EDIT:
Process the page content with regexp (Everyone: Please remember, there is always more than one way to do something wwith Perl!. It works, it is easy...)
it tried it out with this cmd:
wget -nd 'https://familysearch.org/pal:/MM9.1.1/K3BN-LLJ' -O 1.html|cat 1.html|1.pl
use Data::Dumper;
use strict;
use warnings;
local $/=undef;
my $html = <>;#read from file
#$html = $mech->content( format => 'html' );# read data from mech object
my $data = {};
my $current_label = "not_defined";
while ($html =~ s!(<td[^>]*>.*?</td>)!!is){ # process each TD
my $td = $1;
print "td: $td\n";
my $td_val = $td;
$td_val =~ s!<[^>]*>!!gis;
$td_val =~ s!\s+! !gs;
$td_val =~ s!(\A\s+|\s+\z)!!gs;
if ($td =~ m!result-label!){ #primitive state machine, store the current label
print "current_label: $current_label\n";
$current_label = $td_val;
} elsif ($td =~ m!result-value!){ #add each data to current label
push(#{$data->{$current_label}},$td_val);
} else {
warn "found something else: $td\n";
}
}
#process it using a white lists of known entries (son,race, etc).Delete from the result if you find it on white list, die if you find something new.
#multi type
foreach my $type (qw(son wife daughter head)){
process_multi($type,$data->{$type});
delete($data->{$type});
}
#simple type
foreach my $type (qw(birthplace age)){
process_simple($type,$data->{$type});
delete($data->{$type});
}
die "Unknown label!".Dumper($data) if scalar(keys %{$data})>0;
Output:
'line number:' => [
'28'
],
'estimated birth year:' => [
'1912'
],
'head' => [
'Benjamin Schuvlein',
'M',
'28',
'Germany'
],

SimpleXML Reading node with a hyphenated name

I have the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<gnm:Workbook xmlns:gnm="http://www.gnumeric.org/v10.dtd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gnumeric.org/v9.xsd">
<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:ooo="http://openoffice.org/2004/office" office:version="1.1">
<office:meta>
<dc:creator>Mark Baker</dc:creator>
<dc:date>2010-09-01T22:49:33Z</dc:date>
<meta:creation-date>2010-09-01T22:48:39Z</meta:creation-date>
<meta:editing-cycles>4</meta:editing-cycles>
<meta:editing-duration>PT00H04M20S</meta:editing-duration>
<meta:generator>OpenOffice.org/3.1$Win32 OpenOffice.org_project/310m11$Build-9399</meta:generator>
</office:meta>
</office:document-meta>
</gnm:Workbook>
And am trying to read the office:document-meta node to extractthe various elements below it (dc:creator, meta:creation-date, etc.)
The following code:
$xml = simplexml_load_string($gFileData);
$namespacesMeta = $xml->getNamespaces(true);
$officeXML = $xml->children($namespacesMeta['office']);
var_dump($officeXML);
echo '<hr />';
gives me:
object(SimpleXMLElement)[91]
public 'document-meta' =>
object(SimpleXMLElement)[93]
public '#attributes' =>
array
'version' => string '1.1' (length=3)
public 'meta' =>
object(SimpleXMLElement)[94]
but if I try to read the document-meta element using:
$xml = simplexml_load_string($gFileData);
$namespacesMeta = $xml->getNamespaces(true);
$officeXML = $xml->children($namespacesMeta['office']);
$docMeta = $officeXML->document-meta;
var_dump($docMeta);
echo '<hr />';
I get
Notice: Use of undefined constant meta - assumed 'meta' in /usr/local/apache/htdocsNewDev/PHPExcel/Classes/PHPExcel/Reader/Gnumeric.php on line 273
int 0
I assume that SimpleXML is trying to extract a non-existent node "document" from $officeXML, then subtract the value of (non-existent) constant "meta", resulting in forcing the integer 0 result rather than the document-meta node.
Is there a way to resolve this using SimpleXML, or will I be forced to rewrite using XMLReader? Any help appreciated.
Your assumption is correct. Use
$officeXML->{'document-meta'}
to make it work.
Please note that the above applies to Element nodes. Attribute nodes (those within the #attributes property when dumping the SimpleXmlElement) do not require any special syntax to be accessed when hyphenated. They are regularly accessible via array notation, e.g.
$xml = <<< XML
<root>
<hyphenated-element hyphenated-attribute="bar">foo</hyphenated-element>
</root>
XML;
$root = new SimpleXMLElement($xml);
echo $root->{'hyphenated-element'}; // prints "foo"
echo $root->{'hyphenated-element'}['hyphenated-attribute']; // prints "bar"
See the SimpleXml Basics in the Manual for further examples.
I assume the best way to do it is to cast to array:
Consider the following XML:
<subscribe hello-world="yolo">
<callback-url>example url</callback-url>
</subscribe>
You can access members, including attributes, using a cast:
<?php
$xml = (array) simplexml_load_string($input);
$callback = $xml["callback-url"];
$attribute = $xml['#attributes']['hello-world'];
It makes everything easier. Hope I helped.

Resources