PHP : Second Function not being called - php

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.

Related

Check if background image is set

I'm working on a simple script - file input which will change the site's background to the given image. It works, but my problem starts when I refresh site - the background image disappears.
I was wondering how to set and check if the background was set, so it will be there as long since next file input ?
I was trying to do that with a constant but does not work, here is my code:
if (isset($_POST['submit_bgImg'])) {
$myTarget = 'img/' . basename($_FILES['bg_img']['name']);
if (move_uploaded_file($_FILES['bg_img']['tmp_name'], $myTarget)) {
print('<style> body {background-image:url(img/' . $myFile . ');}</style>');
define('MY_BG', $_FILES['bg_img']['name']);
}
}
if (defined('MY_BG')) {
print('<style> body {background-image:url(img/' . MY_BG . ');}</style>');
}
any help ?
If you want to keep it only for the user you must store MY_BG variable in Session or Cookies like :$_SESSION['my_bg'] = $_FILES['bg_img']['name'];
if you want to keep it forever you must store it on a file or a Database like MySQL
$conn = new MySQLi('host','user','password','database name');
$conn->query("INSERT INTO table VALUES ('" . $bg_name . "')");
Try out with echo in php instead of print.I recommended to you can use ajax.
if (isset($_POST['submit_bgImg'])) {
$myTarget = 'img/' . basename($_FILES['bg_img']['name']);
if (move_uploaded_file($_FILES['bg_img']['tmp_name'], $myTarget)) {
echo "<style> body {background-image:url(img/' . $myFile . ');}</style>";
define('MY_BG', $_FILES['bg_img']['name']);
}
}
if (defined('MY_BG')) {
echo "<style> body {background-image:url(img/' . MY_BG . ');}</style>";
}

What is causing my PHP page to render html tags as text (and what can I do to fix it)?

