reader class not found in GeoIP2 - php

I am trying to install Maxmind's GeoIP2. I did everything by their instructions and I still get this annoying error:
Fatal error: Class 'GeoIp2\Database\reader' not found in C:\Program Files\*\*\localweb\GeoIp2\index.php on line 19
this is how the script looks like inside index.php:
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\reader;
// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('C:/Program Files/*/*/localweb/GeoIp2/Database/GeoLite2-Country.mmdb');
$record = $reader->country('128.101.101.101');
?>
Anybody can help please ?

This worked for me thanks #Greg Oschwald!
Since I'm not using composer, my code now is:
<?php
require 'geoip2.phar';
try {
$reader = new GeoIp2\Database\Reader('GeoLite2-City.mmdb');
$record = $reader->city('128.101.101.101');
print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '??'
print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
print($record->city->name . "\n"); // 'Minneapolis'
print($record->postal->code . "\n"); // '55455'
print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323
} catch (Exception $e) {
echo 'Could not open Phar: ', $e;
}
Took that phar file from https://github.com/maxmind/GeoIP2-php/releases

Try changing:
use GeoIp2\Database\reader;
to:
use GeoIp2\Database\Reader;

Try to up php version to 7.1.33 or higher

Related

How do i exit when error from new CallbackFilterIterator

I'm trying to get the files in a directory in my filesystem. Did some research here and found the necessary info to create the following piece of code that works perfectly!
define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define(FILM_IMG_UPLOAD_DIR, DOCUMENT_ROOT . '/filmography/img/films/');
$files = new filesystemiterator(FILM_IMG_UPLOAD_DIR, FilesystemIterator::SKIP_DOTS);
$filter_files = new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
$num_files = iterator_count($filter_files);
...
The problem is when the directory does NOT exist, i get the error
Fatal error: Uncaught exception 'UnexpectedValueException' with
message
'FilesystemIterator::__construct(C:/public_html/filmography/img/films/,C:/public_html/filmography/img/films/)...
So, how do I exit the code when i get an error from new CallbackFilterIterator ?
Looks to me like you need to wrap the code in a try-catch block.
define('DOCUMENT_ROOT', '/usr/local/share');
define('FILM_IMG_UPLOAD_DIR', DOCUMENT_ROOT . '/film/');
try {
$files = new filesystemiterator(FILM_IMG_UPLOAD_DIR, FilesystemIterator::SKIP_DOTS);
$filter_files = new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
$num_files = iterator_count($filter_files);
}
catch(UnexpectedValueException $e) {
echo "App Exception: " . $e->getMessage() . "\n";
}

PHPUnit testing ExpectedException not throwing exception

