...

Hi! I’m Starx

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

What are good practices of error handling when working with API and PHP?

Question by Strawberry

So I am working with an API, and I wanted to know some good practices of handling errors without breaking the script. Throw anything at me, expose me to more so I can research it further.

Also, examples appreciated, it helps me visually link something to a term/phrase.

Some of my reads:

Error handling in PHP

Answer by Starx

Error Handling, is a big big topic. It cannot be narrowed down to a single answer. Best practices are generally judge on the basis of how user friendly and secured they are. So basically your api, should have multiple feature for error alone.

  • Should include a way to log the errors and display if user requires it.
  • Number your errors. Give every error an unique number to identify it.
  • Bring exceptions into practice. Not every errors are ACTUAL, some are exceptions.
  • Multiple ways to handle the error have to be created. Liking grouping the errors at once or showing each one by one.
Read more
May 11, 2012

How to install zend framwork on Xampp version 1.7.1 in windows7 eternity

Question by Ankan Bhadra

I have downloaded ZendFramework-1.11.11 and it has been extracted and then there is zend folder inside library folder of ZendFramework-1.11.11.And then it is copied and paste in the htdocs of xampp. My Xampp version Xampp win32 1.7.1 or Xampp win32 1.7.7
And Then what to do.To check in browser how to check,like localhost/myzendproject/test1.php
I need step by step guide.And also in test.php what to write for checking and in browser what will be URL.
I need your hand. Pls, guied me step by step
Thank you

Answer by Starx

Installing Zend framework does not depend on the system where it will run. Follow the following article for the correct walk-through. It denotes every actions needed to get started.

Installing Zend Framework On Windows

Read more

Wrapping between nowraps

Question by Eric

I have a list of links that should be displayed inline.
The thing is I do not want the text to wrap in the middle of links. If it needs to wrap, it should only do so between links.

I have therefore added the white-space:nowrap; property to my link. But the resulting list of links never wraps and gets out of my div box.

Any idea how I can get my list to wrap between the links? Thank you!

<div class="box">
<p>
<a href="mylink1" class="mytag">Hello there</a>
<a href="mylink2" class="mytag">Hello you</a>
<a href="mylink3" class="mytag">Hello people</a>
<a href="mylink4" class="mytag">Hello world</a>
</p>
</div>

The relevant CSS is just:

.mytag,.mytag:link,.mytag:visited{
  background-color:#FFF5CA;
  border:1px solid #FFE5B5;
  color:#222;
  padding:2px 5px;
  margin-right:5px;
  white-space:nowrap;
}
.mytag:hover{
  background-color:#FFE5B5;
}

Answer by Starx

Basically, white-space:nowrap; is doing exactly what it is supposed and that is not breaking the elements into multiple lines.

What you are actually looking for is to display the links on a single line, without the links wrapping onto the next line. Therefore, use a display property as inline-block.

.mytag,.mytag:link,.mytag:visited{
  background-color:#FFF5CA;
  border:1px solid #FFE5B5;
  color:#222;
  padding:2px 5px;
  margin-right:5px;
  display: inline-block;
}
Read more

call back function with $this

Question by v0idless

I am trying to use an instance method as a callback for PHP 5.2.1. I am aware that as of PHP 5.4 you can use $this inside a closure, and in PHP 5.3 you can rename $this to $self and pass that to the closure. However, neither of these methods will suffice since I need this to work for PHP 5.2.1. The two commented lines was my last attempt. That results in Fatal error: Call to a member function hello() on a non-object – is there anyway I can have a callback to an instance method in PHP 5.2.1?

<?php

class Test {

    public function __construct() { 
        $self = &$this;

        $cb = function() use ( $self ) {
            $self->hello();
        };
        call_user_func( $cb );


        // $cb = create_function( '$self', '$self->hello();' );
        // call_user_func( $cb );

    }

    public function hello() {
        echo "Hello, World!n";
    }
}

$t = new Test();

Answer by Rocket Hazmat

$cb = create_function('$self', '$self->hello();');

This is just making a function that can take a parameter called $self. It’s the same as this:

function test($self){
    $self->hello();
}

You can try passing $self (or $this) to the function when you call it:

call_user_func($cb, $this);

You can also try to make $self a global variable, so that the anonymous function made by create_function can read it.

$GLOBALS['mySelf'] = $self;
$cb = create_function('', 'global $mySelf;  $mySelf->hello();');
call_user_func($cb);
// You may want to unset this when done
unset($GLOBALS['mySelf']);

Answer by Starx

How about SIMPLICITY?

class Test {

    public function __construct() { 
        $this -> funcName($this);
    }

    public function funcName($obj) {
            $obj->hello();
    }

    public function hello() {
        echo "Hello, World!n";
    }
}

Update: Just tested the codes. They are working fine using this.

call_user_func_array(array($self, "hello"), array());
Read more

CSS not display the content correctly

Question by Ali

I’m trying to create a social widget for my own blog, but I don’t know why when I have everything valid, I mean no syntax error and is not displaying it on my blog correctly?

The code is very long, and I don’t think I should include it here?

So I did include the code here http://jsfiddle.net/naKEv/

I’m trying to make it similar to this

enter image description here

but mine when it displays on my blog is not showing it right.

I’m also using css sprices to combine the pictures, but that is not a problem I guess because if I’m using a table to create the code it still display but not the way it suppose to be.

Answer by Starx

You have fixed the height of #share_icons remove that.

Demo

Read more

Set variable from alias in SQL query

Question by Sherif

I have a simple JOIN query:

