php exec() error - php

I'm having a little problem with the following:
When I execute this line:
echo exec(createDir($somevariable));
I get this error:
Warning: exec() [function.exec]: Cannot execute a blank command in /home/mydir/myfile.inc.php on line 32
Any ideas.
Thanks.

exec() expects a string argument, which it would pass on to your operating system to be executed. In other words, this is a portal to the server's command line.
I'm not sure what function createDir() is, but unless it's returning a valid command line string, it's probably failing because of that.
In Linux, you might want to do something like
exec('/usr/bin/mkdir '.$path);
...on the other hand, you should abstain from using exec() at all costs. What you can do here, instead, is take a look at mkdir()

With exec you can execute system calls like if you were using the command line. It hasn't to do anything with executing PHP functions.
To create a directory you could do the following:
exec( 'mkdir [NAME OF DIRECTORY]' );

I'd guess that your createDir() function doesn't return anything. Might also be worth checking that $somevariable is also set to something sensible

You're misunderstanding the purpose of exec(). If all you want to do is create a directory then you should use mkdir().

I think I've derived from other posts and comments what it is you actually want to do:
I think createDir() is a PHP function you've written yourself. It does more than just make a directory - it populates it, and that might take some time.
For some reason you believe that the next command gets run before createDir() has finished working, and you thought that by invoking createDir() using exec() you could avoid this.
Tell me in a comment if this is way out, and I'll delete this answer.
It's seems unlikely that createDir() really does keep working after it's returned (if it does, then we call that 'asynchronous'). It would require the programmer to go out of their way to make it asynchronous. So check that assumption.
Even so, exec() is not for invoking PHP functions. It is for invoking shell commands (the kind of thing you type in at a command prompt). As many of us have observed, it is to be avoided unless you're very careful - the risk being that you allow a user to execute arbitrary shell commands.
If you really do have to wait for an asynchronous function to complete, there are a couple of ways this can be done.
The first way requires that the asynchronous function has been written in an amenable manner. Some APIs let you start an asynchronous job, which will give you a 'handle', then do some other stuff, then get the return status from the handle. Something like:
handle = doThreadedJob(myParam);
# do other stuff
results = getResults(handle);
getResults would wait until the job finished.
The second way isn't as good, and can be used when the API is less helpful. Unfortunately, it's a matter of finding some clue that the job is finished, and polling until it is.
while( checkJobIsDone() == false ) {
sleep(some time interval);
}

I'm guessing createDir() doesn't have a return value.
Try exec("mkdir $somevariable");

Related

PHP CLI - Piping and prompting at the same time?

I have two php cli scripts. The first one pipes data into the second one.
I want the second one to prompt the user for a confirmation.
Is this possible?
I'm using wordpress' php-cli-tools, but my problem seem to be applicable to php in general, from what I see with my basic tests. (i.e. fgets(), readline, etc )
I can never get the prompt to work, since it looks like it will always read an EOT character from the previous input, even if I've already read it...
Then, later, when I prompt by using fwrite for output and then fgets() for input, nothing happens. Program is just waiting for something to happen... Not sure what...
If I use the library I get the error 'Caught ^D during input'. No luck with readline either...
Has anyone ever done this before?
Thank you so much!
The problem isn't really specific to PHP, it applies to any language. On Unix, you can read from /dev/tty instead of from standard input if you want to ignore input redirection and read from the terminal directly.
function prompt_user($prompt) {
$terminal = fopen("/dev/tty", "r+");
if ($terminal) {
fputs($terminal, $prompt);
return fgets($terminal);
}
}

How to pass variables between scripts running in parallel

I'm running IIS on a Windows Server w/PHP 5.3. I have two scripts; let's call them initiator.php and worker.php. A user calls initiator.php and in this script a variable is defined; let's call it $input. I would like to take this $input variable and pass it to worker.php like so:
$oShell = new COM('Wscript.Shell');
$oShell->Run("\"C:/Program Files (x86)/PHP/v5.3/php/worker.php -a $input",0,False);
In worker.php I have the following to pick up the $input variable passed from initiator.php.
$aCliOpts = getopt('a:');
$input_from_initiator = $aCliOpts['a'];
This works great. initiator.php's $input variable is successfully passed to worker.php which picks it up and initiator.php keeps chugging. However, worker.php then takes it's own $input_from_initiator variable, runs through some quick code of it's own and creates a third variable called $output_from_worker. It is this variable that I need initiator.php to read a little ways into it's processing. This is where I'm getting hung up.
I've tried passing the variable back to initiator.php from worker.php the same way it a variable as passed in the beginning and this did not work. I've also tried to use:
header('Location: initiator.php?var=value')
using HTTP GET params but to no avail.
My last resort is for worker.php to write this variable's value to disk then have initiator.php read from disk. I hate to do this due to the latent disk I/O. Speed is very important to this script.
Is there a way two PHP processes can pass variables between each other in memory?
Have a look at file_get_contents() http://php.net/file_get_contents, which you can pass a URL to. So you could use the Query String like:
$var = file_get_contents('http://site.tld/worker.php?input='.$input);
And in worker.php, simply echo your result.
It's a shame you're running on Windows, because the sys5 extension on *nix is marvelous!
You can always use files or a database etc for communication.
Thanks for the help although I ended up doing something a little different than my original question. I was trying to run different cURL requests. curl_multi_exec() ended up working great for me.