Using Laravel framework with phpunit for unit tests.
I am working with a function that requires directories to be created for a file to be written to it, in short, the function gets data, write it to a temp file and moves the temp file once done.
public function getDataAndStoreToCSVFile() {
Log::info(date('Y-m-d H:i:s') . " -> " . __FILE__ . "::" . __FUNCTION__);
try {
// make sure directories exist
if (!Storage::has($this->temporary_directory) || !Storage::has($this->storage_directory)) {
$this->createDirectories();
}
// get full path of storage disk for files
$diskPath = Storage::getAdapter()->getPathPrefix();
// create a complete path to temporary file to allow tempnam to find the directory
$full_temporary_file_path = $diskPath.$this->temporary_directory;
// fetch stations, station networks and station params seperated by double new line,
// will return FALSE if something is missing and file will not be created and not written to
if($stations_data_array = $this->getCompleteStationsDataArray("\n\n")){
// create temporary file
$temporary_file = tempnam($full_temporary_file_path,'') ;
// if both $temporary_file and $stations_data_array exist write entries to file one at a time in CSV format
if (file_exists($temporary_file)) {
$fp = fopen($temporary_file, 'a');
foreach ($stations_data_array as $fields) {
if (is_object($fields) || is_array($fields)) {
// $fields is an array
$fields = (array)$fields;
fputcsv($fp, $fields);
} else {
// $fields is the separator
fwrite($fp, $fields);
}
}
// done writing, close file
fclose($fp);
// create new permanent name for $temporary_file in the storage directory "full_disk_path.storage_path.yyyymmddhhmmss.timestamp"
$storage_file = $diskPath . $this->storage_directory . "/" . date('YmdHis') . "." . time();
// rename $temporary_file to $storage_file
if (!rename($temporary_file, $storage_file)) {
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Failed to move temporary file from " . $this->temporary_directory . " to " . $this->storage_directory);
}
} else{
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Temporary file was not available or does not exist.");
}
} else {
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Temporary file was not created.");
}
} catch (\ErrorException $e) {
// Catches missing directory or file, or tempnam couldn't find temporary storage path //Todo add test for this exception
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
} catch (\Exception $e) {
// Catches uncaught exceptions
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
}
}
To test if ErrorException is thrown when directories are missing, this test :
public function test_getDataAndStoreToCSVFile_handles_ErrorException() {
// set up data
$this->setup_all_data_for_getDataAndStoreToCsvFile_funtion();
// mock class
$mock = $this->getMockBuilder('App\Interfaces\Sources\IdbStationSourceInterface')
// stub function createDirectories, will now return null and not create directories, missing directories will throw ErrorException
->setMethods(['createDirectories'])
->getMock();
// expect the ErrorException to be thrown
$this->expectException('ErrorException');
// run function
$mock->getDataAndStoreToCSVFile();
}
When I run the test, my logs indicate that I fell into :
} catch (\ErrorException $e) {
// Catches missing directory or file, or tempnam couldn't find temporary storage path //Todo add test for this exception
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
}
But my terminal says :
1) Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::test_getDataAndStoreToCSVFile_handles_ErrorException
Failed asserting that exception of type "ErrorException" is thrown.
I have no clue where to go from there, I read and tried a couple of things but clearly I'm doing something wrong.
Edit 1 :
Tried : $this->setExpectedException("ErrorException");
But I get the following :
1) Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::test_getDataAndStoreToCSVFile_handles_ErrorException
Error: Call to undefined method Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::setExpectedException()
Thats because you catched the exception. PHPUnits expectedException-method only registers unhandled or rethrown exceptions. Either rethrow the exception in your catch-block or just test for the log-entry you are creating in the catch-block.
from function getDataAndStoreToCSVFile() you just throw error with error code and message. Then you can use these assertion in test case.
/**
*#expectedException ExampleException
*#expectedExceptionCode ExampleException::EceptionCode
*/
public function test_getDataAndStoreToCSVFile_handles_ErrorException() {}

PHP Warning: require_once(WindowsAzure/Blob/Models/BlockList.php): failed to open stream

I have used azure-sdk-for-php library and I am getting this error-Warning: require_once(WindowsAzure/Blob/Models/BlockList.php): failed to open stream: No such file or directory.
My code is as below-
define("__BLOBNAME__", "BLOBNAME");
define("__CONTAINERNAME__", "CONTAINERNAME");
define("__BLOBKEY__", "BLOBKEY");
//require_once('WindowsAzure\WindowsAzure.php');
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;
use WindowsAzure\Common\CloudConfigurationManager;
use WindowsAzure\Blob\Models\Block;
use WindowsAzure\Blob\Models\CreateContainerOptions;
use WindowsAzure\Blob\Models\ListContainersOptions;
use WindowsAzure\Blob\Models\CreateBlobOptions;
use WindowsAzure\Blob\Models\CommitBlobBlocksOptions;
use WindowsAzure\Blob\Models\BlobProperties;
$connectionString = "DefaultEndpointsProtocol=http;AccountName=" . __BLOBNAME__ . ";AccountKey=" . __BLOBKEY__ . "";
if (null == $connectionString || "" == $connectionString) {
echo "Did not find a connection string whose name is 'StorageConnectionString'.";
exit();
}
// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
try {
// List blobs.
$blob_list = $blobRestProxy->listBlobs(__CONTAINERNAME__);
$blobs = $blob_list->getBlobs();
// iterate over blobs
foreach ($blobs as $blob) {
$options = new WindowsAzure\Blob\Models\CreateBlobOptions();
$options->setBlobCacheControl("public, max-age=604800");
echo 'setting ... ';
$blobRestProxy->setBlobProperties(__CONTAINERNAME__,$blob->getName(), $options);
}
} catch (ServiceException $e) {
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/library/azure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code . ": " . $error_message;
}
It seems that you failed to load the SDK file.
The recommended way to resolve dependencies is to install them using the Composer package manager.
Create a file named composer.json in the root of your project and add the following code to it:
json
{
"require": {
"microsoft/windowsazure": "^0.5"
}
}
Download composer.phar in your project root.
Open a command prompt and execute this in your project root
php composer.phar install
Then load the SDK in your code with:
require_once "vendor/autoload.php";