I have the following PHP code: When it is commented out (as it is now) from just after the comment // ... more stuff in here to the end of that comment block, my page renders html from that 2nd php block as expected as in this screenshot.
If I uncomment that block it renders like the screenshot after the code below which is not what I want (I want the rendered html as in the first screenshot). The only thing not showing in my comment block is a function call that curls a webpage, parses html with DomXNode types of things, and returns an array with 3 elements. How can I get the original rendering of the html back and what am I possibly doing that is ruining that for me? I tried echo instead of print and that makes no difference.
I honestly did search for the answer on here and found lots of pages describing how do do just the opposite of what I want so please be gentle with me. I was surprised that I couldn't find a similar question and I know there has to be an easy answer here. Thanks!
<?php
// ... more stuff in here
/*
include("../../includes/curl_fx.php");
if ($doAppend === "parcel") {
$lines = explode(PHP_EOL, $Data);
foreach($lines as $line) {
if(strpos($line, "http") > 0) {
$start = stripos(strval($line), "http");
$fullLength = strlen($line);
$urlLength = ($fullLength - $start);
$fullUrl = substr($line, $start, $urlLength);
$arraySDAT = getSDAT($fullUrl);
$line .= ", " . $arraySDAT[0] . ", " . $arraySDAT[1] . ", " . $arraySDAT[2] . "\n";
fwrite($Handle, $line);
}
}
}
*/
?>
<?php
if ($DataAdded === true) {
print "<h2>YourFile.txt</h2>Data has been added.<br />Close this window or tab to return to the web map.<br />";
} else {
print "Data may not have been added. Check the file.<br />";
}
fclose($Handle);
print $doAppendAnswer;
print "<br />";
?>
EDIT: Here is the function.
<?php
function getSDAT ($fullUrl="") {
$ch = curl_init($fullUrl);
if (! $ch) {
die( "Cannot allocate a new PHP-CURL handle" );
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
header("Content-type: text");
curl_close($ch);
libxml_use_internal_errors(true);
libxml_clear_errors();
$doc = DOMDocument::loadHTML($data);
$xpath = new DOMXPath($doc);
$ownName1query = '//table/tr/td/span[#id="MainContent_MainContent_cphMainContentArea_ucSearchType_wzrdRealPropertySearch_ucDetailsSearch_dlstDetaisSearch_lblOwnerName_0"][#class="text"]';
$ownName2query = '//table/tr/td/span[#id="MainContent_MainContent_cphMainContentArea_ucSearchType_wzrdRealPropertySearch_ucDetailsSearch_dlstDetaisSearch_lblOwnerName2_0"][#class="text"]';
$ownAddrquery = '//table/tr/td/span[#id="MainContent_MainContent_cphMainContentArea_ucSearchType_wzrdRealPropertySearch_ucDetailsSearch_dlstDetaisSearch_lblMailingAddress_0"][#class="text"]';
$entries = $xpath->query($ownName1query);
foreach($entries as $entry) {
$ownname1 = $entry->nodeValue;
}
$entries = $xpath->query($ownName2query);
foreach($entries as $entry) {
$ownname2 = $entry->nodeValue;
}
$entries = $xpath->query($ownAddrquery);
$pattern = '#<br\s*/?>#i';
$replacement = ", ";
$i=0;
foreach($entries as $entry) {
$ownAddr = $entry->nodeValue;
if(!$entry->childNodes == 0) {
$ownAddr = $doc->saveHTML($entry);
}
$ownAddr2 = preg_replace($pattern, $replacement, $ownAddr, 15, $count); // replace <br/> with a comma
$ownAddr3 = strip_tags($ownAddr2);
}
return array($ownname1, $ownname2, $ownAddr3);
}
Your problem is:
header("Content-type: text");
Just remove that. Why is it there?
As mentioned, it's the header which is causing you a problem. You see the header decides the type of content that the current document should have or how the current document should behave - an information that is usually found in the < head >...< /head > part of an HTML. You can use it for declaring the content type, controlling the cache, redirecting, and etc.
When you use header("Content-type: text"), you are deciding that the content of the current document "yourdocument.php" would be a text instead of the default which is HTML.
header("Content-type: text/html");
echo "<html>This would make mypage.php behave as an HTML</html>";
// This is usually unnecessary since text/html is already the default header
header("Content-type: text/javascript");
echo "this would make mypage.php behave as a javascript";
header("Content-type: text/css");
echo "this would make mypage.php behave as a CSS";
header('Content-type: image/jpeg');
readfile("source/to/my/file.jpg");
// this would make mypage.php display file.jpg and act as a jpg
header('Content-type: image/png');
readfile("source/to/my/file.png");
// this would make mypage.php display file.png and act as a png
header('Content-type: image/gif');
readfile("source/to/my/file.gif");
// this would make mypage.php display file.gif and act as a gif
header('Content-type: image/x-icon');
readfile("source/to/my/file.ico");
// this would make mypage.php display file.ico and act as an icon
header('Content-type: image/x-win-bitmap');
readfile("source/to/my/file.cur");
// this would make mypage.php display file.cur and act as a cursor

php barcode - display multiple barcode in single page

I created a php page that print the barcode. Just to view it before i print it on an A4. Still in testing phase. The codes are as below.
<?php
include('include/conn.php');
include('include/Barcode39.php');
$sql="select * from barcode where b_status = 'NOT-PRINTED'";
$result=mysqli_query($conn,$sql);
echo mysqli_num_rows($result);
$i=0;
while($row=mysqli_fetch_assoc($result)){
$acc_no = $row["b_acc_no_code"];
$bc = new Barcode39($row["b_acc_no_code"]);
echo $bc->draw();
$bc->draw($acc_no.$i.".jpg");
echo '<br /><br />';
$i++;
}
?>
Without the while loop, it can be printed, but only one barcode. How to make it generate, for example in the database have 5 values, it will print 5 barcode in the same page. Thanks in advance
Try to use another bar code source. Because It is generate only one bar code per page. Can't able to create multiple bar code per page.
I know this is an older post but comes up in searches so is probably worth replying to.
I have successfully used the Barcode39 to display multiple barcodes. The trick is to get base64 data from the class and then display the barcodes in separate HTML tags.
The quickest way to do this is to add a $base64 parameter to the draw() method:
public function draw($filename = null, $base64 = false) {
Then, near the end of the draw() method, modify to buffer the imagegif() call and return the output in base64:
// check if writing image
if ($filename) {
imagegif($img, $filename);
}
// NEW: Return base 64 for the barcode image
else if ($base64) {
ob_start();
imagegif($img);
$image_data = ob_get_clean();
imagedestroy($img);
return base64_encode($image_data);
}
// display image
else {
header("Content-type: image/gif");
imagegif($img);
}
Finally, to display multiples from the calling procedure, construct the image HTML in the loop and display:
// assuming everything else has been set up, end with this...
$base64 = $barcode->draw('', true); // Note the second param is set for base64
$html = '';
for ($i = 0; $i < $numBarcodes; $i++) {
$html .= '<img src="data:image/gif;base64,'.$base64.'">';
}
die('<html><body>' . $html . '</body></html>');
I hope this helps anyone else facing this challenge.

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.

PHP POST data in ASCII instead of UTF8

I have got problem with coding after sending data by POST from form.
When I am using special polish characters like ą, ć, ę, ł, ń etc. I am getting ? instead of proper character. I am struggling with it already third day and cannot find the problem.
Website is using UTF8 and all files are in UTF8. The form is sending data using AJAX and getting response using output buffer (ob). When I am checking headers in Chrome everything is alright. So it looks like something is happening with jQuery/Ajax/ob?
My all functions which are used for jQuery/Ajax/ob:
jQuery:
function ajaxForm(oform,ni,wt,nhi) {
if (wt==''||wt==undefined) {
if (oform.id=='theLongForm') {
// time out based on the form id
wt=120000;
} else if (document.forms[oform.id].timeout) {
// use the specific time out setting
wt=document.forms[oform.id].timeout.value;
} else {
// default time out setting
wt=10000;
}
}
if (ni==''||ni==undefined) ni=false;
if (nhi==''||nhi==undefined) nhi=false;
if (ni!=true) showIndicator();
$('#'+oform.id).ajaxSubmit({
url: oform.action,
type: 'POST',
dataType: 'xml',
timeout: wt,
error: function(){
document.forms[oform.id].ajax.value='x';
$('#'+oform.id).submit();
},
success: function(xml){
if (processResult(xml)) {
if (nhi!=true) $("#indicator").hide(200);
}
}
});
return false
}
PHP:
function outputAjaxHeader() {
global $ajaxRequest,$doneAjaxHeader;
if ($ajaxRequest && !$doneAjaxHeader) {
// output ajax XML header
header('Content-type: text/xml; charset: utf-8');
print '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
print '<items>' . "\n";
$doneAjaxHeader = true;
}
}
function outputAjaxItemStart($elem,$option='general',$full=false) {
global $ajaxRequest;
if ($ajaxRequest) {
print "\t" . '<item>' . "\n";
print "\t\t" . '<name>'.($full?'':'#').$elem.'</name>' . "\n";
print "\t\t" . '<option>'.$option.'</option>' . "\n";
print "\t\t" . '<data><![CDATA[';
ob_start();
}
}
function outputAjaxItemEnd() {
global $ajaxRequest;
if ($ajaxRequest) {
$buffer = ob_get_contents();
ob_end_clean();
print $buffer;
print ']]>' . '</data>' . "\n";
print "\t" . '</item>' . "\n";
}
}

Categories