I have a CSV file ( sample.csv ), put in my flashdisk ( drive L: ). I read those file to update my database. I try to run it on localhost, everything works fine.But if the script I uploaded to the internet server, the script is always error. The server can not recognize the disk drive where I put the file (disk drive L:). Here is my first script before :
if (isset($_POST['upload1'])) {
$allowed_ext = array('csv');
$file_name = $_FILES['file']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_path = realpath($_FILES['file']['name']);
if(in_array($file_ext, $allowed_ext) === true){
$handle = fopen($file_path.'/'.$_FILES['file']['name'], "r" );
while (! feof($handle)) {
$import=fgets($handle);
}
fclose($handle);
}
}
Because those script is not going well, then I try to add a few lines to determine the location of faults, this is the complete script:
if (isset($_POST['upload1'])) {
$allowed_ext = array('csv');
$file_name = $_FILES['file']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_path = realpath($_FILES['file']['name']);
if(in_array($file_ext, $allowed_ext) === true){
if (!#fopen($file_path.'/'.$_FILES['file']['name'], 'r')) {
echo $file_path.'/'.$_FILES['file']['name'];
var_dump($php_errormsg);
}else{
$handle = fopen($file_path.'/'.$_FILES['file']['name'], "r" );
while (! feof($handle)) {
$import=fgets($handle);
}
fclose($handle);
}
}
}
From the second script, I know that disk drives are not known because it gives the following message: /SAMPLE.CSV NULL
/SAMPLE.CSV is the output of echo $file_path.'/'.$_FILES['file']['name'];
NULL is the output off var_dump($php_errormsg);
My question is how the script for the program to read the csv file from the drive L: ( L:/SAMPLE.CSV )
Thank you for any advices.
Save the CSV to your server
if (in_array($file_ext, $allowed_ext) === true)
{
move_uploaded_file($_FILES['file']['tmp_name'], '/your/directory/yourfile.csv');
}
Then loop through the CSV as requested
if (($handle = fopen("/your/directory/yourfile.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$fieldOne = trim($data[0]);
$fieldTwo = trim($data[1]);
$fieldThree = trim($data[3]);
// do stuff
}
fclose($handle);
}
After you have done what you need to with you CSV rows then delete the file
unlink('/your/directory/yourfile.csv');
Related
I've read other posts about this error but I couldn't find the one that suit my case.
This is the problem: after uploading a content (text file) on a specific server path (I'm using an Apache local server), I can't read it with the file() function, except when the file is contained also in the main directory (__DIR__).
This is the problematic portion of the script:
$uploaddir = __DIR__.'/cbi_files/';
if (!is_dir($uploaddir))
mkdir($uploaddir);
chmod($uploaddir, 0600);
// Recovering temporary directory
$userfile_tmp = $_FILES['cbi_file']['tmp_name'];
// Recovering originary file's name
$userfile_name = $_FILES['cbi_file']['name'];
$count=0;
$operazione = 0;
$file_caricati = array();
foreach ($_FILES['cbi_file']['name'] as $filename) {
$destination = $uploaddir;
$origin = $_FILES['cbi_file']['tmp_name'][$count];
$count++;
$destination = $destination.basename($filename);
// moving files from temporary directory to destination
$operazione = move_uploaded_file($origin, $destination);
$file_caricati[] = $filename;
}
$file_cbi = array();
$righe = array();
if (is_dir($uploaddir)) {
if ($dh = opendir($uploaddir)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
$righe = file($file, FILE_IGNORE_NEW_LINES); // I get the error on this line
$last_row = count($righe)-1;
include(__DIR__.'/scriptCBI.php');
$file_cbi[] = array(
'nome_file' => $file,
'codice_RH' => $righe[0],
'codice_EF' => $righe[$last_row],
'recs' => $rec_array
);
}
}
closedir($dh);
}
}
I get the error if I keep the file only in $uploaddir = __DIR__'/cbi_files/', but if I keep it both in this directory and in the main directory (__DIR__) it works properly.
How's that possible?
I have a folder and have multiple files over there. The file has the below pattern for example.
The file names should be renamed from
file1.mp4.png
file2.flv.png
file3.xxx.png (xxx - can be anything)
to as follows (the last extension remains).
file1.png
file2.png
file3.png
Files having non-png extension should be left untouched.
I am using the logic mentioned in Bulk Rename Files in a Folder - PHP
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$newName = (how to get new filename) // I am struck here
rename($fileName, $newName);
}
closedir($handle);
}
How best I can do this to do a bulk update?
<?php
// Select all PNG Files
$matches = glob("*.[pP][nN][gG]");
// check if we found any results
if ( is_array ( $matches ) ) {
// loop through all files
foreach ( $matches as $filename) {
// rename your files here
$newfilename = current(explode(".", $filename)).".png";
rename($filename, $newfilename);
echo "$filename -> $newfilename";
}
}
?>
try this
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$arr_names = explode(".", $fileName);
$size = sizeof($arr_names);
$ext = $arr_names[$size-1];
if($fileName=="." || $fileName==".." || is_dir($fileName))
{
continue; // skip png
}
if($ext=='png' || $ext=='PNG')
{
$newName = $arr_names[0].".".$ext;
rename($fileName, $newName);
}
}
closedir($handle);
}
Shortest using regex
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace("/\.(.*?)\.png$/", '', $fileName); // removes .xxx.png
rename($fileName, ($newName . '.png')); // renames file1.png
}
closedir($handle);
}
The code below is uploading and displaying files on the upload.php page and it's working fine. The problem I have is that it's not displaying the files if I copy and paste the url of the upload.php page into a new webpage.
upload.php code
<?php
if (isset($_FILES['file_upload'])) {
$file = $_FILES['file_upload'];
$name = $file['name'];
$type = $file['type'];
$tmp_location = $file['tmp_name'];
$upload = 'uploads';
$final_destination = $upload.'/'.$name;
$error = $file['error'];
$max_upload_size = 2097152;
$size = $file['size'];
$allowedImageTypes = array( 'image/png', 'image/jpeg', 'image/gif', );
function imageTypeAllowed($imageType){
global $allowedImageTypes;
if(in_array($imageType, $allowedImageTypes)){
return true;
}
else{
return false;
}
}
//Check for errors
if($error > 0 || is_array($error)){
die("Sorry an error occured");
}
//Check if file is image
//Only required if image is only whjat we need
if(!getimagesize($tmp_location)){
die("Sorry, you can only upload image types");
}
if(!imageTypeAllowed($type)){
die("Sorry, file type is not allowed");
}
if(file_exists($final_destination)){
$final_destination = $upload.'/'.time().$name;
}
if(!move_uploaded_file($tmp_location, $final_destination)){
die("Cannot finish upload, something went wrong");
}
$handle = opendir('uploads');
if($handle){
while(($entry = readdir($handle)) !== false){
if($entry != '.' && $entry != '..'){
echo "$entry<br>";
}
}
closedir($handle);
}
}
?>
<h2>File Successfully uploaded!</h2>
If you indent your code to be human-readable, you'll find that the entire server-side code block is wrapped in this conditional:
if (isset($_FILES['file_upload'])) {
// all of your code
}
This means that all of that server-side code will execute only if a file_upload value is POSTed to the form. When you copy/paste the URL into a new browser window and invoke that request, you're invoking a GET request with no form values. Since you're not uploading a file in this request, the isset() condition evaluates to false and your code isn't executed.
You should separate your functionality into two groups:
Handling the upload.
Displaying the current state of the data.
The code for handling the upload should execute only when an upload is present. The code for displaying the data should execute always.
If I'm reading your code correctly, all you should need to do is split out the last few parts:
if (isset($_FILES['file_upload'])) {
// the rest of your code
}
$handle = opendir('uploads');
if($handle){
while(($entry = readdir($handle)) !== false){
if($entry != '.' && $entry != '..'){
echo "$entry<br>";
}
}
closedir($handle);
}
I created this code for putting all CSV files located in the folder csvbackup/ into one zip file.
There are no PHP errors and no zip file, only a lot of <br> tags and the output "failed". What am I doing wrong?
$timenow = date("Ymd-Gi");
$timestamp = date_create();
$timestamp = date_timestamp_get($timestamp);
$filepath = 'csvbackup/';
$filename = $timenow.'-'.$timestamp.'.zip';
$zip = new ZipArchive;
if ($zip->open($filepath.$filename) === TRUE) {
if ($handle = opendir($filepath)) {
while (false !== ($file = readdir($handle))) {
if (preg_match('/\.csv$/i', $file)) {
$zip->addFile($filepath.$file, $file);
}
}
}
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
I missed ZIPARCHIVE::CREATE.
if ($zip->open($filepath.$filename, ZIPARCHIVE::CREATE) === TRUE) { ...
It's working now!
I've been trying to change the file extension of all the picture files in a folder using the following snippet:
$dh = opendir('JS2C');
$files = array();
while (($file = readdir($dh)) !== false) {
if($file !== '.' && $file !== '..') {
$file = pathinfo($file);
rename($file, $new . '.jpg');
}
}
I get the following warning messages:
SCREAM: Error suppression ignored for
Warning: rename(ANAZODO.gif,ANAZODO.jpg):
The system cannot find the file specified. (code: 2) in C:\wamp2\www\ckcportal\batch2.php on ...
The folder that contains the files is in the same folder with the PHP script.
you are missing directory for rename
$d = 'JS2C/'
$dh = opendir($d);
while (($file = readdir($dh)) !== false) {
if($file !== '.' && $file !== '..') {
//$file_no_ext = substr($file, 0,strrpos($file,'.'));// before php 5.2
$path_parts = pathinfo($file); // php 5.2
$file_no_ext = $path_parts['filename']; // php 5.2
rename($d.$file, $d.$file_no_ext . '.jpg');
}
}
You have to supply the full path, from the error you are receiving, it looks like you are just giving the file name.
rename('/path/to/old/file', '/path/to/new/file');
And why are you using $file = pathinfo($file);? pathinfo creates an assoc. array from information of $file which should be giving you the full path. If you take this out, it should work.
Unless you need to following:
$info = pathinfo($file);
$path = $info['dirname']
$new_file = $path . '/' . 'newfile.ext';
rename($file, $new_file);