Making PHP Script Automatically write to text file - php

I am writing a script to try and help make my day to day work easier. It works in parts, sending requests to an API and receiving responses. I then want it to save said responses in a text file that will be automatically emailed to a defined mailbox. The bit I am stuck with, is actually making my script save to a text file.
This is my script: (I'm not very experienced.. the include files aren't relevant, as they send requests the the API and contain nothing else.) I'm hoping that i can literally add a line at the bottom after the SQL connection closes to tell it to save to the text file. Also, I would like the text file to take the name of the "$CorrectCLI" variable.
Any help is appreciated. Cheers.
// Check connection
if(mysqli_connect_errno()) {
echo "Could Not Connect, Contact Support.";
exit;
} else {
echo "Connected to Database Successfully.<br><br>";
}
//Required Information:
$CorrectCLI = $CLIrow[0];
$CorrectSitename = $SiteNamRow[0];
$CorrectSiteNumber = $SiteNumRow[0];
$CorrectIP = $IProw[0];;
$xrefFromKF = "503269";
echo nl2br("Affected XREF: " . $xrefFromKF . "\n");
$CLIquery = "select primary_cli from customers where xref = " . $xrefFromKF . "";
$CLIresult = mysqli_query($con,$CLIquery);
if(!$CLIresult) {
echo "Could Not Locate CLI In Database.<br>";
}
$CLIrow = mysqli_fetch_row($CLIresult);
$CLI = $CLIrow[0];
echo nl2br("Circuit CLI: 0" . $CLIrow[0] . "<br>");
if(!$CLI > 0 ) {
echo " Could Not Locate CLI.<br>";
}
$IPquery = "select manufacturers_ip_prim from customers where primary_cli = " . $CLIrow[0] . "";
$result = mysqli_query($con,$IPquery);
if(!$result) {
echo "Could Not Locate Management IP.<br>";
}
$IProw = mysqli_fetch_row($result);
$IPcount = $IProw[0];
echo nl2br("Circuit IP: " . $IProw[0] . "");
if(!$IPcount > 0 ) {
echo " Could Not Locate Management IP.<br>";
}
echo nl2br("\n\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output1, $result1);
if ($result1 == 0) {
echo nl2br("Circuit Recovered - Cancelled Diagnostics.");
} else {
echo nl2br("Circuit Down - Starting Diagnostics");
// Perform Sync Check
include '../diags/SyncStatus.php';
// Perform Data Port Reset
include '../diags/DataPortReset.php';
// sleep(10);
echo nl2br("\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output2, $result2);
if ($result2 == 0) {
echo nl2br("Circuit Recovered - Stopping Diagnostics.");
} else {
echo nl2br("Circuit Still Down - Continuing Diagnostics\n\n");
include '../diags/Metascript.php';
include '../diags/TAMtestSubmit.php';
include '../diags/TAMtestRetrieve.php';
echo "<br>";
include '../diags/GetProfile.php';
echo "<br>";
include '../diags/ProfileOverride.php';
echo "<br>";
// sleep(300);
include '../diags/RevertProfile.php';
echo "<br>";
echo nl2br("\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output4, $result4);
//print_r($output4);
if ($result4 == 0) {
echo nl2br("Circuit Recovered - Stopping End Of Diagnostics.");
} else {
echo nl2br("Circuit Still Down - Requires Attention.\n\n");
}
}
}
// Close the Database Connection
$conn->close();
?>

I would use the PHP output buffer.
Add this code to the top of this PHP script
ob_start("process_output");
function process_output($buffer){
$pageContent = $buffer;
// $pageContent is all the output of your web page,
// put your email logic here
return $pageContent;
}
In your logic I would reference http://php.net/manual/en/function.file-put-contents.php

Related

Header redirect advert die() OR exit() when using script to write to file

I have made a small script which dynamically created a text file and then downloads it to the users computer when then press a download button... the entire script below is what runs when the user presses 'download'
<?php
if (isset($_GET['download'])) {
if ($_GET['download'] == "1") {
header('Content-disposition: attachment; filename=TEST - Backup.txt');
header('Content-type: text/plain');
$projects = "SELECT * FROM projects WHERE user_id = '$user_id' ORDER BY id ASC";
if ($result=mysqli_query($conn,$projects)) {
while ($projects_array=mysqli_fetch_array($result)) {
$sql = $conn->query("SELECT COUNT(*) FROM refs WHERE project_id = " . $projects_array['id']);
$row = $sql->fetch_row();
$count = $row[0];
echo "\n\n" . "=== " . $projects_array['project_name'] . " ===" . "\n\n";
if ($count > 0) {
$all = "SELECT * FROM refs WHERE user_id = '$user_id' AND project_id = " . $projects_array['id'] . " ORDER BY IF(a_s_name = '', company_a, a_s_name) ASC";
if ($result_a=mysqli_query($conn,$all)) {
while ($ref=mysqli_fetch_array($result_a)) {
include 'sections/get.php';
if ($ref['type'] == 1){
include 'refs/1.php';
} elseif ($ref['type'] == 2) {
include 'refs/2.php';
} elseif ($ref['type'] == 3) {
include 'refs/3.php';
}
echo "\t" . strip_tags($cit) . "\n";
echo "\t" . strip_tags($ref) . "\n\n";
}
}
} else {
echo "\t" . "You don't currently have any references for this project." . "\n\n";
}
}
}
die ();
}
}
?>
After the user has pressed the download button, currently the file is download, however I want the user to then be redirected to a new location on the site.
I attempted to do this by using header location along with die();... so I replaced die() with this below:
die (header ("Location: http://siteurl.co.uk/?suc=8"));
However using this the file is not downloaded however the user is redirected
I appreciate any help
Use Javascript to open a popup window that performs the download, then it redirects the original window.
window.open("yourscript.php?download=1");
window.location.href = "http://siteurl.co.uk/?suc=8";

Is there a limit on record updates for MySQL in PHP?

I wrote a PHP script to do some color conversions from Hexadecimal to RGB and HSL values and store them in a database. My current dataset is the entire Pantone Solid Coated color book which is 1341 colors. I have the Hexadecimal values already in there.
From there I accessed the database and took the Hex value and did the two conversions and then stored them back in the table.
I am getting no errors, but the process seems to stop at record 499 for the updates even though the echo of all the values I did for testing show the calculations being applied to all 1341 colors.
Here is the script I have so far:
// SQL Server Login Info Removed
$sql_connection = new mysqli($sql_server, $sql_username, $sql_password, $sql_database);
if ($sql_connection->connect_error) {
die("Connection Failed: " . $sql_connection->connect_error);
}
$query = "SELECT * FROM coated";
$result = $sql_connection->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$colorname = $row["mapName"];
$hexvalue = $row["hex"];
if ($row["rgb"] == '') {
$rgbvalue = hex2rgb($hexvalue);
} else {
$rgbvalue = $row["rgb"];
}
if ($row["hsl"] == '') {
$hslvalue = hex2hsl($hexvalue);
} else {
$hslvalue = $row["hsl"];
}
//echo "Color: " . $row["mapName"] . " | " . $rgbvalue . " | " . $hslvalue . "<br>";
$wrt_query = "UPDATE coated SET hex='".$hexvalue."', rgb='".$rgbvalue."', hsl='".$hslvalue."' WHERE mapName='".$colorname."'";
if ($sql_connection->query($wrt_query) === true) {
echo "Record for " . $colorname . " updated <br>";
} else {
echo "Error updating record for " . $colorname . "<br>";
}
}
}
The data comes from a CSV file. Here is a excerpt:
pantone-Yellow-C,#fedd00
pantone-Yellow-012-C,#ffd700
pantone-Orange-021-C,#fe5000
pantone-Warm-Red-C,#f9423a
pantone-Red-032-C,#ef3340
pantone-Rubine-Red-C,#ce0058
pantone-Rhodamine-Red-C,#e10098
pantone-Purple-C,#bb29bb
pantone-Violet-C,#440099
pantone-Blue-072-C,#10069f
pantone-Reflex-Blue-C,#001489
pantone-Process-Blue-C,#0085ca
pantone-Green-C,#00ab84
pantone-Black-C,#2d2926
pantone-Yellow-0131-C,#f2f0a1
pantone-Red-0331-C,#fcaebb
pantone-Magenta-0521-C,#f1b2dc
pantone-Violet-0631-C,#bf9bde
pantone-Blue-0821-C,#74d1ea
pantone-Green-0921-C,#9de7d7
pantone-Black-0961-C,#9e978e
...
pantone-Black-2-C,#332f21
pantone-Black-3-C,#212721
pantone-Black-4-C,#31261d
pantone-Black-5-C,#3e2b2e
pantone-Black-6-C,#101820
pantone-Black-7-C,#3d3935
You might need to bump up your script time in php.ini, here I do it with a php function.
I think hex is more reliable as a key here, so I'm using that, since its always the same field length.
I've taken out its update since you dont change it.
Im also doing it with mysql if because I am sneaky.
Back up your db and give this a go.
set_time_limit(10000);
// SQL Server Login Info Removed
$sql_connection = new mysqli($sql_server, $sql_username, $sql_password, $sql_database);
if ($sql_connection->connect_error) {
die("Connection Failed: " . $sql_connection->connect_error);
}
$query = "SELECT * FROM coated";
$result = $sql_connection->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$wrt_query =
"UPDATE coated SET
rgb=IF(rgb IS NULL or rgb='','".hex2rgb($row["hex"])."',rgb)',
hsl=IF(hsl IS NULL or hsl='','".hex2hsl($row["hex"])."',hsl)'
WHERE hex='".$row["hex"]."';";
if ($sql_connection->query($wrt_query) === true) {
echo "Record for " . $colorname . " updated <br>";
} else {
echo "Error updating record for " . $colorname . "<br>";
}
}
}

