Pausing PHP process via command line - php

I am running this via the command line. When the loop is running, is there any way I can pause the execution of the code? Ideal case would be that I could press a key to pause and then another key to resume. If I don't press the pause key then the loop continues until $i == 1000
<?php
echo "How long should the code sleep between increments?\n";
echo ">> ";
$sleep = trim(fgets(STDIN));
for ($i = 1; $i <= 1000; $i++) {
echo "$i\n";
sleep($sleep);
}
This is a heavily simplified example of my actual need for the code.

I don't sure my code is best solution or not but it work.
function checkResume()
{
$r = false;
while (!$r) {
if (fgets(STDIN) == "r") {
$r = true;
}
}
}
function checkPause()
{
$input = fgets(STDIN);
if (!empty($input) && $input == "p") {
return true;
}
return false;
}
echo "How long should the code sleep between increments?\n";
echo ">> ";
$sleep = trim(fgets(STDIN));
echo "\nStart ...\n";
stream_set_blocking(STDIN, false);
for ($i = 1; $i <= 1000; $i++) {
if (checkPause()) {
echo "wait for resume \n";
checkResume();
}
echo "$i\n";
sleep($sleep);
}
Hope this help.

Related

how to write prefixed unique coupon code in php

I am trying to write prefixed unique coupon code for get the chance to be a intern at one company. It went well so far, my code is generating 250st, 10 length of codes every time I refresh the page. However, I am issuing a problem with prefixed part. Normally coupon code is looking like this, just one example "1SC476XY3B" but I want every code to start "AB" and then 8 length of code so total will be 10. Can you help me guys? All help will be appreciated, thanks.
<?php
function unique_coupon_codes($number_of_codes,$exclude_codes_array='',$code_length = 10)
{
$characters = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
$unique_codes = array();
for($j = 1 ; $j <= $number_of_codes; $j++)
{
$code = "";
for ($i = 1; $i <= $code_length; $i++)
{
$code .= $characters[mt_rand(0, strlen($characters)-1)];
}
if(!in_array($code,$unique_codes))
{
if(is_array($exclude_codes_array))
{
if(!in_array($code,$exclude_codes_array))
{
$unique_codes[$j] = $code;
}
else
{
$j--;
}
}
else
{
$unique_codes[$j] = $code;
}
}
else
{
$j--;
}
}
return $unique_codes;
}
echo '<h1>Unique Coupon Codes</h1>';
echo '<pre>';
print_r(unique_coupon_codes(250,'',10));
echo '</pre>';
It needs a minor change while initializing $code variable. Change $code = ""; to $code = "AB"; And call unique_coupon_codes function as
print_r(unique_coupon_codes(250, '', 8));
Here generate a unique code of 8 digits as you already have prefix AB of length 2 characters.
How about something like this? :-)
function unique_coupon_codes($number_of_codes,$exclude_codes_array=[],$code_length = 10, $code_prefix="") {
$characters="0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
$unique_codes = array();
for($i=1;$i<=$number_of_codes;$i++) {
$code="";
for($o=1;$o<=$code_length;$o++) {
$code .= $characters[mt_rand(0, strlen($characters)-1)];
}
if(in_array($code, $unique_codes) || in_array($code, $exclude_codes_array)) {
$i--;
} else {
$unique_codes[$i] = $code_prefix.$code;
}
}
return $unique_codes;
}
echo '<h1>Unique Coupon Codes</h1>';
echo '<pre>';
print_r(unique_coupon_codes(250,'',8, 'AB'));
echo '</pre>';

Symfony Tasks wait for multiple tasks

I'm starting 10 processes asynchronously:
$procs = [];
for($i = 0; $i < 10; $i++) {
$proc = new Process('ls -lsa');
$proc->start();
$procs[$i] = $proc;
}
Now i want to wait asynchronous for every process to finish and print out state informations while waiting:
foreach($procs as $proc) {
$proc->wait(function ($type, $buffer) {
if (Process::ERR === $type) {
// Print out error ...
} else {
// Print out state informations ...
});
}
}
The Problem is at the wait function. It waits for the task to finish and then go on to the next tasks. But i want this to run asynchronous.
How can i do this?
Thanks !
As per the Symfony docs the wait method is blocking and therefore will wait until that process is finished before continuing.
If you don't want to wait you could refactor your code to use the run method:
for($i = 0; $i < 10; $i++) {
$process = new Process('ls -lsa');
$process->run(function ($type, $buffer) {
if (Process::ERR === $type) {
echo 'ERR > '.$buffer;
} else {
echo 'OUT > '.$buffer;
}
});
$procs[$i] = $proc;
}

PHP pthreads can't kill thread (& timeout realization)

