Adding a number if file exists PHP - php

I am trying to see if a certain file exists. If it does, I need to make it look like #_filename.jpeg. It works, but only adds a 1 and does not increment further.
This is my code:
if (file_exists('upload/'.$file_name)) {
$i = 1;
while(file_exists('upload/'/$i."_".$file_name)) {
$i++;
}
$file_name = $i."_".$file_name;
}

you have syntax error (missing .) so your while condition not working and not going to loop so $i not increases try to replace
while(file_exists('upload/'/$i."_".$file_name)) {
to
while(file_exists('upload/'.$i."_".$file_name)) {

Related

Need Help on the below modification [duplicate]

I am fairly new to the php world and have been creating an inventory tracking system for one of my side businesses. Most of the basics are working, but I am having issues with my "upload pdf" function. Even though it works and uploads the pdf file to its target location, I cannot get the file name ($docid) to be an integer that auto increments every time there is a submission so that files never have the same name. Below is the code I have working:
$pdfPath = "/Documents/TEST/";
$maxSize = 102400000000;
$docid = TEST;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_pdf'])) {
if (is_uploaded_file($_FILES['filepdf']['tmp_name'])) {
if ($_FILES['filepdf']['type'] != "application/pdf") {
echo '<p>The file is not in PDF</p>';
} else if ($_FILES['filepdf']['size'] > $maxSize) {
echo '<p class="error">File is too big! Max size is =' . $maxSize . 'KB</p>';
} else {
$menuName = "Order_Receipt_".$docid.".pdf";
$result = move_uploaded_file($_FILES['filepdf']['tmp_name'], $pdfPath . $menuName);
if ($result == 1) {
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=http://localhost/website/enter_new_order_success.html">';
} else {
echo '<p class="error">Error</p>';
}
}
}
I know I need some sort of loop to auto increment that $docid variable but I cannot seem to figure it out. I have read up on the topic, but auto increment with the if statement is throwing me off. Any help would be greatly appreciated.
Cheers
Well, unless you store the entries to keep track in a database or similar you could check what entries you have in your upload folder and increment it by one.
The glob function is useful for that:
http://php.net/manual/en/function.glob.php
$myFiles = sort(glob('/Documents/TEST/*.pdf')); // returns an array of pdf files in the target folder. Using sort to sort the array e.g. file_1_.pdf,file_2_.pdf,file_3_.pdf, etc
//last element
$lastFile = end($myFiles); //returns the last file in the array
//get the number and increment it by one
$number = explode('_',$lastFile);
$newNumber = $number[1] + 1; //add this to the name of your uploaded php file.
$pdfUploadedFile= "Order_Receipt_".$newNumber."_.pdf";
As pointed out in the comments... I find it a better idea to name it with a timestamp generated string. And also don't forget the quotes around your strings.
$docid = TEST;
should be:
$docid = 'TEST';
Edit
Even better would be naming it in a formatted date I suppose.
$pdfUploadedFile= "Order_Receipt_".date("Y-m-d-H-i-s").".pdf"; // will output something like Order_receipt_2014-09-24-11-14-44.pdf

Name each new dir with the next available number with php

I'm working on a php file where I want to create one or more directories with names ranging from 1 to 999 or more. I'm creating the first of all directories using the following code:
<?php
$id = '001';
mkdir($id)
?>
What I want to succeed is to automatically create a new directory using as a name the next available number (i.e. 002, 003, 004, 005 etc) either as a string or an integer. However, I really stuck and I try to use:
<?php
$id = 001;
if (file_exists($id)) {
$id = $id + 1;
mkdir($id);
}
?>
..but it doesn't work. Any ideas?
I forgot to mention that the above code is part of the if statement inside the same php code.
Several ways to do this, depending on your use case. This function may work for you:
<?PHP
function makedir($id){
if(file_exists($id)){
$id++;
makedir($id);
}else{
mkdir($id);
return true;
}
}
makedir(1);
This solution of incremented directory names is going to become ugly after a while though; you should probably find a better solution to your problem.
You could do something like this:
// Loop through all numbers.
for ($i = 1; $i <= 999; $i++) {
// Get the formatted dir name (prepending 0s)
$dir = sprintf('%03d', $i);
// If the dir doesn't exist, create it.
if (!file_exists($dir)) {
mkdir($dir);
}
}
Edit: the above was assuming you wanted to make all 999 directories. You could do the following to just append the next available number:
function createDir($dir) {
$newDir = $dir;
$num = 1;
while (file_exists($newDir)) {
$newDir = $dir.sprintf('%03d', $num++);
}
return $newDir;
}

Extracting data from text log file advice

I would like an advice on best approach on this task.
I have a text log file holding data from a gps, this is the format:
time,lat,lon,elevation,accuracy,bearing,speed
2014-07-08T12:56:52Z,56.187344,10.192660,116.400024,5.000000,285.000000,1.063350
2014-07-08T12:56:58Z,56.187299,10.192754,113.799988,5.000000,161.000000,3.753000
2014-07-08T12:57:07Z,56.186922,10.193048,129.200012,5.000000,159.000000,5.254200
2014-07-08T12:57:13Z,56.186694,10.193133,109.799988,5.000000,152.000000,3.878100
2014-07-08T12:57:16Z,56.186745,10.193304,142.900024,5.000000,149.000000,3.940650
2014-07-08T12:57:20Z,56.186448,10.193417,118.700012,5.000000,154.000000,2.376900
2014-07-08T12:57:27Z,56.186492,10.193820,131.299988,5.000000,65.000000,5.379300
I need to find the line where the speed exceeds a certain value, then get the time from that line, then scroll trough the lines and find the line where the speed is below this value, get the time and write these 2 time values into my database.
This has to be an automated task, so I assume that a cron PHP script could do the job.
Best regards Thomas
Despite the fact that there is no special advice needed but wanting someone to code your problem - I will try to put you in the right direction. I've written easy to understand code where you can build on (untested)...
<?php
// Setup.
$pathGpsFile = 'gps.log';
$speedThreshold = 5;
//
// Execution.
//
if(!file_exists($pathGpsFile)) {
die('File "'. $pathGpsFile .'" does not exist.');
}
// Read entries into array.
$gpsEntries = file($pathGpsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Loop through entries.
$lineCount = 0;
$currentDifferences = array();
$currentDifference = array();
foreach($gpsEntries as $gpsEntry) {
// Skip head.
if($lineCount == 0) {
$lineCount++;
continue;
}
// Extract values from gps entry.
list($time, $lat, $lon, $elevation, $accuracy, $bearing, $speed) = explode(',', $gpsEntry);
// Check if there is currently a difference monitored.
if(count($currentDifference) == 1) {
if($speed < $speedThreshold) {
$currentDifference[] = $gpsEntry;
}
// Add to differences list.
$currentDifferences[] = $currentDifference;
// Reset current difference.
$currentDifference = array();
} else {
if($speed > $speedThreshold) {
$currentDifference[] = $gpsEntry;
}
}
// Increase line count.
$lineCount++;
}
// Check output.
var_dump($currentDifferences);
?>

Looping through files, one file processes, then that's it, no error reporting

So I have a problem with a script I'm working on. I have a folder full of JSON files called roster0.json, roster1, etc. etc.
$dir = "responses/";
$files = glob($dir . "roster*");
$failed = array();
$failcnt = 0;
if (isset($files)) {
$data = null;
for ($i = 0; $i < count($files); $i++) {
$data = json_decode(utf8_decode(file_get_contents($files[$i])));
if(isset($data)){
// Process stuff
When I var_dump($files) I get an array with over 100 paths "responses/roster0.json".
When I test $data I get a proper array of data.
However, once the loop goes to the next file, it never loads it, and never processes it.
Here's the crazy part. If I change the start of the for loop, e.g. $i = 20. It will load the 21st file in the directory and parse it and insert it into the db properly!
Ignoring the failcnt stuff at the bottom, here's the current version of the script in it's entirety. http://pastebin.com/yqyKi5Ag
PS - I have full WARNING/ERROR reporting on in PHP and not getting any error messages...HELP! Thanks!
When I was writing the insert string the ID was being duplicated and thus was invalid. Switched to auto-inc and tada. It works. Thanks for the assistance. –

File reading, searching and looping problems

So i've been trying to write this little piece of code to read a file (status.txt), search it for 1 of 4 keywords and loop until either time runs out (5 minutes) or it finds one of the words. I've already written a few simple php scripts to write the words to a txt file, but I can't seem to get this part to work. It either doesn't clear the file in the beginning or seems to hang and never picks up the changes. Any advice would be hugely helpful.
<?php
//Variables
$stringG = "green";
$stringR = "red";
$stringB = "blue";
$stringO = "orange";
$clear = "";
$statusFile = "status.txt";
//erase file
$fh = fopen($statusFile, 'w'); //clear the file with "clear"
fwrite($fh, $clear);
fclose($fh);
//Insert LOOP
$counter = 0;
while ( $counter <= 10 ) {
//echo "loop begun";
// Read THE FILE
$fh = fopen($statusFile, 'r');
$data = fread($fh, filesize($statusFile));
fclose($fh);
//process the file
if(stristr($data,$stringG)) {
echo "Green!";
$counter = $counter + 30; //stop if triggered
}
elseif (stristr($data,$stringR)) {
echo "Red";
$counter = $counter + 30; //stop if triggered
}
elseif (stristr($data,$stringB)) {
echo "Blue";
$counter = $counter + 30; //stop if triggered
}
elseif (stristr($data,$stringO)) {
echo "Orange";
$counter = $counter + 30; //stop if triggered
}
else {
//increment loop counter
$counter = $counter + 1;
//Insert pause
sleep(10);
}
}
?>
You should open the file before your read loop, and close it after the loop. As in :
open the file
loop through the lines in the file
close the file
Also, if you clear the file before you read it, isn't it going to be empty every time?
Well, first of all, you don't need to "clear" the file this way... The "w" option in fopen will already do that for you.
Also, I wouldn't try to read the whole file at once, because, if it's very large, that won't work without intense memory usage.
What you should do is read the file sequentially, which means you always read a fixed amount of bytes and look for the keywords. To avoid losing keywords which are cut in half by your reading mechanism, you could make your reads overlay a bit (the length of your longest keyword-1), to solve that problem.
Then you should modify your while loop so that it also checks if you are at the end of the file ( while(!feof($fh)) ).
PS: It has been mentioned that you clear your file before reading it. What I understood is that your file gets a lot of input really fast, so you expect it to already have content again when you reopen it. If that's not the case, you really need to rethink your logic ;)
PPS: You don't need to abort your while loop by incrementing your counter variable past the boundaries you define. You can also use the break-keyword.
You haven't included the code which deletes the file in the while loop, so it only clears the file once. Also, I'd use unlink($statusFile); to delete the file.
You should rather use for cycle. And to your problem - you clear the file, then get the data from it. Try dumping this $data, you'll end up with string(0) "" for sure. First, save the data, then clear the file.
Edit: If you are changing the file in the loop itself in another thread, there's another problem. You should look after anatomic file stream. For example, you can use Nette SafeStream class.

Categories