require_once function - php

I have this set of codes from JpGraph to help me with creating a bar chart.
<?php
require_once ('src/jpgraph.php');
require_once ('src/jpgraph_bar.php');
$datay=array(1992,1993,1995,1996,1997,1998,2001);
// Size of graph
$width=400;
$height=500;
// Set the basic parameters of the graph
$graph = new Graph($width,$height);
$graph->SetScale('textlin');
$top = 60;
$bottom = 30;
$left = 80;
$right = 30;
$graph->Set90AndMargin($left,$right,$top,$bottom);
// Nice shadow
$graph->SetShadow();
// Setup labels
$lbl = array("Andrew\nTait","Thomas\nAnderssen","Kevin\nSpacey","Nick\nDavidsson",
"David\nLindquist","Jason\nTait","Lorin\nPersson");
$graph->xaxis->SetTickLabels($lbl);
// Label align for X-axis
$graph->xaxis->SetLabelAlign('right','center','right');
// Label align for Y-axis
$graph->yaxis->SetLabelAlign('center','bottom');
// Titles
$graph->title->Set('Number of incidents');
// Create a bar pot
$bplot = new BarPlot($datay);
$bplot->SetFillColor('orange');
$bplot->SetWidth(0.5);
$bplot->SetYMin(1990);
?>
However, this will only work if I put it right at the top of my code. If I put it anywhere else, it will fail to display. Is there any way to overcome this so that if I put the code specifically at one place for example under it will appear there? Also, I'll be using some data from my own database as values for this graph.
Thank you.

JpGraph creates an image, which is displayed. You can't output text and images at the same time.

Requires/includes are resolved at runtime, not during parse. This allows them to be invoked dynamically. Therefore, they must be completed before any of their code can be referenced.
Alternative methods to look at are autoload, spl_autoload. This allows class files to be loaded on first reference.
However, from your comments, it appears that the issue is the usage of JpGraph requiring the sending of headers. You'll need to check studentcourse.php to see if any output is generated (including inadvertent whitespace).

Well, you can't escape the fact that when you call new Graph(), the class should already exist, so if you include the files after that line it'll never work.

This generates an image, right?
I would put this in a file by itself, and then on the page where you want the graph to show up, just do:
<img src="myGraph.php">

Related

How to dynmically draw picture in php gd

