...

Hi! I’m Starx

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

Is it possible to switch in PHP based on version?

Question by Dave M G

I have a function in one of my PHP scripts that relies on version 5.3 to run.

I thought that if it was in a function that didn’t happen to get called when run on a server with PHP 5.2 or earlier, then it would just be ignored. However, it turns out that when that script, and the class inside it, even just gets included, then PHP bails and stops executing.

If I can avoid it, I’d like to not have to branch of different versions of my scripts dedicated to different PHP versions. Instead, it would be ideal to be able to have code that says “If PHP version 5.3, then do this, if less, then do something different.”

I’Ve looked for some kind of “version switch” in the PHP manual, but didn’t see one.

Is a switch function like I’m describing possible?

Answer by Starx

There are numerous ways to solve this. I prefer detecting the version and executing function.

  1. There is a function called phpversion() or constant PHP_VERSION that gives you the current php version

    Use them like

    if(phpversion() == '5.3') {
      //specific php functions
    }
    
  2. To check if the current version is newer or equal to lets say ‘5.3.2’. simply use:

    if (strnatcmp(phpversion(),'5.3.2') >= 0) {
        # equal or newer
    }
    else {
       # not 
    }
    
  3. Or, use version_compare to know

    if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
        echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "n";
    }
    

Or ever more user friendly version is to use function_exists()

if (!function_exists('function_name')) {
    // the PHP version is not sufficient
}
Read more

Multiple onload conflict

Question by bpok

Hi there… I’ve run into a problem using the jQuery thumbnail scroller. It clashes with Fancybox and another script I’ve been using based on the onload event. I found this function which enables multiple onload events to fire by simon wilson:


function func1() {
  alert("This is the first.");
}
function func2() {
  alert("This is the second.");
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(func1);
addLoadEvent(func2);
addLoadEvent(function() {

I WANT TO INSERT THE FOLLOWING JQUERY FUNCTION HERE

})

My problem now is getting the 3rd function to work correctly. It’s a syntax problem.

Here is the jQuery I want to insert:

jQuery.noConflict();
(function($){
window.onload=function(){ 
    $("#tS3").thumbnailScroller({ 
        scrollerType:"hoverPrecise", 
        scrollerOrientation:"vertical", 
        scrollSpeed:2, 
        scrollEasing:"easeOutCirc", 
        scrollEasingAmount:800, 
        acceleration:4, 
        scrollSpeed:800, 
        noScrollCenterSpace:10, 
        autoScrolling:0, 
        autoScrollingSpeed:2000, 
        autoScrollingEasing:"easeInOutQuad", 
        autoScrollingDelay:500 
    });
}
})(jQuery);

Any suggestions much appreciated!

Answer by Starx

Why do you need to do this? Why do you need to queue the onload handlers like that? And since you are using jQuery already, why are using native handlers already?

function func1() { ... }
function func2() { ... }
function thumbScroller() {
$("#tS3").thumbnailScroller({ 
        scrollerType:"hoverPrecise", 
        scrollerOrientation:"vertical", 
        scrollSpeed:2, 
        scrollEasing:"easeOutCirc", 
        scrollEasingAmount:800, 
        acceleration:4, 
        scrollSpeed:800, 
        noScrollCenterSpace:10, 
        autoScrolling:0, 
        autoScrollingSpeed:2000, 
        autoScrollingEasing:"easeInOutQuad", 
        autoScrollingDelay:500 
    });
}

Now call them all collectively

jQuery(document).ready(function() {
    func1();
    func2();
    thumbScroller();
});
Read more
April 27, 2012

php available options

Question by lexvdpoel

Possible Duplicate:
How to generate all permutations of a string in PHP?

I want to make a script in php that will take this input:

12a

And output a result like so:

1, 2, a, 12, 1a, 21, 2a, a1, a2, 12a, 1a2, 21a, 2a1.

I did some research but I cannot find any script that will do this.

Answer by Starx

Here is a modified function from this answer

function permute($str,$i,$n) {
   if ($i == $n)
       print "$strn";
   else {
        for ($j = $i; $j < $n; $j++) {
          swap($str,$i,$j);
          permute($str, $i+1, $n);
          swap($str,$i,$j); // backtrack.
       }
   }
}

// function to swap the char at pos $i and $j of $str.
function swap(&$str,$i,$j) {
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
}   

$str = "12a";
$len = strlen($str);
for($i =0; $i <= $len; $i++) {
   permute($str,0,$i + 1); // call the function.
}
Read more

Get JSON Data – newbie here

Question by redditor

I am using the Songkick API to list the next gig date, I have adapted the code found here. This is a copy of the JSON data source.

The HTML:

<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.livequery.js" type="text/javascript"></script>
<script src="jquery.nano.js" type="text/javascript"></script>
<script src="application.js" type="text/javascript"></script>
</head>
<body>
<ul id="concerts">Loading Next Gig...</ul>
</body>

application.js is:

$(document).ready(function () {
  var template = "<li>Our next gig is <a href='{uri}'>{displayName}</a></li>";
  var apikey = 'MY_API_KEY';
  var container = $("ul#concerts");
  $.getJSON('http://api.songkick.com/api/3.0/artists/253846/calendar.json?apikey=' + apikey + '&jsoncallback=?', function(data) {
    container.html("");
    events = data["resultsPage"]["results"]['event'];
if (events==null) {
      container.append($.nano());
}
else {
      container.append($.nano(template, events[0]));
}
  });
});

I would like to display for the first listed gig only,

event.location.city
event.venue.displayName
event.start.date (in dd MMM format).

If no events are listed, I would like it say something like “There are currently no gigs booked at the moment, please [a href="example.com"] click here [/a] for up to date information.”

Answer by aSeptik

  var events = data.resultsPage.results.event;
  $.each(events, function (i, item) {
        container.append($.nano(template, item));
    });

NOTE: since you are using $.nano you should iterate over the json object in order to replace the shortcode inside the template var.

if you want to access the json properties singularly you should access it like below:

var uri = events.uri;
var displayName = events.displayName;

you full code will look like this:

$(document).ready(function () {
    var template = "<li>Our next gig is <a href='{uri}'>{displayName}</a></li>";
    var apikey = 'MY_API_KEY';
    var container = $("ul#concerts");
    $.getJSON('http://api.songkick.com/api/3.0/artists/253846/calendar.json?apikey=' + apikey + '&jsoncallback=?', function (data) {
        container.html("");
        var events = data.resultsPage.results.event;
        if (events !== null) {
      $.each(events, function (i, item) {
            container.append($.nano(template, item));
        });
        }
    });
});

Answer by Starx

Access the json tree with . (Dots)

events = data.resultsPage.results.event;
Read more

PHP doesn't see MySQL

Question by Marco

I’ve already seen this post PHP doesn't see mysql extension, but it didn’t help me.
I use:

  • Windows Seven (both 32bit in a VM and 64bit on a real pc)
  • Apache 2.2 with SSL
  • PHP 5.3.8
  • MySql 5.5.23

In httpd.conf I configured Apache with PHP

PHPIniDir "C:WEBPHP"
LoadModule php5_module "C:WEBPHPphp5apache2_2.dll"
ScriptAlias /php "C:/WEB/PHP/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"

In php.ini I set

extension_dir = "C:/WEB/PHP/ext/"
[PHP_MYSQL]
extension=php_mysql.dll
[PHP_MYSQLI]
extension=php_mysqli.dll

MySql is started and working, but PHP does not see mysql.
I’ve also tried to copy libmysql.dll into %windir%system32 and restarted web server, but it didn’t work.
If you need I can post other info.

UPDATE 1:
Running <?php phpinfo(); ?> I can only see mysqlnd, but not mysql nor mysqli.
If I run php -i I see

mysql

MySQL Support => enabled
Active Persistent Links => 0
Active Links => 0
Client API version => mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $

UPDATE 2:
Apache, PHP and MySQL folders are the same of a previous working pc.
I copied them, reconfigured paths, installed and started services:

httpd -k install && httpd -k start
mysqld --install && net start mysql

UPDATE 3:

  • I’m able to use mysql through a DOS console
  • If I try to run an existing PhpMyAdmin I get The mysql extension is missing. Please check your PHP configuration.

UPDATE 4:
I checked with Everything and the only php.ini I have on my pc is the one in php folder.

UPDATE 5:
I tried this code:

<?php
ini_set('display_errors', 'on');
error_reporting(E_ALL);
mysql_connect();
?>

and I get Fatal error: Call to undefined function mysql_connect() in C:varwwwApachetest.php on line 4

Answer by Starx

The most feasible and time saving option I see now, is to do the fresh installation of WAMP itself, and migrate the old files and dbs to the new one.

Read more

jQuery: How to close ajax loaded page and bring back old content?

Question by jwaldeck

I’m developing a one page portfolio site which will pull projects from separate html files. So, currently I have this code that loads the new URL (specifically the “#project” div) into the current div “#port-content”.

Part of my custom.js follows:

var hash = window.location.hash.substr(1);
var href = $('.ajax').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
    var toLoad = hash+'.html #project';
    $('#port-content').load(toLoad)
        }                                           
    });

    $('a.port-more').click(function(){                        
        var toLoad = $(this).attr('href')+' #project';
        $('#port-content').hide('normal',loadContent);
        window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
        function loadContent() {
            $('#port-content').load(toLoad,'',showNewContent())
        }
        function showNewContent() {
            $('#port-content').show('normal');
        }
        return false;
    });

How can I close this content and bring back my original “#port-content” div. I tried to create a new fucntion doing the opposite but it didn’t work.

Any ideas?

Tks in advance!
jw

Answer by Starx

Using .data() sound like the correct option for this.

function loadContent() {
   if(!$('#port-content').data('default')) $("#port-content").data('default', $("#port-content").html());
   $('#port-content').load(toLoad,'',showNewContent())
}
// and create another function to load the default
function loadDefault() {
  $('#port-content').html($("port-content").data('default'));
}
Read more

What Data Type is $('#checkbox').attr('checked')

