Before you asked, I did look at all the similar topics and did not not find the solution to my problem. When I try to upload multiple files, say 4, 3 files are uploaded. I am really sure the loop is correct, but i could be wrong. Self-taught PHP newbie.
The code is as follows:
if(isset($_POST['submit']) && $_POST['submit']=="Upload"){
if(count($_FILES['image_filename']['name']) == 0)
{
$form->seterror("fileupload"," * At least one file required.");
}
if($form->num_errors == 0)
{
$directory="../../images/properties";
$ref='';
//Loop through each file
for($i=0; $i<count($_FILES['image_filename']['name']); $i++)
{
if($_FILES['image_filename']['name'][$i] != "")
{
//Get the temp file path
$filename = $_FILES['image_filename']['name'][$i]; // filename stores the value
$filename = str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line
$filename = stripslashes($filename); // strip file_name of slashes
$filename = str_replace("'","",$filename); //remove quotes
$filesize = $_FILES['image_filename']['size'][$i];
$filetype = $_FILES['image_filename']['type'][$i];
$filetemp = $_FILES['image_filename']['tmp_name'][$i];
//echo $filename.'<br>';
$filework->file_upload($_FILES['image_filename']['name'][$i],$directory,$_FILES['image_filename']['tmp_name'][$i]); // this is my File upload class
$ref=$_FILES['image_filename']['name'][$i];
if($countImg == 0) {
if($i==0) {
$main='1';
} else {
$main='0';
}
} else {
$main='0';
}
$q="INSERT INTO property_images(property_id,image_filename,image_reference,main_image)".
" VALUES (".$_GET['pid'].",'".$_FILES['image_filename']['name'][$i]."','".$ref."','".$main."')";
//echo $q.'<br>';
$database->query($q) or die(mysql_error());
$x++;
}
}
}
}
[/code]
Isn't the loop skipping the last file?
Try changing this:
for($i=0; $i<count($_FILES['image_filename']['name']); $i++)
to:
for($i=0; $i<=count($_FILES['image_filename']['name']); $i++)
Related
file.csv structure:
Before uploading to folder upload, I want to check the column.
The algorithm is like:
if ((column 1 = 'no') && (column 2 = 'product_name') && (column 3 = 'product_price') && (column 4 = 'qty'))
{
upload();
}
else
{
die;
}
Is there any coding for this case using php coding or sql to validate?
We have to load the csv file in location and fetch the csv files content and validate the content.
Here is my example:
$destination=C:\Users\AIT\Desktop\SC MArgins new.csv;
$contents = file ($destination);
for($i=1; $i<sizeof($contents); $i++)
{
$line = trim($contents[$i],'",');
$arr = explode(',',$line);
if($arr[0]=='')
{
$rows.='Item#,';
}
if($arr[1]=='')
{
$rows.='Product Name,';
}
if($arr[2]=='')
{
$rows.='Product Code,';
}
if($arr[3]=='')
{
$rows.='Product Grade,';
}
if($rows!=''){
$row1.='Row '.$i.'-'. $rows.'can not be empty'."<br>";}
$k.=$row1;
}
if($k!='' ){
$common->setMsg($row1, 'box_warning');
return false;
}
This code will help u to get which column is missing. Follow this code and let me know if any issues on processing the csv
At Prestashop when I remove some products, the images remains at their directory /img/p/ so at the moment my images directory it's close to being 2GB.
Found this script to delete useless and BBDD unlinked images on Prestashop but I don't know why It's only detecting the orphan images but not removing them. Maybe the unlink function is disabled on the php configuration? Is it possible? Or the code is wrong? Is there another way to do this kind of cleanup?
<?php
// root path of the shop
$shop_root='/home/myweb/public_html/';
// limit number of image files to check, set to 10 for testing
$limit=1000000000;
include $shop_root . '/config/settings.inc.php';
$pdo = new PDO( 'mysql:host='._DB_SERVER_.';dbname='._DB_NAME_, _DB_USER_, _DB_PASSWD_ );
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$r=$pdo->query('select count(1) cnt from ps_image')->fetch();
echo 'count images database: '.$r['cnt'] . "<Br />";
// reset some counters
$cnt_files=0;
$cnt_checked=0;
$cnt_not_found=0;
$cnt_found=0;
for($ii=1; ($ii<=9) && ($cnt_files != $limit); $ii++)
{
$path=$shop_root.'img/p/'.$ii;
delImage($path);
for($jj=0; ($jj<=9) && ($cnt_files != $limit); $jj++)
{
$path=$shop_root.'img/p/'.$ii.'/'.$jj;
delImage($path);
for($kk=0; ($kk<=9) && ($cnt_files != $limit); $kk++)
{
$path=$shop_root.'img/p/'.$ii.'/'.$jj.'/'.$kk;
delImage($path);
for($ll=0; ($ll<=9) && ($cnt_files != $limit); $ll++)
{
$path=$shop_root.'img/p/'.$ii.'/'.$jj.'/'.$kk.'/'.$ll;
delImage($path);
}
}
}
}
echo 'files: '.$cnt_files.' checked: '.$cnt_checked.' not_found: '.$cnt_not_found.' found: '.$cnt_found;
function delImage($imageDir)
{
global $limit, $pdo, $cnt_files, $cnt_checked, $cnt_not_found, $cnt_found;
if ($handle = #opendir($imageDir)) { //# is wriiten to avoid warning message and is handled in else condition
echo $imageDir."<BR />";
while ($cnt_files != $limit && false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$cnt_files++;
$pi = explode('-',$entry);
if($pi[0]>0 && !empty($pi[1])) {
$cnt_checked++;
if(!checkExistsDb($pdo,$pi[0])) {
$cnt_not_found++;
echo 'rm '.$imageDir.'/'.$entry."<BR />";
unlink($imageDir.'/'.$entry);
} else {
$cnt_found++;
}
}
}
}
closedir($handle);
}
else
{
echo $imageDir." doesn't exist".'<BR />';
}
}
function checkExistsDb($pdo, $id_image) {
$r=$pdo->query($q='select \'ok\' ok, (select id_image from ps_image where id_image = '.(int)$id_image.') id_image');
$row=$r->fetch();
if($row['ok']!='ok') die( 'Problem with query, please correct');
return $row['id_image']?true:false;
}
?>
Here's an output piece:
/home/myweb/public_html/img/p/9/9/7
/home/myweb/public_html/img/p/9/9/7/0 doesn't exist
/home/myweb/public_html/img/p/9/9/7/1 doesn't exist
/home/myweb/public_html/img/p/9/9/7/2 doesn't exist
/home/myweb/public_html/img/p/9/9/7/3 doesn't exist
/home/myweb/public_html/img/p/9/9/7/4 doesn't exist
/home/myweb/public_html/img/p/9/9/7/5 doesn't exist
/home/myweb/public_html/img/p/9/9/7/6 doesn't exist
/home/myweb/public_html/img/p/9/9/7/7 doesn't exist
/home/myweb/public_html/img/p/9/9/7/8 doesn't exist
/home/myweb/public_html/img/p/9/9/7/9 doesn't exist
/home/myweb/public_html/img/p/9/9/8
/home/myweb/public_html/img/p/9/9/8/0 doesn't exist
/home/myweb/public_html/img/p/9/9/8/1 doesn't exist
/home/myweb/public_html/img/p/9/9/8/2 doesn't exist
/home/myweb/public_html/img/p/9/9/8/3 doesn't exist
/home/myweb/public_html/img/p/9/9/8/4 doesn't exist
/home/myweb/public_html/img/p/9/9/8/5 doesn't exist
/home/myweb/public_html/img/p/9/9/8/6 doesn't exist
/home/myweb/public_html/img/p/9/9/8/7 doesn't exist
/home/myweb/public_html/img/p/9/9/8/8 doesn't exist
/home/myweb/public_html/img/p/9/9/8/9 doesn't exist
/home/myweb/public_html/img/p/9/9/9
/home/myweb/public_html/img/p/9/9/9/0 doesn't exist
/home/myweb/public_html/img/p/9/9/9/1 doesn't exist
/home/myweb/public_html/img/p/9/9/9/2 doesn't exist
/home/myweb/public_html/img/p/9/9/9/3 doesn't exist
/home/myweb/public_html/img/p/9/9/9/4 doesn't exist
/home/myweb/public_html/img/p/9/9/9/5 doesn't exist
/home/myweb/public_html/img/p/9/9/9/6 doesn't exist
/home/myweb/public_html/img/p/9/9/9/7 doesn't exist
/home/myweb/public_html/img/p/9/9/9/8 doesn't exist
/home/myweb/public_html/img/p/9/9/9/9 doesn't exist
files: 29013 checked: 22290 not_found: 0 found: 22290
Try this. I spent a lot of time to develop this after many failures from different solutions. For me it is the safest method.
<?php
####PUT THIS FILE INTO YOUR MAIN SHOP FOLDER####
// root path of the shop, almost no one needs to change something here.
$shop_root = $_SERVER['DOCUMENT_ROOT']."/"; // need to have slash / at the end
$image_folder = 'img/p/'; // also needs slash at the ennd
$scan_dir = $shop_root.$image_folder;
include_once($shop_root.'config/config.inc.php');
include $shop_root . 'config/settings.inc.php';
#---------------------------------------------#
$last_id = (int)Db::getInstance()->getValue('
SELECT id_image FROM '._DB_PREFIX_.'image ORDER BY id_image DESC
');
$counted_images = Db::getInstance()->executeS('
SELECT count(*) as qnt FROM '._DB_PREFIX_.'image
');
$counted_images = (int)$counted_images[0]['qnt'];
echo 'There was '.$last_id.' images in database but only '.$counted_images.' is used right now. Lets check how many of them are eating up our storage without no reason.<br>';
//$limit = 150; // for testing
$limit = $last_id; // for production
$removed_images = 0;
for ($i=1; $i <= $limit; $i++) {
if (!imageExistsInDB($i)){
$imageDir = str_split($i);
$imageDir = implode('/', $imageDir);
$path = $scan_dir.$imageDir;
deleteImagesFromPath($path);
}
}
function deleteImagesFromPath($path) {
global $removed_images;
$images = glob($path . '/*.{jpg,png,gif,jpeg}', GLOB_BRACE);
if ($images){
foreach ($images as $file) {
if (is_file($file)) {
unlink($file);
}
}
$removed_images++;
echo 'Deleted images from folder ' . $path . '/' ."<br/>";
}
}
function imageExistsInDB($id_image){
return Db::getInstance()->getValue('
SELECT id_image FROM '._DB_PREFIX_.'image WHERE id_image = '.(int)$id_image
);
}
echo '--------------------------------------<br>';
if ($removed_images > 0)
echo 'Hurray! We removed '.$removed_images.' product images!';
else
echo 'Everything is ok with Your images. I did not removed any of them or I made it before. Good Job Presta!';
Check the files permissions. If php user has not permissions to delete files of other users the function unlink will not work.
It will never work because you remove the root of your path:
you remove: /home/myweb/public_html/img/p/9/9/7
and after you want to remove: /home/myweb/public_html/img/p/9/9/7/0 but /home/myweb/public_html/img/p/9/9/7 doesn't exist :)
To work do this:
for($ii=1; ($ii<=9) && ($cnt_files != $limit); $ii++)
{
$pathRacine=$shop_root.'img/p/'.$ii;
//delImage($path);
for($jj=0; ($jj<=9) && ($cnt_files != $limit); $jj++)
{
$path1=$shop_root.'img/p/'.$ii.'/'.$jj;
//delImage($path);
for($kk=0; ($kk<=9) && ($cnt_files != $limit); $kk++)
{
$path2=$shop_root.'img/p/'.$ii.'/'.$jj.'/'.$kk;
//delImage($path);
for($ll=0; ($ll<=9) && ($cnt_files != $limit); $ll++)
{
$path3=$shop_root.'img/p/'.$ii.'/'.$jj.'/'.$kk.'/'.$ll;
delImage($path3);
}
delImage($path2);
}
delImage($path1);
}
delImage($pathRacine);
}
And do not use the same variable name everywhere
For your information, when you delete the product Prestashop automatically delete all the images associated with the product.
I have also checked your script and it worked fine for me by changing $shop_root and adding configuration file.
require(dirname(__FILE__).'/config/config.inc.php');
// root path of the shop
$shop_root = $_SERVER['DOCUMENT_ROOT']."/";
You need to check folder permission and check why it's not allowing to unlink images.
How may i able to retrieve different file extensions in a certain directory. Let say i have a folder named "downloads/", where inside that folder are different types of files like PDFs, JPEGs, DOC files etc. So in my PHP code i wanted those files be retrieved and listed with there file names and file extensions. Example: Inside "downloads/" folder are different files
downloads/
- My Poem.doc
- My Photographs.jpg
- My Research.pdf
So i wanted to view those files where i can get there file names, file extensions, and file directories. So in view will be something like this
Title: My Poem
Type: Document
Link: [url here]
Title: My Photographs
Type: Image
Link: [url here]
Title: My Research
Type: PDF
Link: [url here]
Anyone knows how to do it in php? Thanks a lot!
It's pretty simple. To be honest i don't know why didn't you searched on a php.net. They got whole lots of examples for this. Check it in here: click
Example:
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
//---------------------------------------------------------//
// - SECTION 1 - //
// Actions to be performed on ALL ITEMS //
//----------------- Begin Editable ------------------//
$entry['modtime'] = filemtime($path);
//----------------- End Editable ------------------//
do if (!is_dir($path)) {
//---------------------------------------------------------//
// - SECTION 2 - //
// Actions to be performed on FILES ONLY //
//----------------- Begin Editable ------------------//
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
//----------------- End Editable ------------------//
break;
} else {
//---------------------------------------------------------//
// - SECTION 3 - //
// Actions to be performed on DIRECTORIES ONLY //
//----------------- Begin Editable ------------------//
//----------------- End Editable ------------------//
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
// Output each opened file and then close
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>
You could use glob & pathinfo:
<?php
foreach (glob(__DIR__.'/*') as $filename) {
print_r(pathinfo($filename));
}
?>
You will try this code :
$Name = array();
$ext = array();
$downloadlink = array();
$dir = 'downloads'
while ($file= readdir($dir))
{
if ($file!= "." && $file!= "..")
{
$temp = explode(".",$file);
if (count($temp) > 1)
{
$Name[count($Name)] = $temp[0];
swich($ext)
{
case "doc" :
{
$ext[count($ext)] = "Document";
break;
}
[...]
default :
{
$ext[count($ext)] = "Error";
break;
}
}
$downloadlink[count($downloadlink)] = "http://yourdomain.com/".$dir."/".$file;
}
}
}
closedir($dir);
for($aux = 0; $aux < count($Name); $aux++)
{
echo "Name = " . $Name[$aux]."<br />
Type = " . $ext[$aux]."<br/>
Link = " . $downloadlink[$aux]."<br/>
";
}
I have a file uploader and I want the filenames to auto increment number. I don't feel the need to use a database to do this and I want to keep the code relatively clean, I'm pretty new in file upload and management in PHP so I'm not exactly sure what to do. Could anyone direct me in the right path?
Here is my current code, it just uses an md5 of a bunch of seeds.
<?php
if(isset($_FILES['imagedata']['tmp_name']))
{
// Directory related to the location of your gyazo script
$newName = 'images/' . substr(md5(rand() . time()), 0, 20) . '.png';
$tf = fopen($newName, 'w');
fclose($tf);
move_uploaded_file($_FILES['imagedata']['tmp_name'], $newName);
// Website
echo 'http://davidknag.com/' . $newName;
}
?>
<?php
if(isset($_FILES['imagedata']['tmp_name'])) {
// Directory related to the location of your gyazo script
$fileCount = count (glob ('images/*.png'));
$newName = 'images/' . ( $fileCount + 1) . '.png';
$tf = fopen($newName, 'w');
fclose($tf);
move_uploaded_file($_FILES['imagedata']['tmp_name'], $newName);
// Website
echo 'http://davidknag.com/' . $newName;
}
It just counts all .png files in the directory, increments that number by 1 and uses that as its filename.
Note that if you're storing a very large amount of files (say 10.000s), it's faster to use Joseph Lusts' method, but otherwise this will work jus tfine.
You can just have a basic text file in the given folder. Store the number in there. Read it out and increment it as needed.
It would be easiest to make a function like getNextNumber() that did the above and then you could use it as needed. You could also do this in a $_SERVER[] variable, but it would need to be reloaded from the file on server restart.
<?PHP
// a basic example
function getNextNumber() {
$count = (int)file_get_contents('yourFile.txt');
$count+=1;
file_put_contents('yourFile.txt',$count);
return $count;
}
?>
Note that if you are using this a great deal, you'll need a more advanced sequence generator since this will perform 2 file IO's on each call.
You can try the code below. It creates a file with .png extension and unique name in outdir/
$filename = uniqFile('outdir', '.png');
move_uploaded_file($_FILES['imagedata']['tmp_name'], $filename);
function uniqFile($dir, $ext)
{
if (substr($dir, -1, 1) != '/')
{
$dir .= '/';
}
for ($i=1; $i<999999; $i++)
{
if (!is_file($dir . $i . $ext))
{
return $i . $ext;
}
}
return false;
}
A little late in the game but this pair of functions does the trick and follows the familiar format of the filename followed by "(n)" and then the file extension:
incrementFileName() returns the updated filename incremented by 1 with input filename and destination directory. splitLast() is a modification of explode to only split on the last occurrence of some substring.
function incrementFileName($name,$path){
if (!array_search($name,scandir($path))) {
return $name;
} else {
$ext=splitLast($name,".")[1];
$baseFileName=splitLast(splitLast($name,".")[0],"(")[0];
$num=intval(splitLast(splitLast($name,"(")[1],")")[0])+1;
return incrementFileName($baseFileName."(".$num.").".$ext,$path);
}
}
function splitLast($string,$delim) {
$parts = explode($delim, $string);
if (!$parts || count($parts) === 1) {
$before=$string;
$after="";
} else {
$after = array_pop($parts);
$before=implode($delim, $parts);
}
return array($before,$after);
}
When handling upload, set your filename with it:
$fileName = incrementFileName($_FILES['file']['name'], $path);
This will return someFileName(1).jpg or someFileName(2).jpg etc.
function enc($length = "string") {
if(!is_numeric($length) || $length > 255 || $length < 1){
$length = rand("3","6");
}
// $randomID = substr(uniqid(sha1(crypt(md5("".time("ysia", true)."".rand())))), 0, $length);
$randomID = genUnique($length);
$count = 0;
while(glob("$randomID.*") || fetch("select * from `short` where `short` = '$randomID'") || fetch("select * from `images` where `name` = '$randomID'") || glob("img/$randomID.*") || is_numeric($randomID)){
if($count > 20){
$length++;
}
$randomID = genUnique($length);
$count++;
}
return $randomID;
}
this code is pretty old (not even using mysqli), but i figured i'd include it first
<?php
include_once "functions.php";
if(!isset($_REQUEST['api'])){
notfound("");
}
$con = connect();
$key = $_REQUEST['api'];
$ver = $_REQUEST['version'];
if($ver != "10-26-2016" || $key == "zoidberg")
{
die("Please upgrade your in4.us.exe by logging in and clicking download.");
}
if($key == "nokey"){
die("You need to keep the exe with the ini file to pair your api key. Copy ini file to same directory or redownload.");
}
$key = mysql_real_escape_string($key);
$findkey = fetch(" SELECT * from `users` where `key` = '$key' ");
if(!is_array($findkey)){
die("No user with that API Key found. Configure the INI File using your api key on in4.us");
}
$user = $findkey['username'];
if(isset($_FILES['imagedata']['tmp_name'])){
$newName = enc();
$tf = fopen("img/".$newName.".png", 'w');
fclose($tf);
move_uploaded_file($_FILES['imagedata']['tmp_name'], "img/".$newName.".png");
$domain = $_SERVER['HTTP_HOST'];
date_default_timezone_set('America/New_York');
$mysqldate = date("Y-m-d H:i:s");
$qry = mysql_query("INSERT INTO `images` (`name`, `added`, `dateadded`) VALUES ('$newName', '$user', '$mysqldate');");
if(!qry){
die('Invalid query: ' . mysql_error());
}
echo "http://$domain/$newName.png";
disconnect($con);
}else{
notfound("");
}
?>
It is one of the things I should have the know how but it really bugs. I have a large script which automates several tasks. It starts with uploading of files after which data from the files are extracted and then imported into mysql. In debugging mode it works perfectly but on my web front-end, execution stops after the data from the uploaded file is extracted. It never reaches the importation into database phase.
I realised that I had used this particular code below which I hold suspect:
$newFilePath = $upload_directory."/".$inFileName;
//opening the input file
if($inFileName != "")
$inputFile = fopen($newFilePath,"r");
else exit(1);
if(!$inputFile)
exit(0);
while(!feof($inputFile)) {
It is obvious that the exit() as used terminates the scripts thereby leaving out the lines that is handling the import of data into mysql.WIth the above, the upload works and the data separation carried out but the import never got executed. After some study I reviewed that portion by doing something quite appropriate like:
if (file_exists($inFileName)){
$inputFile = fopen($newFilePath,"r");
}
else {
echo "No file found ";
}
if (is_readable($inputFile)){
echo " ";
}else {
echo 'The file could not be read';
}
Now this piece of code review did not get me anyway as the upload is not even possible.
Now my problem is to fix this little portion of the code so I get the other parts of the script after it to do the import. It has been a nightmare for a beginner like me. I would appreciate if someone could review the above portion in a different way. I hope to see something that is similar or different but valid. I have learnt tougher stuff than this but this is simply nuts. I hope someone could understand my explanation. Thanks
New Edit.
if (is_array($inFilesArray)) {
foreach($inFilesArray as $inFileName) {
$numLines = 1;
$newFilePath = $upload_directory."/".$inFileName;
//opening the input file
if (file_exists($newFilePath)){
if (is_readable($newFilePath)){
$inputFile = fopen($newFilePath,"r");
}
} else {
echo "File not accessable";
}
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inputFile)) {
$line = fgets($inputFile);
$lineTokens = explode(',',$line);
// Assign Device ID
switch ($lineTokens[0]){
case "IMEI 358998018395510\r\n":
$device_id = 1;
break;
case "IMEI 352924028650492\r\n":
$device_id = 3;
break;
case '$GPVTG':
$device_id = 2;
break;
}
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile4, $device_id . "," .$line)===FALSE){
echo "Problem writing files\n";
}
$time = $lineTokens[1];
$date = $lineTokens[9];
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(' ',$line);
$searchCriteria2 = array('OutCell');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile5, $time.",".$date."\n")===FALSE){
echo "Problem writing to file\n";
}
}
}
fclose($inputFile);
}
Entire Script
<?php
#This script has threee parts: The first handles the uploaded files while the second part retrieves all RMCs and Handover dates and the 3rd handles importation of the data into their respective table in mysql database.
# This part uploads text files
include 'setamainfunctions.php';
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
//echo count($_FILES['uploadedFile']['name'])." uploaded ";
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode("<br/>", $uploaded_files)."\n";
echo "</br>";
echo "<p> Please find the processed RMCs and corresponding handovers as text files named:outputRMCs.txt and OutputHandovers.txt in the Setapro project root folder</p>";
/* echo "<br/>";
echo "<br/>";
echo "<p> Result of Mobile GPRMCs Transaction";
//echo "Total entries imported:.$numlines . <br/>";
echo "Data extraction and import mobile mobile GPRMCs successfuly completed";
echo "<br/>";
echo "<br/>";
echo "<p> Result of Handover Transaction";
//echo "Total entries imported:.$numlines . <br/>";
echo "Data extraction and imports for mobile handovers successfuly completed";*/
}
# This is the start of a script which accepts the uploaded into another array of it own for extraction of GPRMCs and handover dates.
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
/*if(isset($_FILES['uploadedFile']['name']))
$_FILES['uploadedFile'] = '';
}else {
echo "yes";
}*/
$inFilesArray = ($_FILES['uploadedFile']['name']);
//$inFiles = fopen($_FILES['uploadedFile']['tmp_name'], 'r');
//This opens a textfile for writing operation and puts all the entries from the multiple text files into one distinct textfile
if( ($outFile4 = fopen("outputRMCs.txt", "a")) === false ){
echo " ";
}
$outFile5 = fopen("outputHandovers.txt", "a");
//processing individual files in the array called $inFilesArray via foreach loop
if (is_array($inFilesArray)) {
foreach($inFilesArray as $inFileName) {
$numLines = 1;
$newFilePath = $upload_directory."/".$inFileName;
$correctFile = false;
//opening the input file
if (file_exists($newFilePath)){
if (is_readable($newFilePath)){
$inputFile = fopen($newFilePath,"r");
$correctFile = true;
}
}
if (!$correctFile)
echo "File not accessable";
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inputFile)) {
$line = fgets($inputFile);
$lineTokens = explode(',',$line);
// Assign Device ID
switch ($lineTokens[0]){
case "IMEI 358998018395510\r\n":
$device_id = 1;
break;
case "IMEI 352924028650492\r\n":
$device_id = 3;
break;
case '$GPVTG':
$device_id = 2;
break;
}
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile4, $device_id . "," .$line)===FALSE){
echo "Problem writing files\n";
}
$time = $lineTokens[1];
$date = $lineTokens[9];
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(' ',$line);
$searchCriteria2 = array('OutCell');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile5, $time.",".$date."\n")===FALSE){
echo "Problem writing to file\n";
}
}
}
fclose($inputFile);
}
//close the in files
fflush($outFile4);
fflush($outFile5);
}
fclose($outFile4);
fclose($outFile5);
#End of script for handling extraction
# This is the start of the script which imports the text file data into mysql database and does the necessary conversion.
$FilePath1 = $_SERVER["DOCUMENT_ROOT"] . '/setapro/outputRMCs.txt';
if (is_readable($FilePath1)) {
$handle = fopen($FilePath1, "r");
rmc_handoverHandler($handle);
echo "";
fclose($handle);
} else {
echo 'The file could not be read';
}
#Begining of script to handle imports into handover table
$FilePath2 = $_SERVER["DOCUMENT_ROOT"].'/setapro/outputHandovers.txt';
if (is_readable($FilePath2)) {
$handle = fopen($FilePath2, "r");
mobile_handoverHandler($handle);
echo "";
fclose($handle);
} else {
echo 'The file could not be read';
}
#End of script for handling imports into handover table
?>
It seems to me you want to do something more like this...
$newFilePath = $upload_directory."/".$inFileName;
$goodFile=false;
//Does the file exist?
if (file_exists($newFilePath)){
//If so, is it readable?
if (is_readable($newFilePath)){
//if it exists, and it readable, open it
$inputFile = file_get_contents($newFilePath);
//Don't display the error when done because file is good
$goodFile=true;
//Do Other stuff with file contents
}
}
if (!goodFile) echo "File Access Error";
You want to use newFilePath as it contains the path as well as the file name. The fact that you are checking for the file's existence and readability without also passing the file's path (only the file name) may be the cause of your issues.
UPDATE
try {
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') {
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
} catch (exception $e){
echo "General Error";
}