...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
February 27, 2012

How to write a custom Zend validator to check the hash of a file against a database record

Question by blainarmstrong

I’m building a file repository where each file has a database entry associated with it. In that database, I include the sha1 hash value for the file. Also, for security reasons, I rename each file with a specific pattern, so I can’t check the filename directly via the form’s filename value.

I’m trying to prevent people from uploading the same file twice, so I want to create a form validator that takes the file being uploaded and checks the hash of the file against all the values in the database. If the hash is already in the database–and thus the file already exists–the validator should return false. How access the file from inside the validator class so I can calculate the hash?

Answer by Starx

Your question is very badly asked. So I will not dig into the logic of it.Sorry Here is a very simple example of how you can create a Custom Validation Class.

The most important thing you need to remember is two methods.

  1. isValid(): Returns either true or false through a logic
  2. getMessages(): Returns errors messages in case of invalid.

Here is a basic example of comparing whether a user is admin or not.

class CustomValidate_UserAdmin extends Zend_Validate_Abstract
{
    $admin = "username"; //I am using a static value this time

    protected $_messageTemplates = array(
        self::FLOAT => "'%value%' is not an admin"
    );

    public function isValid($value)
    {
        $this->_setValue($value);

        if($this -> admin == $value) {     
             return true;
        }
    }
}

Now use it

$element->addValidator(new CustomValidate_UserAdmin('username'));

This is a very simple example to understand. You can replace it with your logic with a lot of ease I think.

Updates


Add validation like this…

$element->addValidator(new CustomValidate_Hash('file/location', $hashvaluettocompare));

Now in your validation class

function isValid($location, $value) {
   if(hash_file("md5", $location)==$value) return true;
}
Read more

PHP Html Dom/Parser

Question by gir3191

i) I need to extract few elements from a html page using php.

ii) Am using html dom parser.

iii) I have been able to extract all **<a>**s, **<b>**s, **<li>**s, etc.

iv) How should I be able to extract elements of the type/enclosed within

**<td class = ""><a href = "">ABC</a></td>**

Anything using href, i.e. property of href

Note: I need to extract ABC

Answer by Starx

You will not get the entire structure using the DOM Parser.

You should use getAttribute() method for that purpose. Check here

Here is a simple example also

$markup = file_get_contents($someplace);
$dom = new DomDocument();
$dom -> loadHTML($markup);
$tds = $dom -> getELementsByTagName("td");
foreach($tds as $td) {
    echo $td -> getAttribute("class");
}
Read more

how to append a div tag generated by jQuery dynamically with a javascript div tag element

Question by subhojit777

I want to append a div tag generated by jQuery dynamically with a javascript div tag element. My code looks like this:

$(".remove_item").click(function(){
  $(this).hide("fast", function(){
  var id = $(this).parent().attr("id");
  var remove_item_id = document.getElementById(id);
  var block_element = document.getElementById("block");

  block_element.removeChild(remove_item_id);

  new_item = $("<div/>");
  new_item.attr("id", "item");
  new_item.attr("name", "item");
  new_item.addClass("div_image");
  new_item.append($("<img/>")
  .addClass("image")
  .attr("src", "/compare/sites/default/files/add_item.jpg")
  .attr("height", 50)
  .attr("width", 50));

  new_item.append($("<span/>")
  .addClass("new_item")
  .click(function(){
  $(this).parent().remove();
  }));

  block_element.append(new_item);
});
});

The code for appending the jQuery div tag with javascript div tag should look like this:
block_element.append(new_item);

But its giving error since we cannot bind since I am using javascript and jQuery in the same line. Is there any way to do it?

Answer by Starx

The only thing, you need to change is

var block_element = $("#block");
$("#"+remove_item_id).remove();

Rest should work as it is.

Read more

jQuery validation not working when radio button selected

Question by Jacob1

I have jQuery validation for my form. There is a radio box (attendance) and 2 drop down menus (colour and shade).

It works perfectly if the user logs in for the very first time. However because I have retreived the value from the database based on what they have selected before, if the user has already selected their choice and log back in, if they previously selected ‘No’ then my jQuery does not work. The two dropdown menus submit and are not greyed out as they should be. But if I click on ‘No’ radio box it does. Not sure if issue lies with jQuery or my radio button.

