Edit a PHP file with PHP without duplicate content - php

So I have been trying to edit a PHP file after it is created and I seem to keep running into problems.
Here is my source code.
if($pbtype == 'pwall' OR $pbtype == 'cl')
{
$file = '../postback/pwallpb.php';
$pbac = '../postback/'.md5($affn).'.php';
}
else
{
$file = '../postback/postback.php';
$pbac = '../postback/'.md5($affn).'.php';
}
copy($file, $pbac);
// Read the while file into a string $htaccess
$files = file_get_contents($pbac);
// Stick the new IP just before the closing </files>
$new_files = str_replace('//NET NAME//', "$affn", $files);
$new_files .= str_replace('// IP 1 //', "$affip", $files);
$new_files .= str_replace('// IP 2 //', "$affip2", $files);
$new_files .= str_replace('// IP 3 //', "$affip3", $files);
$new_files .= str_replace('// IP 4 //', "$affip4", $files);
// And write the new string back to the file
file_put_contents($pbac, $new_files);
$pback = '/postback/'.md5($affn).'.php';
it creates the file. it is not a premissions problem, it edits file as well, but it generates the php each time i do a string replace, So id I str_replace 5 times then there is 5 instances of the code blocks in the file. what is it that I am doing wrong?
update to my code. what did i do wrong this time?
if($pbtype == 'pwall' OR $pbtype == 'cl')
{
$file = '../postback/pwallpb.php';
$pbac = '../postback/'.md5($affn).'.php';
}
else
{
$file = '../postback/postback.php';
$pbac = '../postback/'.md5($affn).'.php';
}
$myfile = fopen($file, "r") or die("Unable to open file!");
$files = fread($myfile,filesize($file));
fclose($myfile);
// Stick the new IP just before the closing </files>
$new_files = str_replace('||NETNAME||', $affn, $files);
$new_files = str_replace('||IP1||', $affip, $files);
$new_files = str_replace('||IP2||', $affip2, $files);
$new_files = str_replace('||IP3||', $affip3, $files);
$new_files = str_replace('||IP4||', $affip4, $files);
// And write the new string back to the file
$fh = fopen($pbac, 'w') or die("can't open file");
$stringData = $new_files;
fwrite($fh, $stringData);
fclose($fh);
$pback = '/postback/'.md5($affn).'.php';

This works and is tested:
error_reporting(-1);
ini_set('display_errors', 'On');
if($pbtype == 'pwall' OR $pbtype == 'cl')
{
$file = 'pwallpb.php';
$pbac = md5($affn).'.php';
}
else
{
$file = 'postback.php';
$pbac = md5($affn).'.php';
}
$myfile = fopen('../postback/' . $file, "r") or die("Unable to open file!");
$files = fread($myfile,filesize($pbac));
fclose($myfile);
// Stick the new IP just before the closing </files>
$new_files = str_replace('||NetName||', $affn, $files);
$new_files = str_replace('||IP1||', $affip, $new_files);
$new_files = str_replace('||IP2||', $affip2, $new_files);
$new_files = str_replace('||IP3||', $affip3, $new_files);
$new_files = str_replace('||IP4||', $affip4, $new_files);
$myFile = md5($affn).'.php';
$fh = fopen('../postback/' . $myFile, 'w') or die("can't open file");
$stringData = $new_files;
fwrite($fh, $stringData);
fclose($fh);
$pback = '../postback/'.md5($affn).'.php';
Test File renders this:
$IParray=array("1.2.3.4","2.3.4.5","4.5.6.7","5.6.7.8");

You are using ".=" instead of "=". ".=" appends your results to the file. Your code might look better like this:
if($pbtype == 'pwall' OR $pbtype == 'cl')
{
$file = '../postback/pwallpb.php';
}
else
{
$file = '../postback/postback.php';
}
$pbac = '../postback/'.md5($affn).'.php';
copy($file, $pbac);
// Read the while file into a string $htaccess
$files = file_get_contents($pbac);
// Stick the new IP just before the closing </files>
$searchArray = array('//NET NAME//','// IP 1 //','// IP 2 //','// IP 3 //','// IP 4 //');
$replaceArray = array("$affn","$affip","$affip2","$affip3","$affip4");
$new_files = str_replace($searchArray,$replaceArray,$files);
// And write the new string back to the file
file_put_contents($pbac, $new_files);
$pback = '/postback/'.md5($affn).'.php';

Related

Generate a new .txt file every 24 hour

