A peculiar newbie debugging - php

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";
}

Related

PHP - Display differences between two CSV files

I have written a small script which upload two csv files and compare them.
//set files upload directory
$target_dir1 = "uploads/old/";
$target_file1 = $target_dir1 . basename($_FILES["fileToUpload1"]["name"]);
$target_dir2 = "uploads/new/";
$target_file2 = $target_dir2 . basename($_FILES["fileToUpload2"]["name"]);
$uploadOk = 1;
//Upload files
if ($uploadOk == 0) {
echo "<BR> Sorry, your files were not uploaded. <BR>";
} else {
if (move_uploaded_file($_FILES["fileToUpload1"]["tmp_name"], $target_file1)) {
echo "<BR> The 1st file ". basename( $_FILES["fileToUpload1"]["name"]). " has been uploaded. <BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 1st file. <BR>";
}
if (move_uploaded_file($_FILES["fileToUpload2"]["tmp_name"], $target_file2)) {
echo "<BR> The 2nd file ". basename( $_FILES["fileToUpload2"]["name"]). " has been uploaded.<BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 2nd file. <BR>";
}
}
//Get contetnt 1st file
$table1 = Array();
$filehandle1 = fopen($target_file1, "r") ;
if($filehandle1 !== FALSE) {
while(! feof($filehandle1)) { // feof end of file
$data1 = fgetcsv($filehandle1, 1000, ",");
array_push($table1, $data1);
}
}
fclose($filehandle1);
//Get content 2nd file
$table2 = Array();
$filehandle2 = fopen($target_file2, "r") ;
if($filehandle2 !== FALSE) {
while(! feof($filehandle2)) {
$data2 = fgetcsv($filehandle2, 1000, ",");
array_push($table2, $data2);
}
}
fclose($filehandle2);
//Find difference between these two files
$headers= array();
$headers = $table1[0];
$i= 0;
foreach ($table1 as $table) {
echo '<BR>';
$diff = array_diff($table2[$i], $table);
if(!empty($diff)) {
print_r($diff);
$chiave= key($diff);
echo $headers[$chiave];
};
echo '<BR>';
$i++;
}
And this is the error I get, however difference between the two files are dispalyed correctly:
Warning: array_diff(): Argument #1 is not an array in /var/www/csv_files/upload.php on line 67 Call Stack: 0.0053 337384 1. {main}() /var/www/csv_files/upload.php:0 0.0064 367220 2. array_diff() /var/www/csv_files/upload.php:67
You get this error because the first argument is not a array where one is expected. You are now checking a table with the nth element of a array but not the whole array. I think you are making a mistake in thinking table2 is a 2 dimensional array, and it's not. It is used a one dimensional array with nth data2 elements.
Hope this helps!
Seems yes, sometimes table2 is empty or those CSV files have different amount of rows - as result that warning.
So - you need add extra checks if $table2[$i] is not null.
Just a bit another variant from me - how to read file faster (Get content 1st and second file):
$table1 = file($target_file1);
$table2 = file($target_file2);
And then you can do same things as before, with extra tests:
if (count($table1)) {
$headers = str_getcsv($table1[0]);
foreach ($table1 as $key => $table) {
if (!isset($table2[$key])) {
echo 'Row ' . ($key+1) . ' is not exists in second CSV file.';
} else {
$diff = array_diff(str_getcsv($table2[$key]), str_getcsv($table));
// Here is code as in your example
print_r($diff);
$chiave = key($diff);
echo $headers[$chiave];
}
}
}
Good luck! :)

How to read a file line by line in php and compare it with an existing string?

I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>

Strange PHP multiple file upload issue

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++)

upload more than 200 images using php and html input tag

i'm trying upload multiple image files in php.i edited the php.ini and set upload_max_files to 20000.but it only uploads 200 images at one time.any help will be appriciated.
here's my code
if(isset($_FILES['files'])){ $count=0; foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name){
$target="upload/photo/";
$target=$target.$_FILES['files']['name'][$key];
$partphoto = substr("$target", 13, -4);
$qq="select * from idol_student_photo where name='$partphoto'";
$res=mysql_query($qq);
$row=mysql_fetch_array($res);
if(file_exists($target))
{
echo $_FILES['files']['name'][$key]." already exists in photo folder <br />";
}
else if($row['name'])
{
echo $partphoto." already exists database <br />";
}
else
{
if(move_uploaded_file($tmp_name, $target)){
//$id = mysql_insert_id($con);
mysql_query("INSERT INTO tablename VALUES ('$partphoto')");
$count=$count+1;
}
}
}
echo "<center>".$count."file uploaded</center>";
}
It's probably a PHP Limitation. So we can't really help you with that. However; most PHP system do have a zip function. So detect if there are too much pictures in you clientside validation and suggest using the zip method to a user. I haven't tested this code, but should put you in the right direction!
$zip = zip_open("/tmp/youruploaded.zip");
$target="upload/photo/";
if ($zip) {
while ($zip_entry = zip_read($zip)) {
$zipfilename = zip_entry_name($zip_entry);
$target=$target.$zipfilename;
$partphoto = substr("$target", 13, -4);
$qq="select * from idol_student_photo where name='$partphoto'";
$res=mysql_query($qq);
$row=mysql_fetch_array($res);
if(file_exists($target)) {
echo $zipfilename." already exists in photo folder <br />";
} else if($row['name']) {
echo $zipfilename." already exists database <br />";
} else{
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
if (file_put_contents($target, $buf)) {
mysql_query("INSERT INTO tablename VALUES ('$partphoto')");
$count=$count+1;
} else {
echo 'can\'t put picture';
}
}
}
zip_close($zip);
}
Good luck

How to retrieve files on a directory in list using PHP

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/>
";
}

Categories