How to generate a Log file in my machine when batch file is run as cronjob

Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);

Query does not insert into database

I've made this code but for some reason when i submit the form the data is not inserted to the table name posts. here's my code, i might have a typo or something, it'd be great if someone could have a look.
$fnames = Array("","","","","");
$fcnt = 0;
if (isset($_POST['submit']))
{
$allowedExts = array("gif", "jpeg", "jpg", "pjpeg", "x=png","png",);
// do all 5 files!
for ( $fnum = 1; $fnum <= 5; ++$fnum )
{
$curfile = $_FILES["uploaded_file" . $fnum];
if ($curfile["error"] > 0) {
echo "Return Code: " . $curfile["error"] . "<br>\n";
} else {
$ftype = explode( "/", $curfile["type"])[1]; // get the part after the /
$fsize = $curfile["size"];
if ( in_array($ftype, $allowedExts) && $fsize < 20000000 )
{
echo "Upload: " . $curfile["name"] . "<br>\n";
echo "Type: " . $ftype . "<br>\n";
echo "Size: " . ($fsize/1024) . " KB<br>\n";
echo "Temp file: " . $curfile["tmp_name"] . "<br>\n";
$fname = $_SESSION["userid"] . "_" . $curfile["name"];
if (file_exists("uploads/$fname"))
{
echo "$fname already exists.<br>\n";
} else {
move_uploaded_file($curfile["tmp_name"], "uploads/$fname");
$fnames[$fnum-1] = $fname;
++$fcnt;
}
}
else
{
echo "No valid file in slot $fnum<br>\n";
}
}
}
if ( $fcnt > 1 )
{
$sql = "INSERT INTO posts (picture1, picture2, picture3, picture4, picture5) VALUES( ". "'" . implode("','", $fnames) . "')";
echo "DEBUG SQL: $sql <hr>\n";
mysqli_query($sql);
}
}
With a quick glance:
A) error in your mysqli_query($sql);.
The mysqli_ extensin needs the connection pointer, something like: mysqli_query($dbConn, $sql);
B) Also, modify your query to look like mysqli_query($dbConn, $sql) or die(mysqli_error($dbConn));. It will show you the sql errors, if any.
EDIT 1
If no errors appear after you put the mysqli_error(), then i think your script never gets to the sql part. Something stops it before that if.
Put on top of your script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
and check if any php errors appear on the page.
Most of the time is a string/integer mismatch. Double check all your string escape characters. Copy your final query string and use some external tool to submit the query. You could start hardcoding all your data in the query and then proceed by adding one parameter at a time. Eventually you'll find the field (or fields) that causes the problem.
However, read carefully the error message first instead of guessing blindly what's causing the problem :-)
Make sure your fields count and values count are the same. Also correct this as well:
"'".implode("','", $fnames)."'"
in values passed.

