I want to check multiple files at once if they exist or not. I want to show a text if any of these files exists:
$filepre = ''.$br.'/filethumb/'.$name.'.jpg';
$filess = ''.$br.'/ss/'.$name.'.jpg';
$filess1 = ''.$br.'/ss/'.$name.'1.jpg';
$filess2 = ''.$br.'/ss/'.$name.'2.jpg';
$filess3 = ''.$br.'/ss/'.$name.'3.jpg';
$filess4 = ''.$br.'/ss/'.$name.'4.jpg';
$filess5 = ''.$br.'/ss/'.$name.'5.jpg';
$filess6 = ''.$br.'/ss/'.$name.'6.jpg';
$filess7 = ''.$br.'/ss/'.$name.'7.jpg';
$filess8 = ''.$br.'/ss/'.$name.'8.jpg';
$filess9 = ''.$br.'/ss/'.$name.'9.jpg';
Then I want to check if any of these files exist or not. If 1 of these 10 files exists then show a text "Screenshots:". If no file exists then nothing will be shown.
I tried:
if (file_exists($filess or $filess1 or $filess2 or $filess3 or $filess4 or $filess5 or $filess6 or $filess7 or $filess8 or $filess9)){
echo 'Screenshots';
}
Did I do anything wrong that it's not working?
Put your filenames in an array and loop through:
$files = array('file_name_1', 'file_name_2'...);
foreach($files as $file){
if(file_exists($file)){
echo "screenshots";
break;
}
}
I would use an array, filter it and check if it is empty or not:
$files[] = $br.'/ss/'.$name.'1.jpg';
$files[] = $br.'/ss/'.$name.'2.jpg';
//etc...
if(array_filter($files, 'file_exists')) {
echo "Screenshots:";
}
This is extendable as you can compare the count() of the result to see if 2, 3, 4, etc.. exist or if the count equals the count of the original array.
You need to rearrange the checking in the if condition,
if (file_exists($filess) or file_exists($filess1) or file_exists($filess2) or file_exists($filess3) or file_exists($filess4) or file_exists($filess5) or file_exists($filess6) or file_exists($filess7) or file_exists($filess8) or file_exists($filess9)){
echo 'Screenshots';
}
Only if you don't want to use array and looping.
Related
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
I have a function to upload multiple files. I use two foreach to upload the files. In the first foreach, I loop the uploaded file,
$j_upl = count($my_upload["name"]);
$isUploaded = 0;
$files = $_FILES;
for($i=0;$i<$j_upl;$i++){
$random_name = substr($my_upload["name"][$i],0,-4)."_".date("ymdhis").$i.substr($my_upload["name"][$i],-4);
$this->load->library('upload', $config);
$_FILES['upload_act']['name'] = $files['upload_act']['name'][$i];
$_FILES['upload_act']['type'] = $files['upload_act']['type'][$i];
$_FILES['upload_act']['tmp_name'] = $files['upload_act']['tmp_name'][$i];
$_FILES['upload_act']['error'] = $files['upload_act']['error'][$i];
$_FILES['upload_act']['size'] = $files['upload_act']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('upload_act');
}
In the $random_name, I use .date("ymdhis") to be added to the file_name. So, the file will be renamed to the file name."_".datetime uploded.
In the second foreach, I use this to insert the $random_name into the database.
foreach($details as $rows){
$file_name = substr($rows['val_upl'],0,-4)."_".date("ymdhis").$ii.substr($rows['val_upl'],-4);
$dt_act['UPL_FILENAME'] = ($rows['val_upl'] == "") ? NULL : $file_name.$ii;
$this->MProject->ins_activity_m($dt_act);
$ii += 1;
}
I use the same method to get the $file_name. If I upload around 2-3 files, the $file_name is matching the $random_name. But, if there are more files to upload, it begins to not match the $random_name because the second in ('Ymdhis') is different.
What is the best method to get the $random_name match the $random_name so the inserted file_name is matching the uploaded file_name?
Note:
I may added something to the file_name, but I prefer not to remove anything (the datetime format should exist)
The easiest way to solve this is to create an associate array in the first for loop with the required information passed in as key-value pairs. You don't need to loop through this object as you can use keys that you already know the values of within your loop like an existing filename to access the values like below...
$file_uploads = array();
for($i=0;$i<$j_upl;$i++){
$random_name = substr($my_upload["name"][$i],0,-4)."_".date("ymdhis").$i.substr($my_upload["name"][$i],-4);
$file_uploads[$my_upload["name"][$i]] = array(
'new_name' => $random_name,
'some_other_value' => $some_other_var
);
$this->load->library('upload', $config);
$_FILES['upload_act']['name'] = $files['upload_act']['name'][$i];
$_FILES['upload_act']['type'] = $files['upload_act']['type'][$i];
$_FILES['upload_act']['tmp_name'] = $files['upload_act']['tmp_name'][$i];
$_FILES['upload_act']['error'] = $files['upload_act']['error'][$i];
$_FILES['upload_act']['size'] = $files['upload_act']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('upload_act');
}
foreach($details as $rows){
$file_name = $file_uploads[substr($rows['val_upl']]['new_name'];
$dt_act['UPL_FILENAME'] = ($rows['val_upl'] == "") ? NULL : $file_name.$ii;
$this->MProject->ins_activity_m($dt_act);
$ii += 1;
}
please note i've not tested this and i'm coding blind here but that should be enough to get you there.
If you need to capture the exact file names from the first loop, why not build an array within the first loop that just stores the file names? Then you can reference the array by the value of $rows rather than attempt to rebuild the names. (It also depends on what's between these two loops.)
I have a database files for holding details about files in different folders and the field flink holds the path of the file.Now i want to run a search both in the folder and database and find the files that are not listed in the database.Is this possible using PHP MYSQL.I have written a sample code but it doesnt seem to work.Please note that files folder contains number of subdirectories as well.
<?php
include("dbfiles.php");
$directory='files/';
// Query database
$query = 'SELECT `flink` FROM `files`';
$result = mysqli_query($fmysqli, $query);
$db = []; // create empty array
while ($row = mysqli_fetch_row($result))
array_push($db, $row[0]);
// Check files
$files1 = scandir($directory);
if ( $files1 !== false ) {
foreach ($files1 as $i => $value) {
if (in_array($value, $db)) {
// File exists in both
echo ' Exists '.$value;
} else {
// File doesn't exist in database
echo ' Not Exists '.$value;
}
}
} else {
echo 0;
}
?>
The result is something unexpected there is a file inside BT363 Folder the path is as follows files/BT363/BT363-Metabolic Engineering and Synthetic Biology-Class Slide--Module 4-admin-admin.pptx
But i am getting the output as
Not Exists . Not Exists .. Not Exists BT363
You can list all the files in a directory by doing this:
$files = scandir($path);
Then query your database for the file information you want and then loop through it and compare the current iteration and find that value in $files.
Yes, it is possible.
Due to the extreme lack of specific detail in your question, my response is going to be equally non-specific.
You'll want to compile a list of files from your folder using glob, scandir or similar. Likewise you will want to compile a list of files in the database.
Compare the two to identify those in the folder, but not in the database.
Edit
The output you're getting . and .. are because filesystems have links to the current (.) and parent (..) directory. Typically you write code to skip these values.
For example, taking your code:
$files1 = scandir($directory)
if ($files1) {
foreach ($files1 as $value) {
if (in_array($value, ['.', '..'])) continue;
// Your other code...
}
}
Ok, I don't fully understand what I'm doing here, so I thought I'd get some feedback on my code.
Trying to recursively search through specific folders on my server, and return the 30 newest *.jpg images that were added (with full filepath).
At the moment my current code gives me (I'm assuming) timestamps (they each look like a string of 10 numbers), and actually I seem to only be getting 22 out of the full 30 I was expecting. I saw another post using directoryIteratorIterator, but I'm not able to upgrade my PHP version for my server and I can't find a lot of clear documentation on that.
Hoping someone can steer me in the right direction on this.
<?php
function get30Latest(){
$files = array();
foreach (glob("*/*.jpg") as $filename) { //I assume "*/*.jpg" would start from the root of the server and go through each directory looking for a match to *.jpg and add to $files array
$files[$filename] = filemtime($filename);
}
arsort($files); //I may not need this since I'm looking to sort by earliest to latest (among the 30 newest images)
$newest = array_slice($files, 0, 29); //This should be the first 30 I believe.
foreach ($newest as $file){ //Assuming I would loop through the array and display the full paths of these 30 images
echo $file . "</br>"; //Returns something similar to "1451186291, 1451186290, 1451186290, etc..."
}
}
?>
You are on a good way. This should work for you:
First of all we create a RecursiveDirectoryIterator which we pass to our RecursiveIteratorIterator so we have an iterator to iterate recursively through all files of your specified path. We filter everything expect *.jpg files out with a RegexIterator.
Now we can convert the iterator into an array with iterator_to_array(), so we can sort the array as we want to. Which we do with usort() combined with filectime() so we compare the creation date of the files and sort it by that.
At the end we can just slice the 30 newest files with array_slice() and we are done. Loop through the files and display them.
Code:
<?php
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("your/path"));
$rgIt = new RegexIterator($it, "/^.+\.jpg$/i");
$files = iterator_to_array($rgIt);
usort($files, function($a, $b){
if(filectime($a) == filectime($b))
return 0;
return filectime($a) > filectime($b) ? -1 : 1;
});
$files = array_slice($files, 0 , 30);
foreach($files as $v)
echo $v . PHP_EOL;
?>
I think what you may want to do is keep you function more general, incase you want to use it's function(s) for other uses or just plain change it. You won't have to then create a get10Latest() or get25Latest(), etc. This is just a simple class that contains all the script that you need to fetch and return. Use what you want from it, the methods are in order of use, so you could just take out the guts of the methods to create one big function:
class FetchImages
{
private $count = 30;
private $arr = array();
private $regex = '';
public function __construct($filter = array('jpg'))
{
// This will create a simple regex from the array of file types ($filter)
$this->regex = '.+\.'.implode('|.+\.',$filter);
}
public function getImgs($dir = './')
{
// Borrowed from contributor notes from the RecursiveDirectoryIterator page
$regex = new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir)),
'/^'.$this->regex.'$/i',
RecursiveRegexIterator::GET_MATCH);
// Loop and assign datetimes as keys,
// You don't need date() but it's more readable for troubleshooting
foreach($regex as $file)
$this->arr[date('YmdHis',filemtime($file[0]))][] = $file[0];
// return the object for method chaining
return $this;
}
public function setMax($max = 30)
{
// This will allow for different returned values
$this->count = $max;
// Return for method chaining
return $this;
}
public function getResults($root = false)
{
if(empty($this->arr))
return false;
// Set default container
$new = array();
// Depending on your version, you may not have the "SORT_NATURAL"
// This is what will sort the files from newest to oldest
// I have not accounted for empty->Will draw error(s) if not array
krsort($this->arr,SORT_NATURAL);
// Loop through storage array and make a new storage
// with single paths
foreach($this->arr as $timestamp => $files) {
for($i = 0; $i < count($files); $i++)
$new[] = (!empty($root))? str_replace($root,"",$files[$i]) : $files[$i];
}
// Return the results
return (!$this->count)? $new : array_slice($new,0,$this->count);
}
}
// Create new instance. I am allowing for multiple look-up
$getImg = new FetchImages(array("jpg","jpeg","png"));
// Get the results from my core folder
$count = $getImg ->getImgs(__DIR__.'/core/')
// Sets the extraction limit "false" will return all
->setMax(30)
// This will strip off the long path
->getResults(__DIR__);
print_r($count);
I don't really need a giant, flexible class of functions. This function will always output the 30 latest images. If I'm understanding correctly, you're assigning a timestamp as a key to each file in the array, and then sorting by the key using krsort? I'm trying to pull out just those pieces in order to get an array of files with timestamps, sorted from latest to oldest, and then slice the array to just the first 30. Here's just a quick attempt as a talking point (not complete by any means). At the moment its outputting only one file several hundred times:
<?php
function get30Latest(){
$directory = new RecursiveDirectoryIterator('./');
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, '/^.+\.jpg$/i', RecursiveRegexIterator::GET_MATCH);
foreach($regex as $file){
$tmp->arr[date('YmdHis',filemtime($file[0]))][] = $file[0];
krsort($tmp->arr,SORT_NATURAL);
foreach($tmp->arr as $timestamp => $files) {
for($i = 0; $i < count($files); $i++)
$new[] = (!empty($root))? str_replace($root,"",$files[$i]) : $files[$i];
echo $new[0] . "</br>"; //this is just for debugging so I can see what files
//are showing up. Ideally this will be the array I'll
//pull the first 30 from and then send them off to a
//thumbnail creation function
}
}
}
?>
So what i am trying to do is get a list of text files from a directory.
take that list and randomly choose 1 file.
then take that file and print out the contents. now i did this a few years back. but can't find my old script. i tried what i have below just to print out a file name.. but event that is not working?
$path = '/seg1';
$files = scandir($path);
$seg = array ( $files );
$rand_keys = array_rand($seg, 1);
print $rand_keys;
Would love some new eyes on this as well as any input.
/*** Search All files in Dir. with .txt extension ***/
foreach (glob('./seg1/*.txt') as $filename)
{
$myFiles[] = $filename;
/*** Array of file names **/
}
/*** Total count of files ***/
$max=sizeof($myFiles);
/*** Select a Random index for Array with Max limit ***/
$fileNo=rand(0, $max);
/*** Path of the Random file to Access ***/
$file=$myFiles[$fileNo];
/*** Get the content from Text file ****/
$data = file_get_contents($file, true);
As your variable naming suggests, you randomly select one key out of the array; try getting the value by
$filename = $seg[$rand_keys];
$path = '/seg1';
$files = scandir($path));
if($files)
echo file_get_contents($files[mt_rand(2,count($files))]);
Recommend you use glob so you only get files you want, this excludes system directories like . and ..
foreach (glob("seg1/*.txt") as $filename) {
$seg[] = $filename;
}
Or an even simpler solution:
$rand_keys = array_rand(glob("seg1/*.txt"), 1);