$lstCheck = $dbWHMCS->query('SELECT * FROM tblmonitorports mp 
                            INNER JOIN tblmonitorhosts h ON h.hst_id = port_mon 
                            INNER JOIN tblhosting ho ON ho.id = h.hst_serverid
                            INNER JOIN tblclients cl ON cl.id = ho.userid');

while ($data = $lstCheck->fetch())
{
            $serveridx = $data['ho.id'];
            $clientid = $data['cl.id'];
}

My problem is that I have an “id” column in both the tblhosting and tblclients tables, so my variables both have the same id. I tried to set it using an alias in the example above (ho. and cl.) but it doesn’t work. How can I do this in the example above?

Thank you!

Answer by Mirko

How about this? (a bit rusty on php details, but this should do it):


$lstCheck = $dbWHMCS->query('SELECT ho.id hid, cl.id cid FROM tblmonitorports mp 
                            INNER JOIN tblmonitorhosts h ON h.hst_id = port_mon 
                            INNER JOIN tblhosting ho ON ho.id = h.hst_serverid
                            INNER JOIN tblclients cl ON cl.id = ho.userid');

while ($data = $lstCheck->fetch())
{
            $serveridx = $data['hid'];
            $clientid = $data['cid'];
}

Answer by Starx

You are selecting the records, with a wild card *, so you can’t select the fields like that.

As per your query h.hst_serverid & ho.userid have the exact same value as you want. SO simply do this

while ($data = $lstCheck->fetch())
{
            $serveridx = $data['hst_serverid'];
            $clientid = $data['userid'];
}

However, selecting specific rows might sound better too

$lstCheck = $dbWHMCS->query('SELECT ho.id hid, cl.id cid, ....');

while ($data = $lstCheck->fetch())
{
            $serveridx = $data['hid'];
            $clientid = $data['cid'];
}
Read more

Javascript method pause() only works with audio element

Question by Panini Venkataraman

So I have a function like this:

function music(song) {
var audio = new Audio("audio/" + song + ".ogg");
audio.play();
}

And the problem I’m having is that audio.play() works perfectly, but if I try audio.pause() later (after defining the same variable), it doesn’t work. However, if I do this:

function music() {
var audio = document.getElementById("songname");
audio.play();
}

Then I can define the variable and later use audio.pause() to pause the track. The problem is that I want to do this within javascript because I have a lot of tracks and I don’t want to create audio elements for each one.

Why doesn’t the first piece of code allow me to pause the audio later? Is there any way I can let it pause the audio later? If not, are there any alternatives that involve playing the audio from javascript by passing a parameter which is the song title? I don’t want to have to include the src in the html.

I suspect that jQuery might have an easy solution for this but form what I’ve researched I couldn’t find anything.

Answer by Starx

I just tested a snippet and it works as such

function music(song) {

    var audio = new Audio("audio/" + song + ".ogg");
    audio.play();
    setTimeout(function() { audio.pause(); }, 5000);

}
Read more
May 10, 2012

PHP Session Variable In JavaScript

Question by user1345650

How could I input php in this so when it has a correct password it stores the information as a cookie and then allow the deletion to it too.

  <SCRIPT language="JavaScript">
    <!--hide

    var password;

    var pass1="password";

    password=prompt('Please enter your password to view this page!',' ');

    if (password==pass1){
      alert('Password Correct! Click OK to enter!');}
    else
       {
        window.location="//Some Location//";
        }

    //-->
    </SCRIPT>

Answer by Starx

If its simple enough (As per the title)

var varname = '<?php echo $_SESSION["variable_name"]; ?>';

But you have to seriously consider your logic. You are checking for authentication on javascript, which is going to be dumbest move in a web application.

The password is totally exposed, and any one can view them or turn off the javascript as a whole, then your whole site becomes vulnerable.


My suggestion is an AJAX request to a PHP page which separately checks and verifies the password and then returns message to the Javascript.

Read more
May 9, 2012

copy() not working from url to folder in php

Question by Jay66online

I am trying to copy file from a url to a folder in my system using php

<?php $image = "http://l.yimg.com/t/frontpage/10-facts-slideshow-080512-630-01.jpg";
if (!copy($image, "localfolder/mainPic1.png")) {
echo "FAILED";
}else{echo "DONE";}

it always end up with “Failed”

  • All permissions are set to the localfolder

  • i checked the phpinfo and found that allow_url_fopen =Off

as it is a shared server i do not have any control over the php settings . please can you suggest an alternative.

Thanks,
Jay

Answer by Michael Berkowski

If allow_url_fopen is off and you cannot enable it, you will need to use curl to retrieve the file and save it locally.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://l.yimg.com/t/frontpage/10-facts-slideshow-080512-630-01.jpg");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$imgdata = curl_exec($ch);

// Save to disk
file_put_contents("localfolder/mainPic1.png", $imgdata);

Answer by Starx

Yes, allow_url_fopen have to ON for this.

allow_url_fopen = On

Even if you are allowed to modify php.ini on your shared server. Create a php.ini and keep the value allow_url_fopen = On in the root folder. It generally overrides the default settings.

Read more

PHP OOP: Job of Authenticator Class to retrieve current user via session?

Question by christian

I’m in the process of reorganizing an application.

At the start of my application I need an object to be initialized to represent the current user. I am planning an authentication class to handle logging in and logging out, and I am wondering if the initial session variable check for user id and database retrieval would be appropriate for this class as well or if there is a standard protocol?

Thanks

Answer by Starx

Well, Of Course. Checking the session variables for user id at first is the right thing to do.

No matter what kind of authentication use, at a point you have to check if someone is already logged in or not. It is not even that complicated. For the simplest of use:

if(isset($_SESSION['logged_status']) && $_SESSION['logged_status'] ==1) {
    $this -> logged = true;
}

However, the database retrieval part as a session variable is not as secured as you want it to be. Although, caches records can be stored in the session without any risk.

Read more
...

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