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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

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