php session variable doesn't update on post

I've had this problem for a couple days now and I've been trying different things to attempt to fix it and I'm not getting anywhere. Basically I'm pulling in data from a database, displaying the data using a loop, adding a "delete" button, and storing the data in a session array.
When the user presses the delete button the page refreshes but my session variable isn't being updated. Can anyone tell me why? I'm using the if isset 'POST' to update my session variable. FYI there's a lot of extra echoes in my code just so I can see what's going on. Any suggestions would be greatly appreciated. I also threw in a JavaScript popup to see if the if statement was working. The popup is not coming up either.
<?php
function multilineQ($con, $sql)
{
$x = 0; // incremented for the ex number
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con))
{
while ($row=mysqli_fetch_assoc($result))
{
$button = "ex" . $x . "Button";
echo "<ex id=\"ex$x\">";
echo $row['ExType'] . ' ----- ' . $row['ExName'] . " " .
"<input type=\"submit\"
name=\"$button\"
value=\"Delete\"> " .
" - <b>Button Name: </b>" . $button;
echo "<br />";
echo "</ex>";
// Add to Array
// ----------------------
$_SESSION['exArray'][$x][0] = 1;
$_SESSION['exArray'][$x][1] = $row['ExType'];
$_SESSION['exArray'][$x][2] = $row['ExName'];
// ----------------------
// If delete button pressed...
// ----------------------
echo "$button If statement created <br /><br />";
if (isset($_POST['$button']))
{
$_SESSION['exArray'][$x][0] = 0;
$foo = "Alert: " . $_SESSION['exArray'][$x][3] . " : Deleted.";
echo "<script type='text/javascript'>alert('$foo')</script>";
}
// ----------------------
$x++; // Increment number
}
mysqli_free_result($con);
}
} while (mysqli_next_result($con));
} else
{
echo 'Could not run SQL...';
}
}
?>
you need add the session_start() on the first statement.
<?php
here> session_start();
function multilineQ($con, $sql)
{

Categories