Question by Jonathan Wood

I’ve done a lot of searching on the web and found examples that treat $('#checkbox').attr('checked') as a string and others that treat it as a Boolean.

In my case, I find that this statement works as expected:

$('#AcceptAgreement').attr('checked', false);

But this one does not:

if ($('#AcceptAgreement').attr('checked') == true)

The second statement is false because in fact the value is ‘checked’.

So which is it? Is it a string or Boolean value, and how can I read and write it in a reliable manner?

Answer by Kevin B

This depends on which version of jQuery you are using.

checked is both a property and an attribute. In older versions of jQuery, .attr() always returned the property, not the attribute, which was usually a boolean value. Newer versions of jquery (1.6+) have a new method called .prop which returns the boolean property value, while .attr() now properly returns the string value. I’m not sure if the attribute is always updated when the property changes.

Answer by Starx

There is a fundamental way of finding out the data types

console.log(typeof $('#AcceptAgreement').attr('checked'));

But before jQuery 1.7, it used to return property value, now it returns pure string.

Another alternative to this is .prop('checked') which return boolean.

Read more

PHP not working correctly in WordPress

Question by Alexander Charles

I have made a plain PHP widget to be displayed on a WordPress sidebar. I have successfully made the widget post the data I am hoping to have filled in on the consecutive page. However where it is supposed to be will not fill in, instead it fills in with "<?php echo $_GET[" then after the text box " />". I am hoping that the email first submitted will fill in on the form on the next page. The code that I have for the registration form is part of a greater widget and looks like the following:

<p class="form-email'.$errorVar.'">
      <label for="email">'. __('E-mail', 'profilebuilder') .$errorMark.'</label>
      <input class="text-input" name="email" type="text" id="email" value="<?php echo $_GET["email"]; ?>" /> 
</p><!-- .form-email -->';

Here is a link to the page: http://universityoutfitters.com/testphp/ — the widget is on the bottom left hand side panel.

Additional information:
The code for the widget is as follows:

<form action="http://universityoutfitters.com/sign-up/" method="post">
    Please submit your email address
    Email: <input type="text" name="email" />
<input type="submit" />
</form> 

Answer by Starx

As the comments told above, you have to wrap it correctly with PHP tags

<?php
echo '<p class="form-email'.$errorVar.'">
      <label for="email">'. __('E-mail', 'profilebuilder') .$errorMark.'</label>
      <input class="text-input" name="email" type="text" id="email" value="'.$_GET["email"].'" /> 
</p><!-- .form-email -->';
?>
Read more

How capture the default.phtml in a variable inside a controller

Question by Jack

I have a simple question… How could I render the contents of the default.phtml which is in Project/application/layouts/scripts/default.phtml to a variable, so I can have its html.

In the index controller, with an action and a phtml file named test, this would work:

$html = $this->view->render('index/test.phtml');

But, of course, this does not:

$htmlDefaultLayout = $this->view->render('default.phtml');

Since default.phtml is not inside any controller, I guess.

Is there a good way to do that?

Answer by drew010

You can add to the path that Zend_View looks in for views so you could then render the default.phtml file.

Example:

// add the layout directory to the path
$this->view->addScriptPath(APPLICATION_PATH . '/layouts/scripts/');

$htmlDefaultLayout = $this->view->render('default.phtml');

The last path added to the scriptPath in Zend_View are the first to be checked (LIFO).

See View Script Paths.

Answer by Starx

You can stop the rendering and grab the output like this:

$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$this->view->addScriptPath(APPLICATION_PATH . '/layouts/scripts/'); //default layout path
$htmlDefaultLayout = $this->view->render('default.phtml');
Read more

Best-practice approach to reset CSS styles on a specific element?

Question by shackleton

I’m building an html5/js/css application that will exist inside of a div on my client’s existing html. I want to be sure that none of the client’s CSS styles are inherited by my app.

Is there a best practice to reset this div and its descendant elements?

I’m thinking I’ll use something like:

#my-id * { //styles }

I’m wondering if there is a better/best-practice approach? Thanks.

Answer by Faust

That will be very difficult/likely impossible to ensure. The type of solutions that Ben Roux is referring to (update: Ben removed his answer, but this is now Starx’ answer) assume no preset styles other than the browser defaults, and “reset” in that context refers to harmonizing the inconsistencies across various browser defaults.

But in your case, your client CSS may already contain highly specific selectors such as

#someDiv .aClass a{float:left;}

… and applying those “CSS reset” solutions simply will not override this.

You can see that Truth’s selectors also have lower specificity than this, and therefore will fail to ovetride the client’s styles in such cases.

Your question is very similar: How to remove all inherited and computed styles from an element?

So the short answer is: there is no way to ensure this because you cannot “remove all inherited and computed styles from an element” … update: …unless you can anticipate and override every preexisting style declaration with new declarations having appropriate specificity.

Answer by Starx

You are probably looking for Eric’s CSS Reset as it one of robust resets out there.

But the reset rule is applied to the whole page, instead of the just the box. SO, modify the rules, by keeping #my-id infront.

Read more
...

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