Get Json and output to text file undecoded - php

I want to fetch json script and write it to a txt file undecoded, exactly how it was originally. I do have a script that I use that I am modifying but unsure what to commands to use. This script decodes, which is what I want to advoid.
//Get Age
list($bstat,$bage,$bdata) = explode("\t",check_file('./advise/roadsnow.txt',60*2+15));
//Test Age
if ( $bage > $CacheMaxAge ) {
//echo "The if statement evaluated to true so get new file and reset $bage";
$bage="0";
$file = file_get_contents('http://somesite.jsontxt');
$out = (json_decode($file));
$report = wordwrap($out->mainText, 100, "\n");
//$valid = $out->validTo;
//write the data to a text file called roadsnow.txt
$myFile = "./advise/roadsnow.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $report;
fwrite($fh, $stringData);
}
else {
//echo the test evaluated to false; file is not stale so read local cache
//print "we are at the read local cache";
$stringData = file_get_contents("./advise/roadsnow.txt");
}
// if/else is done carry on with processing
//Format file
$data = $stringData

Try this:
// Get JSON Data
$json_data = file_get_contents('http://somesite.jsontxt');
// Write JSON to File
file_put_contents('json_data.txt', $json_data);

Related

Odd Behavior when appending JSON file using PHP

So I have a JSON file containing basketball player information in the following format:
[{"name":"Lamar Patterson","team":1,"yearsLeft":0,"position":"PG","PPG":17},{"name":"Talib Zanna", "team":1,"yearsLeft":0,"position":"SF","PPG":13.1},....]
I want a user to be a able to add their own custom players to this file. To do this i try the following:
<?php
$json = file_get_contents('json/players.json');
$info = json_decode($json, true);
$info[] = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
file_put_contents('json/players.json', json_encode($info));
?>
This "sort of" works. But when I check the JSON file, I find that there are 3 new entries rather than 1:
{"name":"","team":null,"yearsLeft":4,"position":"","PPG":""},{"name":"","team":"3","yearsLeft":4,"position":"","PPG":""},{"name":"Jeff","team":null,"yearsLeft":4,"position":"C","PPG":"23"}
assuming $name="Jeff" $team=3 and $ppg=23 (populated via POST submission).
What's going on and how can I fix it?
You could try doing the following:
Untested code
<?php
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
$fh = fopen('json/players.json', 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);//removes last ] char
fclose($fh);
$fh = fopen('json/players.json', 'a');
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
fwrite($fh, ','.json_encode($info).']');
fclose($fh);
}
?>
This will append the only the new json to the file instead of opening the file, making php parse all the json and then writing it to the file again. In addition to that it will only store the data if the variables actually contain data.
Try this:
<?php
//get the posted values
$name = $_POST['name'];
$team = $_POST['team'];
$position = $_POST['position'];
$ppg = $_POST['ppg'];
//verify they're not empty
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
//Open the file
$fh = fopen('json/players.json', 'r+') or die("can't open file");
//get file info/stats
$stat = fstat($fh);
//final desired size after trimming the trailing ']'
$size = $stat['size']-1;
//file has contents? then remove the trailing ']'
if($size>0) ftruncate($fh, $size);
//close the current handle
fclose($fh);
// reopen the file for append
$fh = fopen('json/players.json', 'a');
//build your data array
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
//if this is not the first item on file
if($size>0) fwrite($fh, ','.json_encode($info).']'); //append with comma
else fwrite($fh, '['.json_encode($info).']'); //first item on file
fclose($fh);
}
?>
Maybe your php config is not set to convert the post/get variables to global variables. This happened to me a couple of times so I rather create the variables I'm expecting from the post/get request. Also watch out for the page encoding, from personal experience you could be getting empty strings there.

Receiving post data xml

