Session Upload Progress & Multiple files - php

I am using this function here:
http://www.php.net/manual/en/session.upload-progress.php
And here is my code for the progress uploading:
<?
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if(!empty($_SESSION[$key])) {
echo "<table width='400' style='font-family: Verdana; font-size: 12px;'>";
foreach($_SESSION[$key]['files'] as $f)
{
// Get percentage done
$current = $f["bytes_processed"];
$total = $f["content_length"];
if($current < $total) {
$done = ceil($current / $total * 100);
} else {
$done = 100;
}
echo " <tr>
<td colspan=2>{$f['name']}</td>
</tr>
<tr>
<td colspan=2><img src='uploading.gif' width='{$done}px' height='13px'></td>
</tr>
<tr>
<td>Started # ".date("H:m:s",$f['start_time'])."</td>
<td>{$done}%</td>
</tr>";
}
echo "</table>";
}
?>
The problem is that the individual files do not have a content_length variable. How can I work the progress for each file that is uploaded?

You can't, unless you're uploading a single file. $_SESSION[$key]['content_length'] is the total content length of the files that are being uploaded and the only indication of content length available. So you have two options: show a global progress of all files or limit the number of uploaded files to 1.
(Not sure if you are, but if you're willing to ditch this method you could opt for one of the numerous upload managers available. In the past I've used Fine Uploader with satisfaction.)

Related

If condition in mail body phpmailer

I am using Phpmailer and I am currently emailing the data from my database. However, I need to have a color coding depending on the chosen condition. For example, if the remarks is proceed, the data cell should be in green color and red if hold. Im not really sure how to apply if loop inside an echo. Please help
while ($rowwaf = mysqli_fetch_assoc($queryres)){
$mailbody = "
Good Day!<br><br>
Please see details below<br><br>
<strong>Details:</strong><br><br>
<table class=\"table\" cellpadding=\"5\" rules=\"all\" frame=\"box\" border=\"1\">
<tr><td class=\"data\"><strong>REQUEST DATE:</strong></td><td>".$rowwaf["req_date"]."</td></tr>
<tr><td class=\"data\"><strong>ISSUE ENCOUNTERED:</strong></td><td>".$rowwaf["issue"]."</td></tr>
<tr><td class=\"data\"><strong>URGENCY:</strong> </td><td>".$rowwaf["urgency"]."</td></tr>
<tr><td class=\"data\"><strong>REQUESTOR:</strong></td><td>".$rowwaf["requestor"]."</td></tr>
<tr><td class=\"data\"><strong>REMARKS:</strong></td>
-- if condition sample--
if {
$rowwaf["remarks"] == proceed
<td style="color: green">".$rowwaf["remarks"]."</td></tr>
}
else {
$rowwaf["remarks"] == hold
<td style="color: red">".$rowwaf["remarks"]."</td></tr>
}
";
You could just set a variable for your color(also the code you provided won't work):
<?php
if ($rowwaf['remarks'] === 'proceed') {
$color = 'green';
} elseif ($rowwaf['remarks'] === 'hold') {
$color = 'red';
}
?>
Then use the $color variable in your html
I'd also recommend to use heredoc syntax to create your body and use php variables to do something like :
$mailbody = <<<EOF
<td style="color: {$color}">{$rowwaf['remarks']}</td>
EOF;

generate an Excel file using PHP

I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
#Ranjit this is the PHP code that displays the table and generate the excel file
edit 1
<?php
$ch="";
if(isset($_POST['historique']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
?>
<table id="tab" border="1">
<tr>
<th><font color="red">Date</font></th>
<th><font color="red">Agent</font></th>
<th><font color="red">numéro</font></th>
</tr>
<?php
$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
while ($data = mssql_fetch_assoc($stmt))
{
?>
<tr>
<td><?php echo utf8_encode ($data['operationDate']);?></td>
<td><?php echo utf8_encode ($data['fullName']);?></td>
<td><?php echo utf8_encode ($data['number']);?></td>
</tr>
<?php
} }
?>
</table>
<?php
}
$output ='';
if(isset($_POST['excel']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$rq = "// my query
where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
$res = mssql_query($rq);
if(mssql_num_rows($res)>0)
{
$output.='<table border=1>
<tr>
<th>Date</th>
<th>Depanneur</th>
<th>numéro</th>
</tr>
';
while ($row=mssql_fetch_array($res))
{
$output .='
<tr>
<td>'.$row["operationDate"].'</td>
<td>'.$row["fullName"].'</td>
<td>'.$row["number"].'</td>
</tr>';
}
$output .='</table>';
header("Content-Type: application/xls;charset=UTF-8");
header("Content-Disposition: attachement; filename=file.xls");
echo $output;
//mssql_close($conn);
}}}
?>
You'll have to select the data manually then insert them into the excel sheet, there's php library called PHPEXCEL you can use it.
See this
http://www.c-sharpcorner.com/article/export-to-excel-in-php-with-my-sql/
There are some nice packages out there to generate excel files such as
Box Spout and PHP Spreadsheet.
The documentation of both packages is very clear any you will be generating excel files within minutes of browsing through documentation.
Yes,
It is possible. You can follow this
1) Connect to database:
2) Define a filename of excel
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields
Sources - http://www.anillabs.com/2010/03/how-to-create-excel-file-with-mysql-data-using-php-code/

