...

Hi! I’m Starx

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

How to execute php script from the command line?

Question by user1477886

I have a php script by the following address C:Denwerhomelocalhostwwwupload_record_test.php.
This script shows some text. But if I try to execute this script from the commmand line by command php C:Denwerhomelocalhostwwwupload_record_test, I get the html response with many errors and the message Call to undefined function curl_init(). The code:

<?php
    $_POST_DATA=array();
    $_POST_DATA['id']='AccountPagesView.a_book/45';
    $_POST_DATA['old_value']='1';
    $_POST_DATA['value']='2';
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://localhost/index.php/welcome/update_record');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST_DATA);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    $real_result=curl_exec($ch);
    $expected_result=array('result'=>'LOGIN', 'old_value'=>'1');
    $real_result=json_decode($real_result, true);
    if (count(array_intersect($real_result, $expected_result))==2)
    {
        echo "THE TEST HAS BEEN COMPLETED";
    }
    else 
    {
        echo "THE TEST HASN'T BEEN COMPLETED<br/>";
        echo "RESULT:";
        print_r($real_result);
        echo "<br/>EXPECTED RESULT:";
        print_r($expected_result);
    }
?>

Please, tell me, how can I execute this script from the command line and get only resulted text? Thanks in advance.

Answer by Starx

Check if curl is properly installed. If no check this instruction from php.net.

If Yes, then your curl module may not be enabled. You have to enable the curl module, to use curl methods. You can do this by editing php.ini and enabling the module.

On windows:

  • Open your php.ini file
  • Find a line with ;extension=php_curl.dll
  • Remove the ; infront and save the file
  • Restart apache server

It should work.

Update:

Sometimes safe_mode might be causing this problem. Go to ini file and disable the safe_mode

[php.ini]
safe_mode = Off
Read more

How do I use an IF statement in PHP to decide if I should show an image or not?

Question by Chris Danger Gillett

I’m setting up a weather page using the wunderground.com API. Anyway, I want to do the following:

Of the variable $weather is equal to Clear, I want to display an image.

I’ve tried this:

if ($weather=="Clear") echo <img src="http://example.org/clear.gif" alt="Clear"/> 

What do I need to do instead?

Answer by Ziumin

Try this

if ($weather=="Clear") echo '<img src="http://example.org/clear.gif" alt="Clear"/>';

Answer by Starx

The code you tried will render ERROR. You need to place the HTML text and any string within quotes, before you echo them.

if ($weather=="Clear") echo '<img src="http://example.org/clear.gif" alt="Clear"/>'

Remaining, there is nothing else to improve 🙂

Read more
June 29, 2012

awkward duplication in 2d array php

Question by shanahobo86

I merged two arrays together that both contained a string(url) and int(score). the following is a sample of the outome. Whenever a string is duplicated, i need to remove that string and its corresponding int. For example, on the 4th line (www.thebeatles.com/ – 30) should be removed. The 5th and 6th lines should also be removed as they appear already with a different score.

http://www.thebeatles.com/ - 55
http://en.wikipedia.org/wiki/The_Beatles - 49
http://www.beatlesstory.com/ - 45
http://www.thebeatles.com/ - 30
http://en.wikipedia.org/wiki/The_Beatles - 28
http://www.beatlesstory.com/ - 26
http://www.beatlesagain.com/ - 24
http://www.thebeatlesrockband.com/ - 23
http://www.last.fm/music/The+Beatles - 22
http://itunes.apple.com/us/artist/the-beatles/id136975 - 20
http://www.youtube.com/watch?v=U6tV11acSRk - 18
http://blekko.com/ws/http://www.thebeatles.com/+/seo - 17
http://www.adriandenning.co.uk/beatles.html - 16
http://www.npr.org/artists/15229570/the-beatles - 15
http://mp3.com/artist/The%2BBeatles - 14
http://www.beatles.com/ - 13
http://www.youtube.com/watch?v=TU7JjJJZi1Q - 12
http://www.guardian.co.uk/music/thebeatles - 11
http://www.cirquedusoleil.com/en/shows/love/default.aspx - 9
http://www.recordingthebeatles.com/ - 7
http://www.beatlesbible.com/ - 5

I’m new to PHP and my best efforts to get array_unique() to work have failed. Really appreciate some help guys!

Answer by Sven