I'm trying to make a visitor counter with php that will create yy-mm-dd.txt everyday and contain the number of visitors that day and after 12 AM it will create a new yy-mm-dd.txt file.
As example today is 2019-06-02 so the text file will be 2019-06-02.txt and in the next day, 2019-06-03.txt file will be automatically created.
Here is what I tried but it is not creating new 2019-06-03.txt file after 12 AM. It keeps the same 2019-06-02.txt file
<?php
$date = date('Y-m-d');
$fp = fopen('dates/'.$date.'.txt', "r");
$count = fread($fp, 1024);
fclose($fp);
$count = $count + 1;
$fp = fopen('dates/'.$date.'.txt', "w");
fwrite($fp, $count);
fclose($fp);
?>
How to fix it?
Your code should be working fine. We can also add is_dir and file_exists checks, and we can use either fopen, fwrite and fclose or file_get_content/file_put_content, if we like. We can also add a default_timezone such as:
date_default_timezone_set("America/New_York");
Then, our code would look like something similar to:
date_default_timezone_set("America/New_York");
$dir = 'dates';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$count = 1;
$date = date('Y-m-d');
$filename = $dir . '/' . $date . '.txt';
if (!file_exists($filename)) {
$fp = fopen($filename, "w");
fwrite($fp, $count);
fclose($fp);
} else {
$count = (int) file_get_contents($filename) + 1;
if ($count) {
file_put_contents($filename, $count);
} else {
print("Something is not right!");
}
}
Better use file_get_contents then file_put_contents:
<?php
$count = 1;
$content = file_get_contents(date('Y-m-d').'txt');
if($content !== FALSE){
$count+=(int)$content;
}
file_put_contents(date('Y-m-d').'txt', $count);
?>

Issue with multiple image write

Now I am fed up with this issue, have been trying to fix it since 2-3 days.
The problem:
I am downloading certain images, and then writing them on to disk with php script.
The images are high resolution may be around 7000 pixels. The data is being downloaded properly.
When I write this data on to file, some time 1 image gets write, some times 2,3 etc.
The script is not showing any error and just breaks.
I don't have access to server logs and can't check those either.
It breaks after curl_get_contents , means where I write file, if I comment that section it works properly.
Below is the code:
<?php
ini_set ("display_errors", "1");
error_reporting(E_ALL);
ini_set('max_execution_time', 3000);
include_once("../config.php");
include_once("../utils.php");
$DIR = "../wallpapers";
$URL = "Website url";
$info = array();
$dom = new domDocument;
#$dom->loadHTML(file_get_contents($URL));
$dom->preserveWhiteSpace = false;
$links = $dom->getElementsByTagName('img');
$i = 0;
foreach ($links as $tag){
$iurl = $tag->getAttribute('src');
$lastHyphenAt = strrpos($iurl, "-");
$iurl = substr ($iurl, 0, $lastHyphenAt).".jpg";
$info[$i]["url"] = $iurl;
$info[$i]["name"] = basename($iurl);
$i++;
}
foreach($info as $item){
$url = $item["url"];
$name = $item["name"];
if(!file_exists($DIR."/".$name)){
echo "Downloading: ".$url."<br><br>";
$data = curl_get_contents($url);
$file = fopen($DIR."/".$name,"w") or die('Cannot open file: '.$my_file);
fwrite($file,$data);
fclose($file);
}else
echo "Exists ".($DIR."/".$name)."<br><br>";
}
?>
you can write high resolution images by applying chunk functionality, check below code for the same :-
$chunk = 102400;
$filePointer = fopen($url, "rb");
if ($filePointer!=false){
while (!feof($filePointer))
{
if($chunk<TOTALFILESIZE)
{
$fileData = fread($filePointer, 102400); //102400 is chunk size
$myFile = $DIR."/".$_REQUEST['filename'].'.'.$_REQUEST['ext']; //store the file into temp. location
chmod($myFile, 0777);
$fp = fopen($myFile, 'a+');
fwrite($fp, $fileData);
fclose($fp);
}
}
}

Open dir from read txt

PHP script who open and search data from .txt is:
function explodeRows($data) {
$rowsArr = explode("\n", $data);
return $rowsArr;
}
function explodeTabs($singleLine) {
$tabsArr = explode("\t", $singleLine);
return $tabsArr;
}
$filename = "/txt/name.txt";
$handle = fopen($filename, 'r');
$data = fread($handle, filesize($filename));
$rowsArr = explodeRows($data);
for($i=0;$i<count($rowsArr);$i++) {
$lineDetails = explode("|",$rowsArr[$i]);
if ($kodas == $lineDetails[2]) {
$link3=$lineDetails[4];
echo "";
} }
fclose($handle);
It's works well, but now I transfer name.txt to another folder (folder name txt). How to make, first open this folder and search open name.txt
$filename = "txt/name.txt";
$handle = fopen($filename, 'r');
$data = fread($handle, filesize($filename));
$rowsArr = explodeRows($data);