stop php execution instead of just a php script in codeigniter

I am using Codeigniter for a project and i usually call a series of models (let's say controllerA -> modelA -> modelB -> modelC) for some work. I want the php to stop executing when it reaches some exception where i invoke the exit() command. Now, if the command exit() is invoked in modelB, will it stop execution of only the script of modelB and continue executing rest of the modelA? Or will it stop the entire execution flow.
I really don't know how to put this question here. The question looks quite messy. Please let me know should i need to revise the question itself.
Yes, exit stops all script execution immediately, regardless where you call it.
The opposite is return which only stops execution of the current function (or current file when used at global level in an included file)
Read more here: https://stackoverflow.com/a/9853554/43959
Wherever you call the exit() function, all code will stop executing. This includes the other files because codeigniter just 'requires' them.
It stops the execution from that line.
I'm not sure if what you want, but maybe you can use exceptions to control PHP code execution.
http://es.php.net/manual/en/class.exception.php
Regards!
Like someone mentions above you should return from a function, or If your in a loop you could use continue or break

I want to execute more than one method at a time in php

Hi Please help me in executing more than one method at a time in PHP.
Below is example:
<?php
function writeName()
{
sleep(3);
echo "Kai Jim Refsnes";
}
function b(){
sleep(3);
echo"b";
}
b();
writeName());
?>
Here above program take 6 sec to execute.But I want to run my both method simultaneously so that program should execute with in 3 sec(Multi threading).
With common PHP its not possible, because PHP is executed sequential. You may have a look at a job-server like gearman, or you may try to use forks (pcntl_fork()). It's not multi-threading, because there is no shared memory.
Sorry, but multithreading is not supported in PHP.
But you could start a PHP script which can run in the background using exec(). Just make sure you redirect it's output elsewhere.
That should be the closest you can get to "multithreading" without additional tools. Here's what the manual says:
Note: If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

How to determine that a PHP script is in termination phase?

Is there any function / global variable in PHP that returns the current state of the script (something like runnning, terminating)?
Or is the only way to set this state by making use of register_shutdown_function()?
That function looks inflexible to me as an already registered shutdown functions can be overriden with it. And the shutdown function gets executed when a user aborts the connection, which is not what I'm looking for explicitly and I don't want to introduce too many constraints.
Are there any alternatives to register_shutdown_function() available? Or if not, how to deal with the shortcomings of that function?
UPDATE
Just to clarify: I'm not looking for connection state (e.g. connection_aborted()) but for the run state of the PHP script (running, terminating). Functions to find out more about the connection state I already know of, but how about the current state of the script? Has the script already been terminated and are objects (going to be) destroyed because of that?
UPDATE2
To clarify even more, I'm still not looking for connection state but for something comparable regarding the run-state. It should work in CLI as well which does not have any connection state as there is no TCP connection related to executing the code - to better illustrate what I'm looking for.
After reading a larger part of the PHP sourcecode I came to the conclusion that even if such state(s) exist on the level of experience, they do not really exist within the interpreter in form of a flag or variable.
The code about throwing Exceptions for example decides on various variables if that is possible or not.
The answer to the question is no therefore.
The best workaround I could find so far is to have a global variable for this which is set in a registered shutdown function. But a flag from PHP seems to be not really available.
<?php
register_shutdown_function(function() {$GLOBALS['shutdown_flag']=1;});
class Test {
public function __destruct() {
isset($GLOBALS['shutdown_flag'])
&& var_dump($GLOBALS['shutdown_flag'])
;
}
}
$test = new Test;
#EOF; Script ends here.
You are looking for:
Connection_aborted();
http://it.php.net/manual/en/function.connection-aborted.php
or
Connection_status();
http://it.php.net/manual/en/function.connection-status.php
Addendum
There can't be any Terminated status, because if it's terminated you can't check its status lol
I have never made (practical) use of it myself yet, but you might be able to make use of:
http://www.php.net/manual/en/function.register-tick-function.php
Using this means you can write a file or update a db or something while script is running... i.e. write a record session/some id and a timestamp id to a file or something and check for time between execution perhaps, you could say if it's not been updated in X seconds it's still running.
But as stated PHP is stateless so it's not a notion that PHP will be aware of.
Failing this, you could set a DB field in some way when a script starts/just before it 'ends', but would place a lot of overhead really.
Is there any function / global
variable in PHP that returns the
current state of the script (something
like runnning, terminating)?
No, PHP is stateless.

Categories