I have a file on one application folder of codiginitor and I want to copy that file to another application folder of codignitor in another directory.
I have tried below code but it doesn't seem to be working:
$file = 'http://xxxxxx/jakson_solar/ftp.php';
$newfile = './mobile_image/transfer/';
if ( copy($file, $newfile) ) {
echo "Copy success!"; die;
}else{
echo "Copy failed."; die;
}
is there another way to copy file from one directory to another directory?
copy requires as first parameter an input file and as second parameter an output file
So do it this way
$file = 'path_to/ftp.php';
$newfile = './mobile_image/transfer/ftp.php';
if ( copy($file, $newfile) ) {
echo "Copy success!"; die;
} else {
echo "Copy failed."; die;
}
#dev please find the code below for your needs
// 1 check if your input from the form is not empty
if ((isset($_FILES['file']))){
// 2. files inside the session
$_SESSION['FILES'] = $_FILES;
// 3. your path
$PATH = $_SERVER["DOCUMENT_ROOT"]."/mobile_image/transfer/";
// 4. temporary name -> optional step but recommended
$TEMP_NAME = explode(".",$_FILES["file"]);
// 5. new name of the file
$NAME_NEW = substr(number_format(time() * rand(),0,'',''),0,20) . '.' .end($TEMP_NAME);
$UPLOAD_FILE = $PATH . basename($NAME_NEW);
// 6. check before moving the file that is not empty
if (isset($UPLOAD_FILE)) {
move_uploaded_file($_FILES['file'], $PATH); }
// 7. custom errors
$json = array();
$json['status'] = "OK";
$json['message'] = 'File moved successfully';
echo json_encode($json);
}else{
// 7. custom errors
$json = array();
$json['status'] = "NO FILE";
$json['message'] = 'No files found';
echo json_encode($json);
}
Related
I have the code bellow where I'm creating a new folder and copying some files from another folder, and it's working fine.
Now I need to go on each php file inside new folder and change the word "empty" by some word passed through $_POST["variable"].
Maybe by str_replace but I'm stuck in the logic.
Thanks in advance!
if (!file_exists("/home//public_html/new_conf_folder/"))
{
mkdir("/home//public_html/new_conf_folder/", 0755, true);
$source = "/home/public_html/conf_folder/";
$destination = "/home/public_html/new_conf_folder";
$directory = opendir($source);
while(($file = readdir($directory)) != false)
{
copy($source.'/' .$file, $destination.'/'.$file);
}
}
Try this code its working for me:
// file_process.php
$destination="./"; // Current Directory
if (file_exists($destination))
{
$directory = opendir($destination);
while(($file = readdir($directory)) != false)
{
//echo $file."<br/>";
$contents=file_get_contents($file);
$contents=str_replace("\"empty\"",$_POST['variable'],$contents);
//$contents=str_replace("\"empty\"",$_POST['variable'],$contents); // use this if the word with qouts
//echo $contents;
$bytes_written=file_put_contents($file,$contents);
if($bytes_written>0)echo "File [$file] has been successfully processed.";
else echo "Process Failed.";
}
}
The file does save to the target folder which I can access on the browser and FTP, because when I try to delete the directory it says that the folder is not empty.
I also know they're there, because when I do a scandir(), it lists all the files.
Here is my code:
<?php
$device_name = str_replace(" ","_",strtolower($_POST["device_name"]));
$target_dir = getcwd()."/wedding/";
$target_dir = $target_dir.$device_name."_".time()."_".basename($_FILES["file"]["name"]);
$arr = array();
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
$arr["status"] = 1;
$arr["result"] = "Photo Sent";
} else {
$arr["status"] = 0;
$arr["result"] = "Error Sending Photo";
}
echo json_encode($arr);
?>
Turns out there where special characters in the filename.
Going out of my mind with php unlinking
Here is my delete file script
$pictures = $_POST['data'];
//print_r ($pictures);
$imageone = $pictures[0];
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/" . $imageone;
echo $filename;
if (is_file($filename)) {
chmod($filename, 0777);
if (unlink($filename)) {
echo 'File deleted';
} else {
echo 'Cannot remove that file';
}
} else {
echo 'File does not exist';
}
The above does not work, error response is file does not exist
however if i change the filename path to this (the echo data from the echo above)
$filename = "file:///Users/LUJO/Documents/CODE/REVLIVEGIT/wp-content/uploads/dropzone/1420291529-whitetphoto.jpeg "
works fine and deletes the image.
Why can i not use the $imageone variable?
Do a print_r($pictures) to see if $pictures[0] is indeed the filename you're looking for.
Also note that if $pictures[0] is "//windows/*" you'll loose your windows if the user running PHP has administrative rights... so just using $pictures=$_POST["data"] is very VERY unsafe!
I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
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 "Files successfully uploaded . <br/>" ;
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(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}
hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here