Here is a function that merges two arrays and discards any duplications, hopes it helps:

        function merge_links($arr_l, $arr_r) {
            $new_links = array();
            $links = array_merge($arr_l, $arr_r); //the big list with every links


            foreach($links as $link) {
                $found = false; //did we found a duplicate?

                //check if we already have it
                foreach($new_links as $new_link) {
                    if($new_link['url'] == $link['url']) {
                        //duplicate
                        $found = true;

                        break;
                    }
                }

                //not found, so insert it
                if(!$found) {
                    $new_links[] = $link;
                }
            }

            return $new_links;
        }

        $arr1[0]['url'] = 'http://test.nl';
        $arr1[0]['score'] = 30;

        $arr1[1]['url'] = 'http://www.google.nl';
        $arr1[1]['score'] = 30;

        $arr2[0]['url'] = 'http://www.tres.nl';
        $arr2[0]['score'] = 30;

        $arr2[1]['url'] = 'http://test.nl';
        $arr2[1]['score'] = 30;

        print_r(merge_links($arr1, $arr2));

Answer by Starx

Well, even technically, those strings are not unique. i.e. They are completely different.

So, array_unique() will not give you the required output. One way of solving this issue is by defining a separate array and storing the URI and the number separately. A manageable form would be this.

array(

    array("http://www.thebeatles.com", 55),
    array("http://www.thebeatles.com", 30)

);
Read more

The animate callback function called immediately

Question by Ajax3.14

I am using the below line to blink a block. It works but the callback function incre() is called immediately and does not wait till blinking is over.

I need to call incre() only after the animate function blinks 2 seconds. What am I missing?

block.attr({ opacity: 0.3 }).animate({ opacity: 1 }, 2000,incre());

Answer by Starx

For what you are attempting fadeTo() sounds like a good choice

block.fadeTo(2000, 0.3, function() {
    block.fadeTo(2000, 1);
});

Demo

However, the error in your codes are:

  • the () (Brackets after the callback function name) i.e. incre()
  • opacity is a CSS property not an attribute. so user .css() to manipulate them

The correct codes are:

block
   .css({ opacity: 0.3 })
   .animate({ opacity: 1 }, 2000, incre);

Working Demo

Read more

Confuse about javascript callback function

Question by hh54188

I write two function, which callback will be invoke by the fn:

var callback = function (num) {
        return num + 1;    
}
var fn = function (callback) {
    callback();
}

fn(callback(5));

the firebug tell me: number is not a function ,I know the callback is execute immediately, how can I let it execute in the fn return the num in the fn function, the fn function is only allow the callback parameter

Answer by Elias Van Ootegem

Your example is a not great, seeing as there is no actual need for a second function. But this is what I’d do all the same:

function makeCallback(num)
{
    return function()
    {
        return num+1;
    }
}

fn = function (callback)
{
    callback.apply(this);
}

Seeing that a callback is generally called in an object context (DOM elements, when an event is handled etc) You might want to call the callback function, you passed as an argument to be called in the objects’ context.

Closures are a bit daunting and hard to fathom at first, but there are some great videos with Douglas Crockford on youtube on the matter, that really explain their workings well

Answer by Starx

It is happening due the parameter naming. The way you are using the parameters, makes a call to function called 6() which ends up being incorrect.

So, Use the following (IMO, this is what you are attempting)

var callback = function (num) {
        return num + 1;    
}
var fn = function (num) {
    callback(num);
}

fn(callback(5));

Demo

And so far for the attempt of your to create a callback function. You are only missing a return statement in the function see the result.

var callback = function (num) {
        return function(){
                return num + 1;
        };    
}
var fn = function (callback) {
    return callback();
}

console.log(fn(callback(5)));

Demo

Read more
June 28, 2012

add data dynamically from JSON array to HTML table using JQuery

Question by nag

php file:

   <?php
mysql_connect("127.0.0.1");
mysql_select_db("test"); 
$sql=mysql_query("select first,last,email,city from userdata"); 
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output)); 
   mysql_close(); 
?>

json output:

[{"first":"nag","last":"ch","email":"nag@gmail.com","city":"guntur"},{"first":"hari","last":"ch","email":"hari@gmail.com","city":"guntur"}] 

html code:

 <script>
    $(document).show(function(){
    });

        $("#userdata tbody").html("");
        $.getJSON("http://127.0.0.1/reg/userdata.php",function(data){
              $.each(data,function(i,user){
                    var tblRow =
                        "<tr>"
                          +"<td>"+user.first+"</td>"
                          +"<td>"+user.last+"</td>"
                          +"<td>"+user.email+"</td>"
                          +"<td>"+user.city+"</td>"
                        +"</tr>"
                    $(tblRow).appendTo("#userdata tbody");
                });
            }
        );
    </script>

i was displayed data from database using php in JSON format..i want to insert this data into table format in html page, i created table in html also..i tried using above script but it didn’t fetch any data..plz help me plz..

Answer by Starx

Your PHP is printing the array in an incremented format.

Make the following changes:

print(json_encode($row)); 

Next, there is no userdata in the output, so just use data.

Read more

php file cannot be fetched while running html file

Question by user1487874

