<?php
error_reporting(0);
session_start();
function code($no_of_char)
{
$code='';
$possible_char="0123456789";
while($no_of_char>0)
{
$code.=substr($possible_char, rand(0, strlen($possible_char)-1), 1);
$no_of_char--;
}
return $code;
}
function sendSms($msg, $to)
{
$to=trim($to);
$m.=urlencode($msg);
$smsurl="http://bhashsms.com/api/sendmsg.php?user=*****&pass=*****&sender=******&phone=$to&text=$m&priority=ndnd&stype=normal";
$return = exec($smsurl);
return $return;
}
?>
print_r($smsurl) is showing absolutely right command which i want but doesn't executing exec($smsurl)
i m not familiar with exec() function.
Thanks in advance.
exec is used for executing an external program but accessing some webpage/api from a web url is not a valid use case for exec. Try this if you want to get data from an Url.
how to call url of any other website in php
Related
Is there any way I can pass parameters (like Query string in URL, or URL parameters) to a PHP file which is being run via CLI? I need this for some PHP cron jobs which need input from parameters. For example:
$ php /home/abc/www/myphp.php?param1=abc
There are two special variables in every command line interface argc and argv.
argv - array of arguments passed to the script.
argc - the number of command line parameters passed to the script (if run on the command line).
Make script cli.php
<?php
print_r($_SERVER['argv']);
and call it with argument:
$ php cli.php argument1=1
You should get the output looking like:
Array
(
[0] => cli.php
[1] => argument1=1
)
Source: http://www.php.net/manual/en/reserved.variables.server.php
If you are still so demanding to have a single point entry and to be able to process the url query as $_GET make your script act like a router by adding a switch:
if (PHP_SAPI === 'cli')
{
// ... BUILD $_GET array from argv[0]
}
But then - it violates SRP - Single Responsibility Principle! Having that in mind if you're still so demanding to make it work like you stated in the question you can do it like:
if (PHP_SAPI === 'cli')
{
/** ... BUILD from argv[0], by parsing the query string, a new array and
* name it $data or at will
*/
}
else
{
// ... BUILD new $data array from $_GET array
}
After that convert the code to use $data array instead of $_GET
...and have a nice day!
If the underlying code absolutely requires $_GET (and does not rely on other HTTP features) you can write a simple wrapper that abuses the fact that isn't a read-only superglobal:
<?php
// Untested (tweak to your own needs)
foreach($argv as $i){
list($k, $v) = explode('=', $i, 2);
$_GET[$k] = $v;
}
require_once('/home/abc/www/myphp.php');
... and then schedule your proxy instead:
php /path/to/wrapper.php param1=abc
Here's an extracted/rewritten class from my CLI Application library using $_SERVER['argv'] in the same form that linux runs commands (foo.sh --param "value" --marap):
<?php
class ArgumentScanner {
private static $instance;
private $arguments;
public static function get() {
if (empty(self::$instance)) {
self::$instance = new ArgumentScanner();
}
return self::$instance;
}
public function __construct() {
$this->arguments = $this->parseArguments($_SERVER['argv']);
}
public function __isset($argument) {
return isset($this->arguments[$argument]);
}
public function __get($argument) {
return (isset($this->arguments[$argument]) ? $this->arguments[$argument] : null);
}
/**
* Is used to parse the contents of $_SERVER['argv']
* #param array $argumentsRaw The arguments from $_SERVER['argv']
* #return stdClass An object of properties in key-value pairs
*/
private function parseArguments($argumentsRaw) {
$argumentBuffer = '';
foreach ($argumentsRaw as $argument) {
if ($argument[0] == '-') {
$argumentBuffer = substr($argument, ($argument[1] == '-' ? 2 : 1));
$equalSign = strpos($argumentBuffer, '=');
if ($equalSign !== false) {
$argumentKey = substr($argumentBuffer, 0, $equalSign);
$argumentsParsed[$argumentKey] = substr($argumentBuffer, $equalSign + 1);
$argumentBuffer = '';
} else {
$argumentKey = $argumentBuffer;
$argumentsParsed[$argumentKey] = '';
}
} else {
if ($argumentBuffer != '') {
$argumentKey = $argumentBuffer;
$argumentsParsed[$argumentKey] = $argument;
$argumentBuffer = '';
}
}
}
return (object)$argumentsParsed;
}
}
?>
Use:
<?php
$argumentScanner = ArgumentScanner::get();
if (isset($argumentScanner->reset)) {
echo '--reset was passed!';
}
if (isset($argumentScanner->test)) {
echo '--test was passed as ' . $argumentScanner->test . '!';
}
if (isset($argumentScanner->foo)) {
echo '--foo was passed as ' . $argumentScanner->foo . '!';
}
if (isset($argumentScanner->bar)) {
echo '--bar was passed as ' . $argumentScanner->bar . '!';
}
?>
php script.php --foo "bar" --reset -test="hey you!"
Output:
--reset was passed!
--test was passed as hey you!
--foo was passed as bar!
Best solution there would be to refactor and abstract away the business logic, retain the original script as a wrapper for it. Then add a CLI script to wrap the same business logic for the CLI.
That way, you can use the normal CLI parameter handling: http://www.php.net/manual/en/reserved.variables.argv.php
I needed to do the same thing, pass query parameters to a php script to run as a cron job. The script was from a third party and I didn't want to modify or write a new script. The solution was to place the query string parameters in single quotes and replace the question mark with an ampersand. In my case, I pass three parameters.
php /home/abc/www/myphp.php '¶m1=abc¶m2=def¶m3=123'
I found the solution in this post, tried it and it works fine for me.
if (PHP_SAPI === 'cli')
{
parse_str(implode('&', array_slice($argv, 1)), $_GET);
}
This is solution that I use, if running via cli, put vars and values in $_GET,
seems that is working for simple tasks , not sure if work with php getopt etc
try wget and output to null
wget http://localhost/myphp.php?param1=abc -o /dev/null
I am using xmlprc server in codeignter for web services . the flow of my application is that i need to pass parameters to the xmlrpc server method which then should invoke another controller class method which would set the parameters in a js function and that js method is invoked concurrently .
The problem i am facing is in calling the controller class method from the xmlrpc server method and getting the response to the server parent method which could then be fetched using xmlhttprequest.
my xmlrpc server method is:
function update_p($request) {
$parameters = $request->output_parameters();
$this->session->set_userdata(array("portfolio" =>$parameters['0']["portfolio"]));
$this->session->set_userdata(array("filter" =>$parameters['0']["filter"]));
$url = base_url("ControllerClass/update_p?".$parameters['0']["portfolio"].'&'.$parameters['0']["filter"]);
header("Location: $url");
$xml_rpc_rows=array("portfolio"=>$parameters['0']["portfolio"],"filter"=>$parameters['0']["filter"]);
$response = array(
$xml_rpc_rows,
'struct');
$this->xmlrpc->send_response($response);
}
Controller Class method:
public function update_p() {
$loginid = $this->session->userdata('loginid');
if(!isset($loginid)){
die;
}
error_reporting(E_ERROR);
if (time()>$this->session->userdata('expire')) { redirect("/dashboard/logout?expired=Y","location",401); die; }
$out='';
$request="USER ".$loginid.($this->session->userdata('isMobile')?"#mobile":"")."\n";
if(isset($_GET["portfolio"])) {
$portfolio=trim($_GET["portfolio"]);
$request.='ECHO "LISTP":'."\nLISTP0 #".$portfolio;
if(isset($_GET["filter"])) {
$filter=trim($_GET["filter"]);
$request.=" -".$filter;
}
if(isset($_GET["sort"])) {
$sort=trim($_GET["sort"]);
if ($sort>=1024) $request.=" -s".($sort&1023);
else $request.=" -S".$sort;
}
$ph = isset($_GET["first"]);
if ($ph) {
$this->load->model('Model');
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','listp');
$request.=" ".$resultArray[0]['listp'];
}
$request.="\nECHO ,\n";
if(isset($_GET["watch"])) {
$portfolio=trim($_GET["watch"]);
if ($ph)
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','watch');
$request.='ECHO "watchl":'."\nLISTP1 #".$portfolio." -WL ".($ph?$resultArray[0]['watch']:"")."\n";
$request.='ECHO ,"watchs":'."\nLISTP1 #".$portfolio." -WS\nECHO ,\n";
}
}
$request.="RISk\nECHO ,\nPnL\n";
if ($result=$this->getData($request."BYE\n")) {
if (result!='') $out=$result."\n";
}
ob_start('ob_gzhandler');
echo "{".$out."}";
ob_end_flush();
}
I can not figure out how to get the controller method result in the server method anyone who can shed some light on this would be much appreciated .
Thankyou.
Your controller method is expecting to output the result as an echo statement, which goes to the browser, rather than to return it in a variable. This means your server function is having to try to capture the output of that controller method. That setup is much more awkward and prone to error.
Unless you also need to access your update_p method directly from a browser you should change your Controller to simply return the output which really means this controller is more of a library and should probably go in the libraries folder. You will need to change your controller code a bit so that instead of grabbing the parameters from $_GET you are getting them as arguments, which in CodeIgniter is what you should be doing anyway.
So from the end of update_p just do this instead of your echo:
return "{".$out."}";
Then in your xmlrpc server do this:
$controller = new ControllerClass();
$result = $controller->update_p($parameters['0']["portfolio"], $parameters['0']["filter"]);
Then do whatever you want with your $result.
I am new to php, Please give me a help if anyone know how to execute an external JavaScript function from a function in another PHP file. (or using Ajax).
In my code (see the comment):
In index.php->
<script type="text/javascript">
function OnUnityReady()
{
u.getUnity().SendMessage("test", "SubmitInputValue", "name");
}
</script>
In chatApp.php ->
<?php
class pfcCommand
{
function write($chan, $nick, $cmd, $param)
{
$data .= $nick."\t";
$data .= $cmd."\t";
$data .= $param;
.
.
$this->setMeta("channelid-to-msg", $this->encode($chan), $msgid, $data);
//FROM HERE, I NEED TO EXECUTE OnUnityReady() FUNCTION in index.html
//IN EVERY TIME WHEN EXECUTE THIS write FUNCTION
return $msgid;
}
}
?>
You cannot execute a javascript function from within a php script. Especially since javascript is parsed by your browser, using file_get_contents() or cURL wouldn't work. Find a way to replicate the JavaScript function in PHP :/
I have a php script the I often run using CLI (regular ssh terminal).
<?php
class foo {
public function __construct() {
echo("Hello world");
}
}
// script starts here...
$bar = new foo();
?>
When I run the code using php filename.php I get the Hello world stagnant as expected. Problem is that when i include the file from other php file I get the same thing (which I don't want).
How can I prevent code from running when file include but still use it as a CLI script?
You can test if $argv[0] == __FILE__ to see if the file called form the command line is the same as the included file.
class foo {
public function __construct() {
// Output Hello World if this file was called directly from the command line
// Edit: Probably need to use realpath() here as well..
if (isset($argv) && realpath($argv[0]) == __FILE__) {
echo("Hello world");
}
}
}
you can use php function get_included_files and check if your file is in array(using in_array)
http://php.net/manual/en/function.get-included-files.php
I hope this helps you.
You should check that you are BOTH running in the CLI environment AND NOT "included". See my re-write of your sample below:
<?php
class foo {
public function __construct() {
echo("Hello world");
}
}
// script starts here...
if (substr(php_sapi_name(), 0, 3) == 'cli'
&& basename($argv[0]) == basename(__FILE__) ) {
// this code will execute ONLY if the run from the CLI
// AND this file was not "included"
$bar = new foo();
}
?>
Is there a way to check in a php script if exec() is enabled or disabled on a server?
This will check if the function actually works (permissions, rights, etc):
if(#exec('echo EXEC') == 'EXEC'){
echo 'exec works';
}
if(function_exists('exec')) {
echo "exec is enabled";
}
ini_get('disable_functions')
What you actually want to do is use ini_get('disable_functions') to find out if it is available to you:
<?php
function exec_enabled() {
$disabled = explode(',', ini_get('disable_functions'));
return !in_array('exec', $disabled);
}
?>
Answered on stackoverflow here: Check if "exec" is disabled, Which actually seems to come from the PHP Man page: http://php.net/manual/en/function.exec.php#97187
Path
If the above returns true (you can use exec()), but PHP can still not trigger the script there is a good chance that you have a path issue for that script, test this by doing:
print exec('which bash');
and then try
print exec('which ogr2ogr');
This will check that exec is available and enabled BEFORE trying to run it. If you run exec() and the function does not exist or is disabled a warning will be generated. Depending on the server settings that may render to the browser and will almost-always write a line to a log file = performance hit.
// Exec function exists.
// Exec is not disabled.
// Safe Mode is not on.
$exec_enabled =
function_exists('exec') &&
!in_array('exec', array_map('trim', explode(', ', ini_get('disable_functions')))) &&
strtolower(ini_get('safe_mode')) != 1
;
if($exec_enabled) { exec('blah'); }
It's a bit tricky to find exec function available until unless checking all possibilities
1.function_exist('exec')
2.Scanning through ini_get('disabled_functions)
3.Checking safe_mode enabled
function is_shell_exec_available() {
if (in_array(strtolower(ini_get('safe_mode')), array('on', '1'), true) || (!function_exists('exec'))) {
return false;
}
$disabled_functions = explode(',', ini_get('disable_functions'));
$exec_enabled = !in_array('exec', $disabled_functions);
return ($exec_enabled) ? true : false;
}
This function never throws warnings unless ini_get function not disabled.
I am assuming that you are running this on a linux server.
You could test the exec function by running the following php script:
exec("whoami", $ret);
echo $ret[0];
This will return the command whoami.
If it errors out, it is because the exec function could not run.
Example:
if(strpos(ini_get('disable_functions'),'ini_set')===false)
#ini_set('display_errors',0);
This is some ugly code I made to detect if a function is enabled or not.
function is_enabled($f)
{
if($f=='ini_get')return#ini_get('a')===false;
return(($l=#ini_get('disable_functions'))===null||!is_callable($f)||!function_exists($f)||!in_array($f,array_map('trim',explode(',',$l)));
}
//Usage example:
print_r(is_enabled('str_split'));//true or null if ini_get() is disabled
(Based on other responses)
To check if exec exists and services are running:
function isRunning($serviceName)
{
return exec('pgrep '.$serviceName);
}
if (#exec('echo EXEC') == 'EXEC') {
$services = [
'mysql',
'nginx',
'redis',
'supervisord',
];
foreach ($services as $service) {
if (isRunning($service)) {
echo $service.' service is running.<br>';
} else {
echo $service.' service is down.<br>';
}
}
}
// mysql service is running.
// nginx service is running.
// redis service is running.
// supervisord service is down.
I would use this:
if (in_array('exec', preg_split('/\s*,\s*/', ini_get('disable_functions')) {
echo "exec is disabled";
}