Hi I have searched the web for 2 days but did not accomplish what I am looking for.
I have an apache server which will be accessed by 146 students. the user picks an angle from dropdown lets say 45 degress, then user clicks CALCULATE button. Then user clicks DIAGRAM button to see how the sine graph looks like.
Works like charm when i write the image to a file e.g: imagepng($img,"diagram.png");
Now the problem is that the diagram.png will always get overwritten by the last user. So for example if another user logs in and calculates the Sin 135. Both users will see Sine 135 because filename is hardcoded since there is conflict of filename.
I have searched the web on how to create the image dynamically instead of writing to a file and then reading the file. I have come across the following but not working:
base64_encode and decode
What would I have to do to my code of imagepng(...., ...) mentioned above to make use of base64 so I can actually draw the picture of already processed data. Let assume if I comment out the imagepng(..) code, then what do I replace it with. I hope I don't have to change my code a whole lot.
Please help
thanks
Amit
The filename argument to imagepng is optional. From the manual:
filename
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
You would just need to send a png header at the top of the script and you would get the image as output for that script.
It's hard to tell without seeing you code how it is structured
but if once the user submits the form all you do is show the image by itself, then you can do something like this.
// make sure nothing else is out put before this otherwise it will stuff up the header
header('Content-Type: image/png);
imagepng($img);
If you embed the image into an html page as the result, then your best best would be to change the url of the image on the success page to something like this.
<img src="/path/to/file.php?deg=45" />
Then in the file.php
$deg = $_GET['deg'] + 0; // make sure it is a number
$img= function_render_graph($deg);
// make sure nothing else is out put before this otherwise it will stuff up the header
header('Content-Type: image/png);
imagepng($img);
By using a GET request, rather then a POST request then the image will likely be cached by the browser, so it doesn't need to be rendered each time. (Given that you have a drop list of angles, there must be a limited number of graphs that can actually be drawn)
Draw_Resultant_Prism_Graph (parameters)
{
$img = imagecreatetruecolor(800,750);
....
....
...
the following lines captures the data from output buffer and displays on same screen
***some version of IE have some issues mostly the dumb terminals where IE update is ADMIN
***restricted
ob_start();
header("Content-type: image/jpeg");
imagepng($img);
$output = ob_get_contents();
ob_end_clean();
imagedestroy($img);
echo img src="data:image/jpeg;base64,'.base64_encode($output).'"
user tags around img above and semicolon af
}

Zend pdf, resizing and placing and a pdfstring to a pdf

I have made good progress with producing pdf's with Zend PDF.
I am now integrating a web service into the application i am building. Everything has gone smoothly, but am now struggling to render a dynamically produced pdf that is to contain a pdf label returned via web service. Consider the following :
1.) An action to print the pdf is called.
2.) the pdf will contain n pages (n objects/items) of dynamic information about the item/shipment.
3.) each of the n shipments contains a shipment number, that when passed as a parameter to a specific method of the web-service, returns a pdfstring (which i can save as pdf).
4.) i have to resize and add each label to the bottom of the appropriate page.
so far, i have been able to use an already saved pdf, and have managed to load the pdfstring thats returned from the web service, and "merge" it into a final pdf. this works fine. but i would actually like to do the following:
1.) start a new pdf and add all other content to it.
2.) make the SOAP call and extract the returned Pdf string.
i have already done that, and now i would like to :
3.) resize the "label"
4.) rotate it 90 degrees
5.) add it to the pdf thats being built. (not merge with an already existing pdf).
so if i :
$returnedFromWebServicePDF = Zend_Pdf::parse($pdfLabel, 1);
I am able to save it on its own or even merge it (via cloning see here) but would like to resize, rotate and the add it to the pdf im building.
could someone guide me in the right direction as im pretty stumped. if someone could simply show me how to add this to a dynamic document, that would suffice as an answer to this question.
thanks in advance
EDIT
My efforts this far have been fruitless. i am now trying to change major parts of the applications processes, in order to already have stored the pdf, before this action is called. which means i could merge a static pdf into a dynamically generated one. will keep this problem updated.
Just to clarify, your goal is to download a PDF created by the service, load it back into Zend_PDF and make a change to content which exists in the pdf.
Zend_PDF is good at adding content to an existing pdf but doesn't have the ability to change content already on the page.
It does let you add new content which layers on-top of existing content.
If you don't have control over the service, you can redact the content your trying to change with a shape filled with the background color and add a new text block over the shape.
We use something similar to make personalized certificates.
Its tricky getting it in just the right spot.
I use a grid overlay on the pdf to get my bearings on the pdf.
/**
* Creates a grid overlay on a pdf. Useful for positioning text on a page.
* #param integer intPage The page number to operate on.
* #param integer intInterval. Lines on the page will be drawn at this interval. Value is in points.
* #return boolean TRUE for success.
*/
public function addGridLines($intPage = 0, $intInterval = 25)
{
$this->objPdf->pages[$intPage]->saveGS();
$pageWidth = $this->objPdf->pages[$intPage]->getWidth();
$pageHeight = $this->objPdf->pages[$intPage]->getHeight();
$this->objPdf->pages[$intPage]->setStyle($this->arrStyles['defaultLine']);
$this->objPdf->pages[$intPage]->setStyle($this->arrStyles['defaultText']);
//draw lines across the page.
for($a = 0; $a < $pageHeight; $a+= $intInterval){
$x = 0;
$y = $a;
$this->objPdf->pages[$intPage]->drawLine($x, $y, $pageWidth, $y);
$this->objPdf->pages[$intPage]->drawText($a, $x, $y);
}
//Draw lines up the page.
for($a = 0; $a < $pageHeight; $a+= $intInterval){
$x = $a;
$y = 0;
$this->objPdf->pages[$intPage]->drawLine($x, $y, $x, $pageHeight);
$this->objPdf->pages[$intPage]->drawText($a, $x, $y);
}
$this->objPdf->pages[$intPage]->restoreGS();
return TRUE;
}
This method is in another object with pdf related methods, but you get the idea.
The 'objPdf' is a Zend_PDF object I'm working with.

How to add graph to website?

I'm a beginner here and need help. I have this code, which works and outputs a graph in my browser (if this is the only code in php file). I don't know how to add text below or above just like any other site. When I try, it returns my whole code in the browser. How do I go on about this?
<?php
// content="text/plain; charset=utf-8"
require_once ('jpgraph/src/jpgraph.php');
require_once ('jpgraph/src/jpgraph_line.php');
// Some data
$ydata = array(11,3,8,12,5,1,9,8,5,7);
// Create the graph. These two calls are always required
$graph = new Graph(350,250);
$graph->SetScale('textlin');
// Create the linear plot
$lineplot=new LinePlot($ydata);
$lineplot->SetColor('blue');
// Add the plot to the graph
$graph->Add($lineplot);
// Display the graph
$graph->Stroke();
?>
Thanks in advance!
What you need is quite simply:
<img src="graph.php">
Put that in a separate HTML file or PHP script. You cannot output the image and text in the same script / web page. It needs to be separated.
Don't worry about the .php extension for the image src= attribute. It will display despite the lack of .jpeg extension. (The Graph class already outputs the correct MIME type I assume.)
I'm a bit rusty on PHP, but I believe that all "require" are supposed to be made before any content is output. Otherwise, the normal HTML/XHTML syntax and formatting take precedence.
I haven't actually used this library, but I'm assuming the image is output directly to the browser. It's probably easiest to create a new HTML document (or whatever the rest of your site is powered by) and include this as an image, with the image's src being the name of this script.