php dynamically creating a file on form submit

would any one know how to automatically create a file through PHP so when the tag is clicked it also have the file right now it's only a path which is displayed through a loop. but when you click it there is no file, of course, long story short how can I also create a file too with a loop so all links have files created through fopen or something, just like all of them have paths generated.
<?php
function display_user_docs($doc_array) {
// set global variable, to test later if this is on the page
global $doc_table;
$doc_table = true;
?>
<br>
<form name="doc_table" action="delete_doc.php" method="post">
<table width="300" cellpadding="2" cellspacing="0">
<?php
$color = "#cccccc";
echo "<tr bgcolor=\"".$color."\"><td><strong>Documentations</strong></td>";
echo "<td><strong>Delete?</strong></td></tr>";
if ((is_array($doc_array)) && (count($doc_array) > 0)) {
foreach ($doc_array as $doc) {
if ($color == "#cccccc") {
$color = "#ffffff";
} else {
$color = "#cccccc";
}
echo "<tr bgcolor=\"".$color."\"><td><a class=\"all-doc-link\" href=\"".$doc.".php\">".htmlspecialchars($doc)."</a></td>
<td><input type=\"checkbox\" name=\"del_me[]\"
value=\"".$doc."\"></td>
</tr>";
}
} else {
echo "<tr><td>No documentation on record</td></tr>";
}
?>
</table>
</form>
<?php
}
?>
You can use file_put_contents to create a file in PHP.
It takes two parameters, the first of which is the name of the file to create, and the second of which is the contents to put inside of the file.
For example, if I wanted to make a file called 123.txt which contains hello world, I would do the following:
file_put_contents("123.txt", "hello world");
The filename can contain slashes /, so that you can specify which folder to create the file in. Thus, if I wanted to make my 123.txt file in the folder abc, I can put abc/123.txt as the filename (as long as abc is in the same folder as the PHP script).
You can find more about file_put_contents in the PHP manual.

PHP Simple HTML DOM Parser works on localhost but not live WordPress website

I am working with a WordPress plugin that outputs a table of data on the plugin's admin page. I have modified the plugin to add a button on the page that exports the table of data into a CSV file. Everything works perfectly on my localhost, but after transferring to the live server, it no longer works - the CSV file that is exported is blank. I am using PHP Simple HTML DOM Parser to parse the HTML table and convert it to CSV, and this seems to be where the roadblock is happening.
I have added the export button with this code (parts of the URL hidden for privacy):
<form action="**website-url**/wp-content/plugins/**plugin**/includes/votes-logs-export.php" method="POST">
<input type="submit" value="<?php _e('Export Table as CSV','**plugin**'); ?>" class="button" id="export" name="export" />
</form>
My file votes-logs-export.php has this code:
require_once('../../../../wp-load.php');
include 'simple_html_dom.php';
$file_name = "contest_votes_".date('d-m-Y-H-i-s').'.csv';
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$file_name);
global $wpdb;
$export_sql = "SELECT log.*,pst.post_title FROM ".$wpdb->prefix."votes_tbl as log LEFT JOIN ".$wpdb->prefix."posts as pst on log.post_id=pst.ID ORDER BY pst.post_title DESC";
$export_logs = $wpdb->get_results($export_sql, OBJECT);
if (!empty($export_logs)) {
$fp = fopen("php://output", "w");
if ($wpdb->num_rows > 0) {
$output = '';
foreach ($export_logs as $logs) {
$vote_id = $logs->post_id;
$postdata = get_posts($vote_id);
$vote_author_id = $postdata[0]->post_author;
$vote_author = get_the_author_meta( 'display_name', $vote_author_id );
$voter_name = $logs->ip;
if(filter_var($voter_name, FILTER_VALIDATE_IP) !== false)
$voter_name = $logs->ip;
else
$voter_name = get_the_author_meta( 'display_name', $voter_name );
$voted_date = $logs->date;
$output .= '
<tr>
<td>'.$logs->post_title.'</td>
<td class="author column-author">'.$vote_author.'</td>
<td class="author column-author">'.$voter_name.'</td>
<td class="author column-author">'.$voted_date.'</td>
</tr>';
}
}
$table = '
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Voter</th>
<th>Vote Date</th>
</tr>' . $output . '</table>';
$html = str_get_html($table);
foreach($html->find('tr') as $element){
$td = array();
foreach( $element->find('th') as $row){
$td [] = $row->plaintext;
}
// prevent blank rows being inserted into CSV file
if (!empty($td)) {
fputcsv($fp, $td);
}
$td = array();
foreach( $element->find('td') as $row){
$td [] = $row->plaintext;
}
// prevent blank rows being inserted into CSV file
if (!empty($td)) {
fputcsv($fp, $td);
}
}
fclose($fp);
}
I'm able to view the PHP page in order to debug by commenting out the header redirects. On my localhost, the PHP page outputs the table data in CSV format, but on the live server, it's a blank page. (No errors on the page or in error_log.) I have debugged this code and found that $table and all of the code above it seems to be running perfectly - if I print the contents of $table I get a formatted HTML table of my data:
<table>
<tbody>
<tr>
<th>Title</th>
<th>Author</th>
<th>Voter</th>
<th>Vote Date</th>
</tr>
<tr>
<td>Writing-on-Stone Park</td>
<td class="author column-author">admin</td>
<td class="author column-author">email#email.com</td>
<td class="author column-author">2014-07-04 16:42:57</td>
</tr>
<tr>
<td>White Tailed Ptarmigan</td>
<td class="author column-author">admin</td>
<td class="author column-author">email#email.com</td>
<td class="author column-author">2014-07-04 06:07:51</td>
</tr>
<tr>
<td>Rockbound Lake</td>
<td class="author column-author">admin</td>
<td class="author column-author">email#email.com</td>
<td class="author column-author">2014-07-04 06:07:28</td>
</tr>
</tbody>
</table>
The block happens at $html = str_get_html($table) - if I print out $html, nothing gets printed to the page, not even an error or any kind of 'false' or 'NULL' value. If I try to echo a string after that block of code, it is not output to the page, so the script seems to stop running there.
I was able to confirm that my simple_html_dom.php file is being referenced correctly because echoing a string in that file does get output to my votes-logs-export.php page. Yet the functions within the file don't seem to be firing? I'm out of ideas on this one!
I confirmed that 'allow_url_fopen' is set to 'true' in php.ini. In my simple_html_dom.php file, I also tried changing the "MAX_FILE_SIZE" from 600,000 to 100,000,000 but to no effect. The memory on the server is set to 40MB. I admit I am a newbie with working with custom WordPress plugins, but the fact this works on my localhost seems to indicate there is some kind of configuration or compatibility issue on the live server...? I would appreciate any guidance or tips you can offer.
PHP version on the live server is 5.4.21. My localhost is using 5.3.
I ended up explicitly setting error_reporting(1) in my file, which finally threw me a valuable error - Call to undefined function mb_detect_encoding() on line 1238 of simple_html_dom.php. Turns out I needed to enable the PHP extension mbstring on my server. Problem solved!