If the user logged in for the first time and selects ‘No’, they boxes grey out immediately.

jQuery validation:

<script src="jquery.js"></script>
 <script>      
    $( function(){    
            function validate(id){       
                var enabled = ($("input[name='attendance" + id + "']:checked").val() == 'Yes');         
                if(enabled){              
                    //Please select option is selected              
                    if($("#colour" + id)[0].selectedIndex == 0){                 
                    alert('Please make your colourselection');                  
                    return false;             
                    }              
                    //Please select option is selected              
                    if($("#shade" + id)[0].selectedIndex == 0){                  
                        alert('Please select your shade');                  
                        return false;             
                    }   
                }     
                return true;    
            };

            $("input[name^='attendance']").click(function() {  

                var id = this.name.replace('attendance', '');      
                $("#colour" + id + ", #shade" + id).prop("disabled", this.value == 'No');         
                validate(id);    
            });      
           $("input:submit").click(function(){         
               var retVal = true;
               $.each([1], function(i, val){
                  retVal = (validate(val) && retVal);
               });
                return retVal;   
           }); 
         }); 
  </script>

radio button:

<input name="attendance1" type="radio" id="Yes" value="Yes" checked="CHECKED" <?php if($row3['attendance1']=="Yes") { echo "checked"; }?>/>Attend with pleasure 
<br />
<input name="attendance1" type="radio" id="No" value="No" <?php if($row3['attendance1']=="No") { echo "checked"; }?>/>Decline with regret 

Answer by Starx

The problem I see is this part

checked="CHECKED" <?php if($row3['attendance1']=="Yes") { echo "checked"; }?>

This will render to the following if $row3['attendance1'] is “Yes”

checked="CHECKED" checked

So this will create problem. Remove checked="CHEKCED" part.

Read more

What is ~ for CSS

Question by Lap Ming Lee

I want to know what the ~ is used for in CSS.

e.g.

#confirmPage:target ~ #navigation #confirm-link,

Answer by minitech

It means “general sibling”. The selector:

a ~ b

matches every element matching b that comes after an element matching a, within the same parent element. For example, take this structure:

<p>
    <span>Span 1</span>
    <strong>Strong emphasis</strong>
    <span>Span 2</span>
</p>

The selector p span ~ span will match the second <span>.

Answer by Starx

The tilde(~) is used for the indirect adjacent combinator as part of a selector. Its part of CSS Sibling Combinator. [docs here]

If you see adjacent selector a + b the style will match once the b comes right after a

But, a ~ b generalizes the selection so that b can come to any position after a.

Example:

h1 ~ pre

represents a pre element following an h1. It is a correct and valid, but partial, description of:

<h1>Definition of the function a</h1>
<p>Function a(x) has to be applied to all figures in the table.</p>
<pre>function a(x) = 12x/13.5</pre>
Read more
February 26, 2012

Why can't I enable and uncheck an element with jQuery?

Question by just_name

I want to enable and set check = false by editing this code?

