Class to manipulate .ini files in php - php

I've been playing around with a php class I found on the net called Config Magik that I use to store some info in a INI file but have recently run into some problems when using removeKey. I wanted to know if someone can point me to a similar class that would work as well or better. Or if there is a better way to go about this.
This is my function right now, after playing around with it like crazy, so it is probably very faulty.
require_once('class.ConfigMagik.php');
$config = new ConfigMagik('config.ini', true, true);
if(!empty($_GET)){
if(!is_writeable('config.ini')){
echo 'Could not write to config.ini';
return false;
}
//if there is no section parameter, we will not do anything.
if(!isset($_GET['section'])){
echo false; return false;
} else {
$section_name = $_GET['section'];
unset($_GET['section']); //Unset section so that we can use the GET variable to manipulate the other parameters in a foreach loop.
if (!empty($_GET)){
foreach ($_GET as $var => $value){
echo $var.'='.$_GET[$var].'<br />';
//Check if said variable $var exists in the section.
if($config->get($var, $section_name) !== NULL){
//Set variable value.
try{
$config->set($var, $value, $section_name);
echo 'Setting variable '. $var.' to '.$value.' on section '.$section_name;
} catch(Exception $e) {
echo 'Could not set variable '.$var;
echo $e;
return false;
}
} else {
echo $var.' does not exist <br />';
}
}
}
try{
$section = $config->get($section_name); //Get the entire section so that we can manipulate it.
echo '<pre>';print_r($section);echo '</pre>';
foreach ($section as $title=>$value){
if(!isset($_GET[$title]) && isset($section[$title])){
try{
$config->removeKey($title, $section_name);
echo '<b>'.$title.'</b>: removed <br />';
} catch(Exception $e){
echo $e;
}
}
}
} catch(Exception $e){
echo $e;
}
$config->save();
//echo $config->toString('HTML');
echo true;
return true;
}
} else { RUN SOME HTML }
It basically saves the settings I pass on from the GET parameters and if the parameters are not there it is supposed to delete it. When I get to $config->removeKey($title, $section_name); in the last try catch statement it won't save automatically (as it should), so I tried running $config->save() and I ended up with a ini file that had section = array everywhere. Any advice will be appreciated as I've been learning PHP on the web for the last few weeks so I believe I've got a ways to go.
I have definitely isolated the problem to the $config->save() part, just don't know how to solve it.
Thanks in advance.

I have been using Zend_Config_Ini and Zend_Config_Writer_Ini in the past and was satisfied with the features. You will have extract the whole library/Zend/Config folder from Zend Framework and make Zend_Exception available though.

Related

How to add an error handling to read an XML file in php?

I am developing a PHP script that allows me to modify tags in an XML file and move them once done.
My script works correctly but I would like to add error handling: So that if the result of my SQL query does not return anything display an error message or better, send a mail, and not move the file with the error and move to the next.
I did some tests but the code never displays the error and it moves the file anyway.
Can someone help me to understand why? Thanks
<?php
}
}
$xml->formatOutput = true;
$xml->save($source_file);
rename($source_file,$destination_file);
}
}
closedir($dir);
?>
Give this one a try
$result = odbc_fetch_array($exec);
if ($result === false || $result['GEAN'] === null) {
echo "GEAN not found for $SKU_CODE";
// continue;
}
$barcode = (string) $result['GEAN'];
echo $barcode; echo "<br>"; //9353970875729
$node->getElementsByTagName("SKU")->item(0)->nodeValue = "";
$node->getElementsByTagName("SKU")->item(0)->appendChild($xml->createTextNode($result[GEAN]));

Display the value of variables in PHP, as soon as they are specified