I’ve a pre defined php file that has to be run when I run my HTML file on browser. It’s a part of learning AJAX from the book “Head Rush Ajax” and I downloaded those files from their website. But that PHP file’s not running and I can’t update my page. Please let me know if I’ve to install any other php related software to run the HTML file perfectly using PHP file.

Answer by Starx

PHP is a server side programming/scripting languages. Its needs a server capable of running PHP files. These servers include, Apacher web server, IIS and others too.

To test your application on your system during development, you can use many suites, like WAMPsever, LAMP Stack, XAMPP server, MAMP (Mac) and Local IIS too.

Read more

Why can't I animate a cloned element?

Question by markzzz

This is my code :

var newElement=$('.oggetto').eq(0).clone();
newElement.animate({ 'top': '2000px'}, 5000);

<div id="container">
    <div class="oggetto" style="left:0px;">&nbsp;</div>
    <div class="oggetto" style="left:50px;">&nbsp;</div>
</div> 

but seems that “.oggetto” won’t to move after the clone().

In fact, if I just write :

$('.oggetto').eq(0).animate({ 'top': '2000px'}, 5000);

it works as well. Where am I wrong?

Answer by Starx

Because, first the cloned element have to inserted into the DOM and then should be animated.

var newElement=$('.oggetto').eq(0).clone();
$("#container").append(newElement); //add the element 

//Now animate
newElement.animate({ 'top': '2000px'}, 5000);

Demo

Read more

random number generation without duplicates

Question by Zendie

I have to show some banners in a webpage.The number of banners will be with in 10 (max 10). I can set the number of banners and each banner folder in database. Banner images are stored in separate server folders based on category. Banners are showing in columns.

My code is,
Here, long1,long2,…long10 are directory names from database

 $array=array();
       for($n=1;$n<=$long;$n++)
       {
       $files = array();
       $dir=${'long'.$n};

               if(is_dir($dir))
              {
               $openDir = opendir($dir);
                       while (false !== ($file = readdir($openDir)))
                       {
                               if ($file != "." && $file != "..")
                               {
                                       $files[] = $file;
                               }
                       }
               closedir($openDir);
               }


mt_srand((double) microtime()*1000000);
 $randnum = mt_rand(0,(sizeof($files)-1));

 $arraycount=count($array);
for($index=0;$index<=$arraycount;$index++)
 {
 if(!in_array($array,$randnum))
     {
      $array[]=$randnum;
     }

 }

 $img = $dir."/".$files[$randnum];

  <input type="image" class="advt_image" src="<?=$img;?>" alt="" name=""/>
 }

ex: if there is 7 banner set in database, I have to show 7 banners from different or same folder.(some banners will be from same folder). I need to avoid the duplicate banners each time when I display a webpage.

I have assigned an array to store each random numbers. Do I need to change anything in code? any thought/idea?

Thanks!

Answer by restart

You can remove the image that is displayed from the $files array in the loop. this means you will have to check the length of the array in the loop as well. you could use array_diff for this.

$files = array(...); // this holds the files in the directory
$banners = array();  // this will hold the files to display
$count = 7;
for($i=0;$i<$count;$i++) {
    $c = mt_rand(0,count($files));
    $banners[] = $files[$c];
    $files = array_diff($files, array($files[$c]));
}

// now go ahead and display the $banners

Answer by Starx

A simple way to solve this problem would be create a array to hold the list of banner than before displaying them.

I didn’t read your code (Sorry), but here is a basic concept, with which this is possible.

$bannerList = array();

//Now, check if the list contains the banner before adding it
while($rows) { //your big list of banners

    if(!in_array($rows['bannerpath'])) {
        $bannerList[] = $rows['bannerpath'];
    }

}
Read more

Why isn't this image showing?

Question by sab

I made a header image, but for some reason I can’t get it to appear from CSS.

Here’s a screenshot:
enter image description here

The header is in the same image directory as the index.html file. The background image is appearing, but not this header. I typed the header twice in the HTML as a div to test it in two different spots to see if it is working, but for some reason it is not showing up, I don’t get it lol.

Thanks.

#header {
        background-image:url('../emailheader.png');
        width:100%;
        height:100%;
        background-repeat:no-repeat;

 } 

<div id="header"></div>

Here’s an example of it. But I am not sure why it doesn’t work.

Answer by Rab Nawaz

DEMO

You need provide height OR it will be dependent on the height of the inner content, which 0

 #header {
            background-image:url('http://i.imgur.com/ncTiy.png');
            width:100%;
            background-repeat:no-repeat;
            height:200px;
     } 

Answer by Starx

On seing the screenshot of the code. I found two problems.

  1. There is NO stylesheet attached on the first place
  2. header is used to identify two different elements. (Also mentioned by Blaster)

However, the main reason why it is not showing up in tinkerbin, is because the div neither contains any elements nor has a fixed dimensions. Check this update of your bin.

Read more
...

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