HTML to PDF Creation in Cakephp

Path : Vendor/dompdf
I am getting Fatal error: Class 'DOMPDF' not found in C:\wamp\www\sms_app\app\Controller\SentMessagesController.php on line 313.
Why i am getting error? This is my code:
function example()
{
//App::import('Vendor','dompdf',array('file'=>'dompdf'.DS.'dompdf_config.inc.php'));
require_once(APP . 'Vendor' . DS . 'dompdf' . DS . 'dompdf_config.inc.php');
$html =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';
try{
$this->dompdf = new DOMPDF();
}
catch (Exception $e)
{
echo $e;
}
$papersize = "legal";
$orientation = 'landscape';
$this->dompdf->load_html($html);
$this->dompdf->set_paper($papersize, $orientation);
$this->dompdf->render();
$output = $this->dompdf->output();
file_put_contents('Brochure.pdf', $output);
}
The error message pretty clearly tells you what is wrong. Check the file(s) you include if the class exists in that file, I doubt it is there. If not figure out in which file the class is and load that file. Check how Dompdf is loading its files.
This error clear says you missing a class so please check how actually importing class in your code.

PHP ZipArchive not adding more than 700 files

I have a problem with the php_zip.dll's ZipArchive class. I'm using it through the ZipArchiveImproved wrapper class suggested on php.net to avoid the max file-handle issue.
The problem is really simple: 700 files are added properly (jpg image files), and the rest fails. The addFile method returns false.
The PHP version is 5.2.6.
The weird thing is that this actually used to work.
What could be the problem? Can you give me any clues?
Thank you very much in advance!
Edit: sorry, it's not true that I'm not getting any error message (display_errors was switched off in php.ini I didn't notice it before). From the 701. file on, I'm getting the following error message:
Warning: ZipArchive::addFile() [ziparchive.addfile]: Invalid or unitialized Zip object in /.../includes/ZipArchiveImproved.class.php on line 104
Looks like the close() call returns false, but issues no error. Any ideas?
Edit 2: the relevant source:
include_once DIR_INCLUDES . 'ZipArchiveImproved.class.php';
ini_set('max_execution_time', 0);
$filePath = $_SESSION['fqm_archivePath'];
$zip = new ZipArchiveImproved();
if(! $zip->open($filePath, ZipArchive::CREATE))
{
echo '<div class="error">Hiba: a célfájl a(z) "' . $filePath . '" útvonalon nem hozható létre.</div>';
return;
}
echo('Starting (' . count($_POST['files']) . ' files)...<br>');
$addedDirs = array();
foreach($_POST['files'] as $i => $f)
{
$d = getUserNameByPicPath($f);
if(! isset($addedDirs[$d]))
{
$addedDirs[$d] = true;
$zip->addEmptyDir($d);
echo('Added dir "' . $d . '".<br>');
}
$addName = $d . '/' . basename($f);
$r = $zip->addFile($f, $addName);
if(! $r)
{
echo('<font color="Red">[' . ($i + 1) . '] Failed to add file "' . $f . '" as "' . $addName . '".</font><br>');
}
}
$a = $zip->addFromString('test.txt', 'Moooo');
if($a)
{
echo 'Added string successfully.<br>';
}
else
{
echo 'Failed to add string.<br>';
}
$zip->close();
It's probably because of maximal number of open files in your OS (see http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/ for more detailed info; it can by system-wide or just user limit).
Zip keeps every added file open until Zip::close is called.
The solution is to close and reopen archive every X files (256 or 512 should be safe value).
The problem is described here: http://www.php.net/manual/en/function.ziparchive-open.php#88765
Have you tried to specify both flags?
I solved this problem by increasing the ulimit: ulimit -n 8192.

Categories