I want to get about 50 variables from several different sites and show them to user, with PHP Simple HTML DOM Parser.
My Code Structure is something like this:
<?php
include('simple_html_dom.php');
$html = file_get_html('https://site1.com/name1/');
foreach ($html->find('span#name1') as $e) {
$name1 = $e->outertext;
echo $name1;
break;
}
$html = file_get_html('https://site2.com/family1/');
foreach ($html->find('span#family1') as $e) {
$family1 = $e->outertext;
echo $family1;
break;
}
$html = file_get_html('https://site3.com/degree1/');
foreach ($html->find('span#degree1') as $e) {
$height1 = $e->outertext;
echo $height1;
break;
}
$html = file_get_html('https://site4.com/height1/');
foreach ($html->find('span#height1') as $e) {
$height1 = $e->outertext;
echo $height1;
break;
}
// About 30 other blocks of code similar to the above code
?>
At the moment, this code works well and displays the variables, but as expected, it takes about two or three minutes to do this process and show all the variables to the user, which is a lot of time.
Now I'm looking for a way to show to the user (send result to browser), each variable that was found and then find the next variable.
For example, when the value of $name1 is specified, show it to the user and then go to specify the value of $family1
Apparently I should use flush() to fix this problem, but unfortunately I could not find a solution to fix this problem.
You can use ob_flush approach like:
<?php
include('simple_html_dom.php');
$html = file_get_html('https://site1.com/name1/');
foreach ($html->find('span#name1') as $e) {
$name1 = $e->outertext;
echo $name1;
break;
}
flush();
ob_flush();
$html = file_get_html('https://site2.com/family1/');
foreach ($html->find('span#family1') as $e) {
$family1 = $e->outertext;
echo $family1;
break;
}
flush();
ob_flush();
$html = file_get_html('https://site3.com/degree1/');
foreach ($html->find('span#degree1') as $e) {
$height1 = $e->outertext;
echo $height1;
break;
}
flush();
ob_flush();
$html = file_get_html('https://site4.com/height1/');
foreach ($html->find('span#height1') as $e) {
$height1 = $e->outertext;
echo $height1;
break;
}
flush();
ob_flush();
// About 30 other blocks of code similar to the above code
?>
This code after each block flush PHP output to browser.
You will most likely need to architect your app slightly differently. A relatively simple approach would be to to an AJAX call for each variable you need to show, and let the client (browser) decide when to make each call so you can parallelize them. Each call would hit one (and only one) remote URL. This way, you can display results as they come in as AJAX responses.
A slightly more complex approach would be to use Websockets to send back new information as it becomes available. But I think this might be overkill.
In any case both solutions require more browser / JavaScript work than PHP.

Writing data to php file

Trying data taken from the form to inscribe another PHP file by using the file functions.php.
It works great, except that it only retrieves data from the form, but it doesn't retrieve/register data that I wish to input such as html tags that are required to properly operate the website.
I would be grateful for advice.
/** php function file dir: ‘/themes/dir/securedir/subdir/functions.php’ */
/** php form file dir: ‘/themes/dir/formsdir/subdir/forms.php’ */
function updateVesti() {
If (isset($_GET['pn-path'])){
/** path: ‘/themes/dir/pagedir/subdir/phpfile.php’ */
$pn_path = $_REQUEST['pn-path'];
$inputs = !empty($_REQUEST['novosti']) ? $_REQUEST['novosti'] : array();
if(!$fhandle = fopen($pn_path,"w")){
header("Location: ../error.php?err=updateVesti() fhandle razlicno od fopen");
exit();
}
if (is_writable($pn_path)) {
foreach($inputs as $value) {
$val1 = '<li class="news-item"><a href="#">';
$val2 = '</a></li></br>';
$contents = $val1. $value. $val2; /** write only $value? */
echo $contents;
$novosti = $value .PHP_EOL;
if (fwrite($fhandle, $novosti) === FALSE) {
header("Location: ../error.php?err=updateVesti() fwrit = false");
exit();
}
}
}else{
header("Location: ../error.php?err=updateVesti() file is not writible");
}
fclose($fhandle);
header('Location: ../dir/index.php');
exit();
}else{
exit();
}
}
strong text**
Аs we usually gets reliable solution! Leave aside the work for some time and the solution will appear on its own! Minor changes in the code name for the variable, and now works great! Probably from fatigue make such omissions, although surprising is that I failed to find a similar problem across the board! I hope this example will help someone, if nothing else to know that they should take proper rest to be fresh in the brain!
...
$value = $val1. $value. $val2; // instead of $content
echo $value;
$novosti = $value .PHP_EOL;
...

PHP preg_match() steam link validation error

What's wrong with this preg_match() usage? I want to check steam lobby link and if it's matching then write to database. If not, just echo the error. I am doing this through ajax. Is it better to do this with ajax or $_SERVER["REQUEST_METHOD"] == "POST"?
<?php
require("../includes/config.php");
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^((steam?:)+(/joinlobby\/730\/)+([0-9]{17,25}\/.?)+([0-9]{17,25})/$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
else {
$rank = "Golden";
$mic = "No";
try {
$stmt=$db->prepare("INSERT INTO created_lobby (lobby_link, current_rank, have_mic) VALUES (:lobby_link, '$rank', '$mic')");
$stmt->execute(array(
':input_link' => $_POST['lobbyLink']
));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
My Problem:
When I execute this code, it will give me false.
Thank you for help.
This works:
$lobby = "steam://joinlobby/730/109775243427128868/76561198254260308";
if (!preg_match("%^(steam?:)+(//joinlobby/730/)+([0-9]{17,25}/.?)+([0-9]{17,25}$)%i", $lobby)) {
echo "Lobby link isn't formatted correctly.";
}
I changed /joinlobby to //joinlobby, and remove the / at the end. I also removed the unnecessary () around everything.
I suspect you also shouldn't have (...)+ around steam?: and //joinlobby/730/. They'll cause repeated uses of those prefixes to be accepted as correct, e.g. steam:steam:...

Handle error when getimagesize can't find a file

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}

Categories