Hi I need to receive a post data which will be in an xml that is encoded in a base64 format.
I'll be receiving this from a payment gateway. Now all i get is this. My code creates a txt file but is empty. Is there anything wrong with the code? The output should be an xml envelope in a text file.
$body = '';
$fh = #fopen('php://input', 'r');
if ($fh)
{
while (!feof($fh))
{
$s = fread($fh, 1024);
echo $s;
if (is_string($s))
{
$body .= $s;
}
}
fclose($fh);
}
$body = base64_decode($body);
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $body;
fwrite($fh, $stringData);
fclose($fh);
I tried to contact the payment gateway and they are telling me that they are getting this error "The remote server returned an error: (417) Expectation failed." where could the problem exist us or them?
Since your file is returning blank, I would recommend verifying the specifications from the payment gateway for your fopen() function. In addition, if you are properly getting data back from them, then I would check the base64_decode() function. I have seen situations where there may be a header or other data at the top of the actual payload data that fouls up the base64_decode and ruins your day.
It looks like you are mixing up your file handlers, can you see if the following codes run:
$body = $HTTP_RAW_POST_DATA;
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
$stringData = $body;
fwrite($ourFileHandle, $stringData);
fclose($ourFileHandle);
I have just tested the above code myself successfully.
What I suggest you do is trying the following:
Try to put a static piece of data into $body (eg: "$body = 'test';")- and see if that saves - if not then it is an issue at your end.
Delete the file (to remove any permission issues).
Double check the url that the payment gateway is sending to is correct.

Persistent Date Stamp - write/read to file

I'm trying to set a persistent date stamp by writing it to a text file and then reading it back in each time the page is viewed.
// set the date, w/in if statements, but left out for brevity
$cldate = date("m/d/Y");
$data = ('clickdate' => '$cldate'); // trying to set a variable/value pair
- It's throwing an Error on this !
// Open an existing text file that only has the word "locked" in it.
$fd = fopen("path_to_file/linktrackerlock.txt", 'a') or die("Can't open lock file");
// Write (append) the pair to the text file
fwrite($fd, $data);
// further down …
// Open the text file again to read from it
$rawdata = fopen("path_to_file/linktrackerlock.txt", 'r');
// Read everything in from the file
$cldata = fread($rawdata, filesize("path_to_file/linktrackerlock.txt"));
fclose($rawdata);
// Echo out just the value of the data pair
echo "<div id='Since'>Clicks Since: " . $cldata['clickdate'] . "</div>";
$data = ('clickdate' => '$cldate');
needs to be:
$data = array('clickdate' => $cldate);
Additionally, you are required to pass a string to an fwrite statement, so there is no need to create an array:
$cldate = date("m/d/Y");
if($fd = fopen("path_to_file/linktrackerlock.txt", 'a')){
fwrite($fd, $cldate);
fclose($fd);
}else{
die("Can't open lock file");
}
Code's fundamentally broken. You're trying to create an array, then write that array out to a file:
$data = array('clickdate' => '$cldate');
^^^^^---missing
Then you have
fwrite($fd, $data);
But all that will do is write the word Array out to your file, NOT the contents of the array. You can try it yourself... just do echo $data and see what you get.
You could probably make this whole thing a lot simpler with:
$now = date("m/d/Y");
file_put_contents('yourfile.txt', $now);
$read_back = file_get_contents('yourfile.txt');
If you do insist on using an array, then you have to serialize or, or use another encoding format, like JSON:
$now = date("m/d/Y");
$arr = array('clickdate' => $now);
$encoded = serialize($arr);
file_put_contents('yourfile.txt', $encoded);
$readback = file_get_contents('yourfile.txt');
$new_arr = unserialize($readback_encoded);
$new_now = $new_arr['clickdate'];

How to build a PHP rotator