if (confirm('This widget will be removed, ok?')) {
    $(​'table tr input[type=hidden]').filter(function() {
        return $(this).val()​​​​​ == widgetId;
    }).siblings('input[type=checkbox]').attr({disabled: true, checked: true});

I try :

.siblings('input[type=checkbox]').removeAttr('disabled');

and this.

.siblings('input[type=checkbox]').attr({disabled:false, checked: false});

but in vain


EDIT 1:

<table><colgroup><col title="process name"></colgroup> <tbody><tr><td><input name="rlv_mainservices$ctrl0$hf_id" id="rlv_mainservices_ctrl0_hf_id" value="91" type="hidden"> <input id="rlv_mainservices_ctrl0_chb_sys" name="rlv_mainservices$ctrl0$chb_sys" type="checkbox"> <span id="rlv_mainservices_ctrl0_lbl_main_sys">pro1</span> </td></tr></tbody></table><table><colgroup><col title="processname"> </colgroup><tbody><tr><td><input name="rlv_mainservices$ctrl1$hf_id" id="rlv_mainservices_ctrl1_hf_id" value="92" type="hidden"><input id="rlv_mainservices_ctrl1_chb_sys" name="rlv_mainservices$ctrl1$chb_sys" type="checkbox"> <span id="rlv_mainservices_ctrl1_lbl_main_sys">pro2</span> </td></tr></tbody></table>

I wanna to enable input type=”checkbox” if the value of the input type =”hidden” that exist in the same <td> equal to the id of li(widget).This when the user click close.

Answer by Starx

Actually you can do this with jQuery.

To enable

$('#element').removeAttr('disabled');

To uncheck

$('#element').removeAttr('checked');

Or, even Combine them

$('#element').removeAttr('disabled').removeAttr('checked');

Just in case, you manipulated the attribute after it has been loaded, then it will no longer be available as an attribute from jQuery 1.6.

If you are using so and later, try .removeProp( propertyName ) [docs here] instead.

$('#element').removeProp('disabled').removeProp('checked');

Update

  • Update 1: It does work. Check a demo here.

  • Update 2: I have also simulated the manipulation and created another fiddle using .removeProp(), check it here

  • Update 3: Ok, check this update. It it compatible with your markup, however, you might have to use proper selector, for you. However, this will give you the entire idea.

Read more

CodeIgniter forfeit default views

Question by JHollanti

I’m in the process of creating a quick “hack”. I’ve never used CodeIgniter before, so what i’m asking is probably pretty basic stuff.

I have a controller that outputs some JSON data. However, with the setup i’m working with comes a default view which creates some html to the end of the file and so, my JSON parser throws a fit. Is there a way to disable views altogether as i really don’t need a template file of any kind for this purpose?

Answer by Starx

You can simply use an exit() at the end of action to do this.

exit();
Read more

How do I migrate a PHP based website to Joomla?

Question by mtanti

I have a PHP based website, with database connections, form processing, etc, that I need to use a CMS on. I’m trying to use Joomla but after using it for 2 days and reading tutorials on it I’m getting the impression that it’s designed to handle static content and that all form processing is to be handled by 3rd party extensions.

Am I getting the wrong impression? Is there a standard way to import a PHP website into a Joomla CMS?

Answer by Bobby Jack

I inherited a Joomla 1.5 site a few months ago, so I was in a similar situation to you – where to begin, with lots of questions about Joomla, its ethos, etc. What I’ve learnt in the meantime is:

  • Joomla is very heavily dependent on 3rd-party extensions. Some of these are good, some not so good – evaluation and caution is advised.
  • Joomla encourages the use of extensions, even for relatively static content. Whether these are full blown ‘components’, or ‘modules’, depends on quite how powerful/flexible they need to be.
  • The MVC architecture that underlies everything has its positives and negatives. On the plus side, if everything is done consistently, there is a good separation of concerns and – in particular – the template system offers good configurability. On the downside, very simple components/modules have an awful lot of complexity – e.g. just in terms of number of files.
  • Joomla is open-source … sort of. If your familar with the open-source community, you might be a bit disappointed with Joomla, especially when it comes to 3rd-party extensions. Many of them do not embrace the open source ethos, and try to sell code and/or support so, to reiterate, choose your extensions carefully.
  • Writing your own extension is fairly simple, especially if you’re familiar with PHP. Although the documentation isn’t great, there are some gems – in particular, take a look at:
  • When it comes to forms, I’m still undecided. The site I’ve inherited uses a third-party extension to manage them (mod_breezingforms), but it has its issues. If you have the luxury of trying out several alternatives, take it.
  • Run your development site in debug mode. Take a look at database queries. In my own experience, Joomla is very, very demanding on the database. For example, I have some pages that make hundreds of calls to the database with every request. Watch out for this.
  • At some point, you’ll see itemid in the URL and wonder what on earth it is. It refers to a menu item. Menus in Joomla are a bit more general than you might think – they don’t necessarily represent a ‘menu’ and they’re quite important. For example, the built-in way to include content on a series of pages is for them to belong to the same menu item, so you might need to create ‘fake’ menus to house content.

Answer by Starx

This question is very broad to answer. There are few step-by-step tutorial available on the internet for this.

  1. From Joomla
  2. Site Ground tutorial

If you follow this head start. You are sure to know a lot of joomla along way and convert your website to the joomla.


BUT, it is easier to build on Joomla rather than convert to it

Read more

Php that generates XML

Question by dane rias

<?php

require("phpsqlajax_dbinfo.php");
$dom  = new DOMDocument("1.0");
$dp   = fopen('samp.xml', 'w');
$node = $dom->createElement("Groceries");
fwrite($dp, '$node');
$parnode = $dom->appendChild($node);

$connection = mysql_connect($host, $user, $pass);
if (!$connection) {
    die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
    die ('Can't use db : ' . mysql_error());
}

$query  = "SELECT * FROM tbl_groceryitem";
$result = mysql_query($query);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

echo "<groceries>";
while ($row = @mysql_fetch_assoc($result)) {

    $node = $dom->createElement("item");
    echo "<echo>";
    fwrite($dp, '$node');
    $newnode = $parnode->appendChild($node);
    $newnode->setAttribute("auto_id", $row['auto_id']);
    echo "<auto_id>", $row[auto_id];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_barcode", $row['Gro_barcode']);
    echo "<Gro_barcode>", $row[Gro_barcode];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_name", $row['Gro_name']);
    echo "<Gro_name>", $row[Gro_name];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_brand", $row['Gro_brand']);
    echo "<Gro_brand>", $row[Gro_brand];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_category", $row['Gro_category']);
    echo "<Gro_category>", $row[Gro_category];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_aisle", $row['Gro_aisle']);
    echo "<Gro_category>", $row[Gro_aisle];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_qty", $row['Gro_qty']);
    echo "<Gro_qty>", $row[Gro_qty];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_netwt", $row['Gro_netwt']);
    echo "<Gro_netwt>", $row[Gro_netwt];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_pic", $row['Gro_pic']);
    echo "<Gro_pic>", $row[Gro_pic];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_price", $row['Gro_price']);
    echo "<Gro_price>", $row[Gro_price];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_tax", $row['Gro_tax']);
    echo "<Gro_tax>", $row[Gro_tax];
    fwrite($dp, '$newnode');
    echo "</item>";
    fwrite($dp, '</item>');
}
fwrite($dp, '</groceries');
echo $dom->saveXML($xml);

?>

I’m new in php.

I’m creating a php file that can generate xml file with data from myPHPAdmin. Thanks :D. Hope someone can help me.

At first try, the code has been displayed in php and when I open to check for the created XML. the display was ‘$node‘, it reflects the exact string a place inside fwrite, when I try to delete the string quote (”) like this fwrite($dp,$node);. I got error.

And when I try to return the code to fwrite($dp,’$node’);. There was no Display. the XML page is blank.

Answer by Starx

You need to use XML headers when you are creating a XML file with PHP.

<?xml version="1.0" encoding="utf-8"?>

But this is not needed when you are using saveXML() on the end.

Here is an example, picked out from php’s manual.

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:n";
echo $doc->saveXML() . "n";

echo "Saving only the title part:n";
echo $doc->saveXML($title);
?>
Read more

PHP & MySQL date

Question by Ayman Jitan

I am trying to insert in a field of type “timestamp” in MySQL database “CURRENT_TIMESTAMP” and its 2012-2-26 10:04:34 AM in my local are and its the time on my pc
but the thing is that I find it 2012-02-26 02:04:34 in my database
everytime I insert I find different values from my local time
and aslo if I do

echo strtotime('now');

it prints the same value “2012-02-26 02:04:34”

how can I fix , knowing that I am working on a schedule needs to perform operations on a certain time

Answer by Starx

This looks like problem with time zones. Check them in php.ini. Or as suggested my Cheery on the comment, use [docs here]

<?php
date_default_timezone_set('America/Los_Angeles');
?>

However, You should make sure you are using correct methods to input the date and time in the database. There are two ways to do so.

  1. MYSQL: Use NOW() Function

    INSERT INTO table VALUES( data = '$data', date = now());
    
  2. PHP: Use time() Function

    $query = "INSERT INTO table VALUES( data = '$data', date = '".time()."');"
    
Read more
...

Please fill the form - I will response as fast as I can!