Find out if a directory exists in php

I want to know whether or not a directory exists.
If not, I would like to create the directory.
My code is below:
$da = getdate();
$dat = $da["year"]."-".$da["mon"]."-".$da["mday"];
$m = md5($url)."xml";
if(is_dir($dat))
{
chdir($dat);
$fh = fopen($m, 'w');
fwrite($fh, $xml);
fclose($fh);
echo "yes";
}
else
{
mkdir($dat,0777,true);
chdir($dat);
$fh = fopen($m, 'w');
fwrite($fh, $xml);
fclose($fh);
echo "not";
}
Use is_dir, which checks whether the path exists and is a directory then mkdir.
function mkdir_if_not_there($path) {
if (!is_dir($path)) {
// Watch out for potential race conditions here
mkdir($path);
}
}
Use is_dir:
$pathname = "/path/to/dir";
if(is_dir($pathname)) {
// do something
}

Convert vCard Bulk Contact File to Single .vcf files

I recently had an issue... I wanted to transfer my contacts fro my LG U990 Viewty to my iPhone 3GS
I exported the contacts from my LG to a vCard File containing all the addresses all in one as
BEGIN:VCARD
VERSION:2.1
N;CHARSET=UTF-8:A;
TEL;CELL;CHARSET=UTF-8:*121#
REV:20120720T081000Z
END:VCARD
Now the above format repeated itself for all contacts... in that single file...
I wanted to convert this single file to original vcf files... not knowing that they could not be imported to iPhone also :(
Actualy Solution : I needed to upload the original bulk vCard file to a new gmail's accounts contacts and sync my contacts to that list in iTunes... which finally I did
However, I made this code which is in PHP generally available as a paid software which people buy to decipher the contacts... here is the below code... FREE
contacts.txt is that file ... open that vCard file in text editor and copy the contents and make this contacts.txt file
$filename = "contacts.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));
fclose ($fd);
$delimiter = "BEGIN:VCARD";
$splitcontents = explode($delimiter, $contents);
$counter = "";
$write = "";
$finalName = "";
foreach ( $splitcontents as $color )
{
$counter = $counter+1;
$first = strpos($color, "UTF-8:");
$second = strpos($color, "TEL;");
$name = substr($color, $first+6, $second-$first-7);
$wordChunks = explode(";", $name);
for($i = 0; $i < count($wordChunks); $i++)
{
if(trim($wordChunks[0])!="" || trim($wordChunks[1])!="" )
$finalName .= " ".$wordChunks[$i];
}
$finalName= trim($finalName);
$fileName = $finalName.".vcf";
$ourFileHandle = fopen($fileName, 'w') or die("can't open file");
$stringData = "BEGIN:VCARD ".$color;
fwrite($ourFileHandle, $stringData);
fclose($ourFileHandle);
$finalName = "";
}
this will finally make miltuple .vcf files of format given above...
MY QUESTION : WHAT I DID WAS VERY SIMPLE AND HAS LOOPHOLES - CAN WE DO THE ABOVE ITERATION AND FILTERING IN A PHP REGULAR EXPRESSION ?
it would be a great learning ?
Read the file and get a string of the context
NSData *String_Data = [NSData dataWithContentsOfFile:yourfilepath];
NSString *theString = [[NSString alloc] initWithData:String_Data encoding:NSUTF8StringEncoding];
Get array of all the lines in the context
NSArray *lines = [theString componentsSeparatedByString:#"\n"];
Run for Loop through each line: Check prefix for BEGIN: or END:
NSString * stringForVCard=#"";
for (int i=0; i<[lines count];i++){
[stringForVCard stringByAppendingString:[lines objectAtIndex:i]
if ([line hasPrefix:#"END"])
[stringForVCard writeToFile:[NSString stringWithFormat:#"Make your own file path for each VCF"] atomically:TRUE encoding:NSUTF8StringEncoding error:nil ];
//Empty the string
stringForVCard=#"";}
file structure:
index.php
contacts.vcf
a(folder)
$filename = "contacts.vcf";
$file = file($filename);
$i=1;
$content = "";
foreach ( $file as $line )
{
if($line == 'BEGIN:VCARD'."\r\n"){
$content = "";
}
$content .= $line;
if($line == 'END:VCARD'."\r\n"){
$fileName = $i.".vcf";
$ourFileHandle = fopen('a/'.$fileName, 'w') or die("can't open file");
fwrite($ourFileHandle, $content);
fclose($ourFileHandle);
$i++;
echo '<br>' . $i .'
';
}
}

Categories