Getting console output in Laravel - php

I need to capture the output of a console command to be sent by email as well when requested. How can I do this?
How do I get the output generated from the following $this->info() calls?
$r = processData();
$this->info("\nSubmitted data:");
$this->info("SubmissionId: " . $r['submission_id']);
$this->info("Status: " . $r['status']);

Decided to just replace the $this->info() calls with a simple echo command and output buffer control. Looks good enough in the console and catches the data requested for emailing.
Example:
$r = processData();
if ($this->option('email-results'))
ob_start();
echo "\nSubmitted data:";
echo "\nSubmissionId: " . $r['submission_id'];
echo "\nStatus: " . $r['status'];
if ($this->option('email-results')) {
mail(
$this->option('email-results'),
'Results on ' . $start_time->toDateTimeString(),
ob_get_contents()
);
ob_end_flush();
}

an Artisan method could help:
\Illuminate\Support\Facades\Artisan::output()

Related

how to echo/print a nicely formatted array to the modx log?

I'm trying to figure out how to print/echo a formatted array to the modx error log. but print_r & pre tags do not work, if I use something like:
$log = "<pre>";
$log .= print_r($formdata);
$log .= "</pre>";
$this->modx->log(modX::LOG_LEVEL_ERROR, 'Form Data = ' . $log);
the result in the log is:
[2014-12-20 22:35:18] (ERROR # /index.php) Form Data = <pre>1</pre>
I have seen formatted arrays in the modx logs before, does anyone know how to do it?
in print_r() function add 2nd argument TRUE for return output value, see below sample code
$log = "<pre>";
$log .= print_r($formdata, true);
$log .= "</pre>";
$this->modx->log(modX::LOG_LEVEL_ERROR, 'Form Data = ' . $log);
You don't need the "<pre>" - "</pre>" tags, just
$modx->log(xPDO::LOG_LEVEL_ERROR, "Form Data = " . print_r($formdata,true),'','mySnippet');
will do the job, as of Revo version 2.3.3 at any rate.

Echo entire pre-compiled php page

For example if I had the script:
<?php
$page = "My Page";
echo "<title>" . $page . "</title>";
require_once('header.php');
require_once('content.php');
require_once('footer.php');
?>
Is there something I can add to the bottom of that page to show the entire pre-compiled php?
I want to literally echo the php code, and not compile it.
So in my browser I would see the following in code form...
// stuff from main php
$page = "My Page";
echo "<title>" . $page . "</title>";
// stuff from require_once('header.php');
$hello = "Welcome to my site!";
$name = "Bob";
echo "<div>" . $hello . " " . $name . "</div>";
// stuff from require_once('content.php');
echo "<div>Some kool content!!!!!</div>";
// stuff from require_once('footer.php');
$footerbox = "<div>Footer</div>";
echo $footerbox;
Is this possible?
There's no way to do it native to PHP, but you could try to hack it if you just wanted something extremely simplistic and non-robust:
<?php
$php = file_get_contents($_GET['file']);
$php = preg_replace_callback('#^\s*(?:require|include)(?:_once)?\((["\'])(?P<file>[^\\1]+)\\1\);\s*$#m', function($matches) {
$contents = file_get_contents($matches['file']);
return preg_replace('#<\?php(.+?)(?:\?>)?#s', '\\1', $contents);
}, $php);
echo '<pre>', htmlentities($php), '</pre>';
Notes:
Warning: Allowing arbitrary file parsing like I've done with the fist line is a security hole. Do your own authentication, path restricting, etc.
This is not recursive (though it wouldn't take much more work to make it so), so it won't handle included files within other included files and so on.
The regex matching is not robust, and very simplistic.
The included files are assumed to be statically named, within strings. Things like include($foo); or include(__DIR__ . '/foo.php'); will not work.
Disclaimer: Essentially, to do this right, you need to actually parse the PHP code. I only offer the above because it was an interesting problem and I was bored.
echo '$page = "My Page";';
echo 'echo "<title>" . $page . "</title>";';
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');
For clarity I'd put the title generation in it's own file, then just use a series of echo file_get_contents()...
echo file_get_contents('title.php');
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');

PHP : Second Function not being called

I am using PHP and want to run 2 functions, one after the other.
These functions are getallmydata() and createCSV()
The code below runs the first function fine but the second function createCSV() is not working. It seems like it is not being called properly.
Is there anything wrong with the structure of my code as both functions work correctly independently? I cannot work this out!
<?php
//run this function//
getallmydata();
//then run this function//
createCSV();
function getallmydata(){
require_once dirname(__FILE__).'/cm/csrest_general.php';
require_once dirname(__FILE__).'/cm/csrest_clients.php';
require_once dirname(__FILE__).'/cm/csrest_campaigns.php';
$api_key = 'MY API KEY';
$wrap = new CS_REST_General($api_key);
$result = $wrap->get_clients();
$Content = "";
if ($result->was_successful()) {
foreach ($result->response as $client) {
$client_wrapper = new CS_REST_Clients($client->ClientID, $api_key);
$client_details_result = $client_wrapper->get();
$campaigns_result = $client_wrapper->get_campaigns();
if ($client_details_result->was_successful()) {
/* This is where the client details will be */
$client_details = $client_details_result->response;
echo ('<pre>');
/*print out the company name*/
echo "Company Name = " . $client_details->BasicDetails->CompanyName . "<br/>";
/*print out the company markup*/
echo "Markup On Delivery = " . $client_details->BillingDetails->MarkupOnDelivery . "<br/>";
$count = 0;
if ($campaigns_result->was_successful()) {
/*print out the latest campaign name of the current campaign*/
foreach ($campaigns_result->response as $campaign_ob) {
echo 'Latest Campaign Name = ' . $campaign_ob->Name . '<br/>';
//echo 'Latest Subject = ' . $campaign_ob->Subject . '<br/>';
//echo 'Total Recipients = ' . $campaign_ob->TotalRecipients . '<br/>';
//echo 'Sent Date = ' . $campaign_ob->SentDate . '<br/>';
/*Set content for CSV File*/
//$Content .= "This is within the loop \n";
$count++;
if($count > 0) break;
}/*end loop*/
}/*end campaigns if statement*/
echo ('</pre>');
} else {
echo 'Failed with code '.$client_details_result->http_status_code."\n<br /><pre>";
var_dump($client_details_result->response);
}
}
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo ('</pre>');
}
} //end main function
/*create the downloadable csv file*/
function createCSV(){
$FileName = date("d-m-y") . '.csv';
# Titlte of the CSV
//$Content = "Company_Name Markup Campaign_Name Subject Recipients Date \n";
# fill data in the CSV
//$Content .= "\"John Doe\",\"New York, USA\",15,65465464 \n";
$Content .= "Testing The Function Works OK \n";
//$Content .= "This should be another line";
header('Content-Type: application/csv');
header("Content-length: " . filesize($NewFile));
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
}//end csv download function
/*end create downloadable .csv file */
?>
I think you should get the error: headers already sent. (you checked that the second function is called right? You can find it out by placing a echo on the first line of the function.)
You are trying to create a CSV page but you are parsing HTML in the first function, so the header is already sent to the client saying that it is a normal HTML page. Remove these echo's in the first function and it should work.
Quote of the PHP manual:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
More info about headers: PHP header
First think I would tell you is
1 you should first write function definition and then you should call a function
i.e
function getallmydata(){
// function code
}
function createCSV(){
// function code
}
getallmydata();
createCSV();
2 . The second thing is that check that is there any white space left in the code out side php code or any o/p that is sent as resonse as because when ever you user header() at that if any kind of content other than header() is sent as response then header() function fails. Try this things and check again.

PHP header function not triggering?

I'm getting some fairly odd behavior here... I noticed that only localhost, a header statement I have worked just fine, but when copied over (SAME EXACT CODE) to my live site, the header statement no longer triggers.
I added some echos to help debug. This if statement will only trigger if the URL variable id is NOT set. So with this same exact code on localhost, I never see these debug statements. On the live site, I do... which I shouldn't. I should get redirected instead. Anyone know why a header statement would be ignored?
if((!isset($_GET['id'])) && $rows != 0) {
$result = mysql_query('SELECT videoinfo FROM videos where game_id=' . $gameid . ' LIMIT 1');
$row = mysql_fetch_array($result);
$tubeID = $row['videoinfo'];
echo '<script type="text/javascript">';
echo 'window.location = "videos.php?id=' . $tubeID . '&awayid=' . $awayid . '&homeid=' . $homeid . '&date=' . $date . '&time=' . $time . '&gameid=' . $gameid . '&play=0"';
echo '</script>';
}
EDIT 4 people have told me already that I can't have any echo calls before my header function. This code WORKS on localhost and the header function DOES trigger. Regardless, REMOVING the echo statements DOES NOT fix it.
AFAIK
Can't send header() after some echo.
You cannot output ANYTHING before you call header(), i.e. echo etc...
I don't think you can have a header after any sort of output. I just came up with that.
You need to enable output buffering. This is probably enabled on your localhost but not on your live system (or the value on the live system is too small).
This will keep your output buffered, and then the Header will work fine.
Your debug statements are making the problem worse.
header statements will not work if there is any output before they are called. In this case, your echos are killing it. Also, make sure there is no other output before this is called (white space, HTML, etc.).
at start of script, add
ob_start();
and just before calling header();, use
ob_clean();
ob_clean();
header('Location: videos.php?id=' . $tubeID . '&awayid=' . $awayid . '&homeid=' . $homeid . '&date=' . $date . '&time=' . $time . '&gameid=' . $gameid . '&play=0');
Edit
Check to ensure that your files are encoded correctly. For instance, if you are encoding in UTF-8, make sure you encode in UTF-8 without BOM (Byte Order Mark).
How to check depends on what you use to edit and save your file. For instance, I use Notepad++ so I just go to the 'Encoding' menu and select 'Encode in UTF-8 without BOM' and then save the file.
function goto_url($url) {
// must not have output anything prior to calling this function
if (!headers_sent()){
header('Location: '.$url); exit;
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>'; exit;
};
};
http://www.w3schools.com/php/func_http_headers_sent.asp

How do I update an html table after each XML call to the server without refreshing the page?

I have a mySQL table loaded with 50 rows. Each row has the necessary information to process a credit card. When the user clicks on Process Credit Cards, query the table and display each row on the page using html. Once the data has been displayed on the page a scrip would begin to process each row through the merchant account and turn the corresponding row either red for decline or green for approve without refreshing the page after each transaction. I think I need to use AJAX or jQuery to make this happen but I'm not sure I'm headed in the right direction. Here is the script to process the transactions:
<?php
$request = new GatewayRequest();
$response = new GatewayResponse();
$service = new GatewayService();
$request->Set(GatewayRequest::MERCHANT_ID(), "111111111111111");
$request->Set(GatewayRequest::MERCHANT_PASSWORD(), "xxxxxxxxxxxx");
$time = time();
$request->Set(GatewayRequest::MERCHANT_CUSTOMER_ID(), $time . '.PHPTest');
$request->Set(GatewayRequest::MERCHANT_INVOICE_ID(), $time . '.SaleTest');
$request->Set(GatewayRequest::AMOUNT(), "9.99");
$request->Set(GatewayRequest::CARDNO(), "4111111111111111");
$request->Set(GatewayRequest::EXPIRE_MONTH(), "02");
$request->Set(GatewayRequest::EXPIRE_YEAR(), "2010");
$request->Set(GatewayRequest::CVV2(), "999");
$request->Set(GatewayRequest::CUSTOMER_FIRSTNAME(), "Joe");
$request->Set(GatewayRequest::CUSTOMER_LASTNAME(), "PHPTester");
$request->Set(GatewayRequest::EMAIL(), "phptest#fakedomain.com");
$request->Set(GatewayRequest::IPADDRESS(), $_SERVER['REMOTE_ADDR']);
$request->Set(GatewayRequest::BILLING_ADDRESS(), "123 Main St");
$request->Set(GatewayRequest::BILLING_CITY(), "Las Vegas");
$request->Set(GatewayRequest::BILLING_STATE(), "NV");
$request->Set(GatewayRequest::BILLING_ZIPCODE(), "89141");
$request->Set(GatewayRequest::BILLING_COUNTRY(), "US");
$request->Set(GatewayRequest::SCRUB(), "IGNORE");
$request->Set(GatewayRequest::CVV2_CHECK(), "IGNORE");
$request->Set(GatewayRequest::AVS_CHECK(), "IGNORE");
$service->SetTestMode(TRUE);
if ($service->PerformPurchase($request, $response)) {
print "Purchase succeeded\n";
print "Response Code: " .
$response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
print "Reasone Code: " .
$response->Get(GatewayResponse::REASON_CODE()) . "\n";
print "Auth No: " . $response->Get(GatewayResponse::AUTH_NO()) . "\n";
print "AVS: " . $response->Get(GatewayResponse::AVS_RESPONSE()) . "\n";
print "CVV2: " . $response->Get(GatewayResponse::CVV2_CODE()) . "\n";
print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
print "Account: " .
$response->Get(GatewayResponse::MERCHANT_ACCOUNT()) . "\n";
print "Scrub: " .
$response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
} else {
print "Purchase failed\n";
print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
print "Response Code: " .
$response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
print "Reasone Code: " .
$response->Get(GatewayResponse::REASON_CODE()) . "\n";
print "Exception: " .
$response->Get(GatewayResponse::EXCEPTION()) . "\n";
print "Scrub: " .
$response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
}
?>
Will this type of code work with AJAX or jQuery without being rewritten? Any help would be appreciated.
Anything can be made to work without being rewritten, but you've set yourself up for a lot of headaches there. You'll probably have much better luck (and save yourself tons of time) by formatting all those print statements into an array and JSON encoding it. Obviously javascript loves JSON.

Categories