PHP will not execute properly and only displays as text

My entire PHP page only displays as text and no PHP code is executed. It's weird because when I test it using <? phpinfo(); ?> in a test.php file, I get a successful test and it works on my Apache server. However when I attempt to do anything else. It only shows as text.
Edit: Here is the link to the code. I couldn't figure out how to post it here. Pastebin
<?php
// create short variable names
$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
$find = $_POST['find'];
?>
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<?php
echo "<p>Order processed at ".date('H:i, jS F Y')."</p>";
echo "<p>Your order is as follows: </p>";
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo "Items ordered: ".$totalqty."<br />";
if ($totalqty == 0) {
echo "You did not order anything on the previous page!<br />";
} else {
if ($tireqty > 0) {
echo $tireqty." tires<br />";
}
if ($oilqty > 0) {
echo $oilqty." bottles of oil<br />";
}
if ($sparkqty > 0) {
echo $sparkqty." spark plugs<br />";
}
}
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
echo "Subtotal: $".number_format($totalamount,2)."<br />";
$taxrate = 0.10; // local sales tax is 10%
$totalamount = $totalamount * (1 + $taxrate);
echo "Total including tax: $".number_format($totalamount,2)."<br />";
if($find == "a") {
echo "<p>Regular customer.</p>";
} elseif($find == "b") {
echo "<p>Customer referred by TV advert.</p>";
} elseif($find == "c") {
echo "<p>Customer referred by phone directory.</p>";
} elseif($find == "d") {
echo "<p>Customer referred by word of mouth.</p>";
} else {
echo "<p>We do not know how this customer found us.</p>";
}
?>
</body>
</html>
I am willing to bet 10$ that test.php uses <?php, and the changed code uses <?, while the server does not understand it as an opening tag since short_open_tags is off in php.ini.
A lot of books use <? for open tags, while most servers only support the long version (<?php). If that's the case, then changing all the simple <? to <?php will do the trick.
PHP code is only exposed in 1 case: When PHP interpreter does not identify it as PHP code. That can be caused by only 2 problems:
Wrong configuration of Apache (or other http server) which doesn't handle php files at all.
Wrong open tags in PHP files, so PHP doesn't know when code begins.
If the file is a *.php, if Apache is turned on serving *.php files through PHP interpreter, if standard open tags are used or PHP is configured to use other types of used tags, and if you're accessing this PHP file through the browser, in no circumstances would PHP expose this code.

Categories