I have an example code. What it does is visiting pages. I want to make timeout for thread execution and shut it down when it hangs too long. I thought that there is built-in methods to implement that. Also, i've tried to do it by my own with time() function. But there is another problem. At this point $workers[$i]->kill(); script hangs and kill() method returns false so i can't shutdown thread by force. What is happening and what am i doing wrong?
Thank you!
<?php
/**
* Author: Abu Ashraf Masnun
* URL: http://masnun.me
*/
//define("TMT",3);
class WorkerThreads extends Thread
{
private $workerId;
public function __construct($string)
{
$this->command_string = trim($string);
}
public function run()
{
echo $this->command_string." ".Thread::getCurrentThreadId()."\n";
//sleep(rand(0, 3));
$str = "C:\\Users\\Alex\\Desktop\\2web\\phantom\\phantomjs.exe C:\\Users\\Alex\\Desktop\\2web\\test.js ";
$url = $this->command_string;
$d = explode("://",$url);
$ex_str = $str." ".$url." > ".$d[1].".html";
//$ex_str = $str." ".$url;
//echo $ex_str;
//$ex_str = escapeshellarg($ex_str);
//echo $ex_str;
exec($ex_str, $out);
//print_r($out);
}
}
//$data = file('sites.txt');
$data_f = file('sites_x.txt');
print_r($data_f);
$data = array();
$data_size = count($data_f);
for($i = 0;$i<$data_size;$i++)
{
$info = explode(";",trim($data_f[$i]));
if($info[1] === 'y')
continue;
$data[] = $info[0];
}
print_r($data);
$data_size = count($data);
// Worker pool
$workers = [];
$t_count = 4;
$flag = 1;
$k = 0;
//echo "$data_size";
while($flag === 1)
{
/*
//echo "$k\n";
if($k >= $data_size)
{
//echo "111"; exit();
$flag = 0;
break 2;
}
*/
$c_w = count($workers);
if($c_w < $t_count)
{
for($i = $c_w; $i<$t_count - $c_w;$i++)
{
if($k >= $data_size)
{
$flag = 0;
break;
}
$workers[$i] = new WorkerThreads($data[$k]);
//echo $data[$k]."\n";
echo "worker $i started\n";
$workers[$i]->start();
$k++;
}
}
$c_w = count($workers);
for($i=0;$i<$c_w;$i++)
{
$workers[$i]->kill();
unset($workers[$i]);
echo "unset $i\n";
//var_dump($workers[$i]->isTerminated(), $workers[$i]->getTerminationInfo());
/*
if($workers[$i]->join())
{
//var_dump($workers[$i]->isTerminated(), $my->getTerminationInfo());
echo "joining $i\n";
unset($workers[$i]);
}
*/
}
}
?>
I ran into this problem today with pthreads 2.0.10.
After recompiling PHP from source to get ZTS support, I tried building pthreads (phpize, configure, make). Everything seemed OK until I ran make test. killed-info test failed after a 30 second timeout.
Solution for me was to compile the latest pthreads from the master branch on github.

PHP timeout error handling

I'm triyng to catch timeout error to output some clear text to the user (like "Sorry, timeout").
So why does this example:
function shutdown() {
$a=error_get_last();
if($a==null)
echo "No errors";
else
print_r($a);
}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
output no errors?? I'm confused about it.
Here this example looks helpful.
Thanks
Try not using sleep(), seems to work if the reason for timeout is real work:
Example
function isPrime($num) {
if($num == 1)
return false;
if($num == 2)
return true;
if($num % 2 == 0) {
return false;
}
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}
function shutdown()
{
$a=error_get_last();
if($a==null)
echo "No errors";
else
print_r($a);
}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
$ps = 0;
for ($i = 0; $i < 1000000; $i++) {
if (isPrime($i)){
$ps++;
}
}
echo $ps;

error in php program

I am just a beginner in PHP. I have tried to write a program for prime numbers, but the result is not correct. I couldn't find the error. How can I correct this? Here is my code:
<?php
$n=15;
for($i=2; $i<=$n; $i++)
{
echo "<br />";
for($j=2; $j<=$i-1; $j++)
{
$k=$i%$j;
if($k==0)
{
break;
}
else echo $i."is prime";
break;
}
}
?>
Try this:
<?php
$n=15;
for($i=2; $i<=$n; $i++)
{
$k = 1; //assume that it is prime
for($j=2; $j<$i; $j++) //if $i is 2, then it won't enter the loop as it will not match the condition ($j<$i)
{
$k=$i%$j;
if($k==0)
break; //if not prime, $k will be set as 0. So, break.
}
if($k!=0) // if $k <> 0, then it is prime
echo "<br />" . $i." is prime";
}
?>
Edit
Updated the code to take care of the "2"
Try this:(whitout using loop)
function is_prime($p) {
return ($p > 1) && (($p%2 >= 1) && ($p%3 >= 1) && ($p%5 >= 1)) || in_array($p, [2,3,5]);
}
echo is_prime(15);
You are breaking the loop the first time it's run by calling this basically:
if (something) {
break;
} else {
break;
}
it will break no matter what. you need to take out the last break.
Well, your code is kind of confusing to understand; at first glance it seems as if it's trying to determine primality by checking every divisor up to N, but you've got that outer-loop going on which I didn't see at first... Oh boy.
If you're just trying to figure out if some number N is prime, the following should work:
$n = 15
$prime = true;
for ($i = 2; $i < sqrt($n); $i++) {
if ($n % $i == 0) {
$prime = false;
break;
}
}
echo $n . " is " . ($prime ? "" : "not") . " prime.";
<?php
echo "TEST\r\n";
$n=15;
for($i=2; $i<=$n; $i++)
{
echo "I= $i \r\n";
for($j=2; $j<=$i-1; $j++)
{
$k = $i%$j;
if($k==0)
{
break;
} else {
echo $i."is prime \r\n";
}
break;
}
}
I think your secod for loop is incorrect.
for($i=2; $i<=$n; $i++) {
echo "<br />";
for($j=2; $j<=$i-1; $j++) {
...
The first value for $j is 2. And for the first time, the first value for $i is 2 again. Now, look at your second for loop code.
It will be like this at the first time:
for($j=2; $j<=2-1; $j++) ... // for($j=2; $j<=1; $j++)
And this condition is not valid at all: 2<=1

Categories