I'm writing a script for a lead contact form that needs to send the first 10 leads to email 1, the second 10 leads to email 2, and so on until it gets to email 4, and then it goes back to email 1.
this is a rotator i have that was built for landing pages, but it rotates 1 each time rather than waiting 10 times, and then rotating. how would I modify this to suit my needs?
Also, it cant happen on every 'refresh' obviously. there would need to be a separate group of code which would go in the action="whatever.php" of the form and thats the code that would increment it.
<?php
//these are the email addresses to be rotated
$email_address[1] = 'email1#email.com';
$email_address[2] = 'email2#email.com';
$email_address[3] = 'email3#email.com';
$email_address[4] = 'email4#email.com';
//this is the text file, which will be stored in the same directory as this file,
//count.txt needs to be CHMOD to 777, full privileges, to read and write to it.
$myFile = "count.txt";
//open the txt file
$fh = #fopen($myFile, 'r');
$email_number = #fread($fh, 5);
#fclose($fh);
//see which landing page is next in line to be shown.
if ($email_number >= count($email_address)) {
$email_number = 1;
} else {
$email_number = $email_number + 1;
}
//write to the txt file.
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $email_number . "\n";
fwrite($fh, $stringData);
fclose($fh);
//include the landing page
echo $email_address[$email_number];
//terminate script
die();
?>
What I understood from your question is there would be form to submit leads and when a lead is submitted, it has to follow your logic. Correct me if I'm wrong.
If that be the case,
use two a text file like track.txt. The initial contents of this text file would be 1,0. Which means leads are sent to first email id 0 times.
So in the action script of the form include the following code.
<?php
$email_address[1] = 'email1#email.com';
$email_address[2] = 'email2#email.com';
$email_address[3] = 'email3#email.com';
$email_address[4] = 'email4#email.com';
$myFile = "track.txt";
//open the txt file
$fh = #fopen($myFile, 'r');
$track = #fread($fh, 5);
#fclose($fh);
$track = explode(",",$track);
$email = $track[0];
$count = $track[1];
if($count >= 10)
{
$count=0;
if($email >= count($email_address))
{
$email = 1;
}
else
{
$email++;
}
}
else
{
$count++;
}
$track = $email.",".$count;
//write to the txt file.
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $track);
fclose($fh);
//send lead to $email
?>

Writing to Text files via php

I have a little issue while trying to kill time. I am writint to a text file the contents of the filled in form so it is easy to read. At the moment everything gets put int a single line, and therfore I can not tell where msgs begin or end. I wrote a php like this:
$from = $_POST[from];
$friend = $_POST[friend];
$carrier = $_POST[carrier];
$message = stripslashes($_POST[message]);
if ((empty($from)) || (empty($friend)) || (empty($message))) {
header ("Location: sms_error.php");
}
else if ($carrier == "orange_mobile_network") {
$formatted_number = $friend."#orange_mobile_network.co.uk";
mail("$formatted_number", "SMS", "$message");
header ("Location: sms_success.php");
}
Then the SMS/Text message will be sent. After this I wanted to write/store/append the message on a txt file. So I wrote:
$myFile = "sms_Numbers_Mgs.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
$stringData = $_POST[from];
fwrite($fh, $stringData);
$stringData = $_POST[friend];
fwrite($fh, $stringData);
$stringData = $_POST[message];
fwrite($fh, $stringData);
fclose($fh);
But like I said. Everything works. I just want to be able to read the file and put everything in a new line and possibly format it nicely for easy reading. I do not want to use a DB for storing the TXT as my host is going to charge me.
change this:
fwrite($fh, $stringData);
with this:
fwrite($fh, $stringData . PHP_EOL);
or:
fwrite($fh, $stringData . "\r\n");
You can append PHP_EOL when you write for a platform aware newline. I.e. $stringData = <string> . PHP_EOL;
If don't need it to be platform aware, going with the windows newline is a safe option.
define('CRLF', "\r\n");
$stringData = <string> . CRLF;
fwrite($fh, $stringData);
I do not know exactly Cause you're using. txt instead of a bank, but my tip for this specific case is to work with json format.
Example:
$myFile = "sms_Numbers_Mgs.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
//assembles a string of type json
$data = json_encode(array(
'from' => $_POST[from],
'friend' => $_POST[friend],
'message' => $_POST[message]
));
//Write in the file
fwrite($fh, $data);
fclose($fh);
//reads the file
$content = file_get_contents($myFile);
$object = json_decode($content);
var_dump($object);
good it is at least better organized.
a hug!

Categories