How to make business card with fpdf or tcpdf or others? When i have a jpg background and text overlap requires?

I have a jpg image for the business card layout with dimensions: 9,8 cm/5,9 cm. I have to put it as background layout and on top of this layout i have to print name/address/telephone number email etc. And print it/save it as pdf for later use.
But problem is i cant make it work with FPDF or TCPDF. Any idea how can i prepare this? with FPDF or TCPDF?
Using TCPDF you can position elements absolutely as it were, so you could do something like
$pdf = new TCPDF('L', 'mm', 'A4'); //Or whatever your required settings are
//Basic setup
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->Image('src', x, y); //Where x and y are the offset (probably 0, 0)
$pdf->writeHTMLCell(w, h, x, y, 'html') //Again where x and y are offset
$pdf->Output('filename.pdf', 'D'); //To force download
The TCPDF online documentation isn't great, but the examples help a lot http://www.tcpdf.org/examples.php
You specifically asked about creating a business card sized document, so you should use:
//Sets document size to a 5.9cm x 9.8cm landscape oriented page
$pdf = new TCPDF('L', 'mm', array(59,98));
The documentation gives a list of pre-defined page sizes here: http://www.tcpdf.org/doc/classTCPDF.html#a087d4df77e60b7054e97804069ed32c5
The example n. 51 at http://www.tcpdf.org shows how to create a full page background.
Then, for the page format, check the source code documentation of the getPageSizeFromFormat() method (more than 300 page formats are already defined, including business cards).
To set the background on fpdf you have to call Image() as the first thing when setting up the Header() function in your class.
The way I normally do it is by extending Extend FPDF in my own class, i.e.:
require('path/to/fpdf.php);
class SomeClassName extends FPDF {
// add your instance variables if needed
....
function Header(){
//now call Image()
$this->Image(); //set up your background here
...
}
}
If you look at faqs in the fpdf.org site you will see (vague) instructions on how to do this.
There is a library which implements FPDF called FPDI. To create custom paper sizes, like business cards, which typically use CR80 with dimensions of 54mm x 86mm, you can directly add this size into the class constructor of fpdf.php at stdPageSizes as this: 'cr80'=>array(152.82,243.38). This entry already exists so just add this custom one. Your complete definition will be something like this:
$this->StdPageSizes = array('a3'=>array(841.89,1190.55), 'a4'=>array(595.28,841.89), 'a5'=>array(420.94,595.28), 'letter'=>array(612,792), 'legal'=>array(612,1008), 'cr80'=>array(152.82,243.38));
Your calls, if using FPDI, will now be something like this:
$pdf = new Fpdi();
$pdf->AddPage('L','cr80'); //note our custom name
Note that even though the right size of CR80 is 54x86mm, it seems that the right settings require that these values be multiplied by 2.83 - tested. I hope this helps in code shortenings and quick reuse.

Reuse PHP image randomizer

I wrote a simple image randomizer on PHP that picks a random image from a list using the rand() function. The code works perfectly, and a random image is generated when I include it on my html as a picture.
The problem comes when I try to include it twice in the same html. A random image WILL be generated and displayed for both times I included it, but it will be the same image. In other words, I get a repeated random image on my page.
An easy way to solve this is to simply copy the randomizer.php, give it a new name, and include both images in HTML. The reason I don't want to do this is because my final HTML will have about 25 pictures, and I simply feel like there should be a better way to do this. Keep in mind that I CANNOT add any PHP functions into my HTML, given that my files are hosted in different servers, and my HTML server does not support PHP.
If anyone know of a better fix other than creating 25 copies of my randomizer.php file (or creating 25 different files that include it), please let me know. I will most definitely appreciate your input!!
Thank you very, very much!!
Here's a snippet of the code:
if (count($fileList) > 0) {
do { //do-while loop will get a new random image until that image has not been used yet in this session
$imageNumber = rand( 0 , ( count($fileList) - 1) ); //get random image from fileList
$iterations++;
} while( !(empty($_SESSION['img' . $imageNumber])) && iterations < 200);
$_SESSION['img' . $imageNumber] = True; //this image number has been displayed
$_SESSION['shown']++; //increments the number of shown pictures in this signature
$img = $folder.$fileList[$imageNumber];
}
It may be that the browser thinks it is the same image and is caching, try setting the name of the image (emit a header with content-disposition/filename IIRC) and/or adding a unique tag to the end of the image name with a random string, ( e.g. image.jpg?e0.6613725793930488 )
My guess is that rand() either didn't reseed, or is seeded with the same value.
Have you considered calling srand() - or "the better random number generator" combination of mt_srand() and mt_rand()?

Categories