I want to add some function to download my files that was uploaded some other day. i am not handy with php so i dont know how to add function and generate link for all listed files at time.
here is my php code:-
// Destination folder for downloaded files
$date = date('m.d.y');
mkdir("uploads/" . $date, 0777, true);
$upload_folder = 'uploads/' . $date;
// If the browser supports sendAsBinary () can use the array $ _FILES
if(count($_FILES)>0) {
if( move_uploaded_file( $_FILES['upload']['tmp_name'] , $upload_folder.'/'.$_FILES['upload']['name'] ) ) {
echo 'done';
}
exit();
} else if(isset($_GET['up'])) {
// If the browser does not support sendAsBinary ()
if(isset($_GET['base64'])) {
$content = base64_decode(file_get_contents('php://input'));
} else {
$content = file_get_contents('php://input');
}
$headers = getallheaders();
$headers = array_change_key_case($headers, CASE_UPPER);
if(file_put_contents($upload_folder.'/'.$headers['UP-FILENAME'], $content)) {
echo 'done';
}
exit();
}
Related
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);
}
i am encrypting my pdf but when i open it and enters the password it always says wrong error this is my code:
global $_dompdf_show_warnings;
global $_dompdf_debug;
global $_DOMPDF_DEBUG_TYPES;
$outfile = $id . '_qr_codes.pdf';
$save_file = TRUE; // Save the file or not
$buff = $this->qr_generate_pdf($id);
//echo $buff; die;
$dompdf = new DOMPDF();
$dompdf->load_html($buff);
if (isset($base_path)) {
$dompdf->set_base_path($base_path);
}
$dompdf->render();
$dompdf->get_canvas()->get_cpdf()->setEncryption('admin','ownerpass');
if ($_dompdf_show_warnings) {
global $_dompdf_warnings;
foreach ($_dompdf_warnings as $msg) {
echo $msg . "\n";
}
echo $dompdf->get_canvas()->get_cpdf()->messages;
flush();
}
if ($save_file) {
// if ( !is_writable($outfile) )
// throw new DOMPDF_Exception("'$outfile' is not writable.");
if (strtolower(DOMPDF_PDF_BACKEND) == "gd") {
$outfile = str_replace(".pdf", ".png", $outfile);
}
list($proto, $host, $path, $file) = explode_url($outfile);
if ($proto != "") // i.e. not file://
$outfile = $file; // just save it locally, FIXME? could save it like wget: ./host/basepath/file
//$outfile = dompdf_realpath($outfile);
// if ( strpos($outfile, DOMPDF_CHROOT) !== 0 )
// throw new DOMPDF_Exception("Permission denied.");
file_put_contents($outfile, $dompdf->output(array("compress" => 0)));
}
if (!headers_sent())
$dompdf->stream($outfile);
}
when i enter the password 'ownerpass' in the downloaded pdf it throughs an error-> The Password is incorrect. Please make sure that capslock is not on by mistake,and try again.
Thanks in advance
I have used the following code for saving open docx file.
javascript:
function SavetoServer(){
OA1.Save();
OA1.CloseDoc();
OA1.HttpInit();
OA1.HttpAddPostFile("C:\wamp\www\rte\sample2.docx");
document.OA1.HttpPost("http://localhost/rte/actor2.php");
}
php code "actor2.php"
<?php
header("http/1.1 200 OK");
$handle = fopen($_FILES['trackdata']['name'],"w+");
if($handle == FALSE)
{
exit("Create file error!");
}
$handle2 = fopen($_FILES['trackdata']['tmp_name'],"r");
$data = fread($handle2,$_FILES['trackdata']['size']);
fwrite($handle,$data);
fclose($handle2);
fclose($handle);
exit(0);
?>
The file is not saving when we changed in browser. Can anyone see a problem with this?
The HttpAddPostFile can add only the file from the remote website. It does work for the local disk file.
function SavetoServer()
{
if(document.OA1.IsOpened)
{
document.OA1.SetAppFocus();
document.OA1.HttpInit();
var sFileName = document.OA1.GetDocumentName();
document.OA1.HttpAddPostOpenedFile (sFileName); //save as the same file format with the sFileName then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 16); //save as docx file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 0); //save as doc file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, -4143); //save as xls file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 51); //save as xlxs file then upload
document.OA1.HttpPost("upload_weboffice.php");
if(document.OA1.GetErrorCode() == 0 || document.OA1.GetErrorCode() == 200)
{
var sPath = "Save successfully! You can download it at http://www.ocxt.com/demo/" + sFileName;
window.alert(sPath);
}
else
{
window.alert("you need enable the IIS Windows Anonymous Authentication if you have not set the username and password in the HttpPost method. you need set the timeout and largefile size in the web.config file.");
}
}
else{
window.alert("Please open a document firstly!");
}
}
upload_weboffice.php
<?php
$sql = sprintf("username=%s passwd=%s param=%s", $_POST['user'],$_POST['password'],$_POST['param']);
echo $sql;
$filecount = count($_FILES["trackdata"]["name"]);
echo "\r\n";
echo "file account:";
echo $filecount;
echo "\r\n";
$sql = sprintf("file=%s size=%s error=%s tmp=%s", $_FILES['trackdata']['name'],$_FILES['trackdata']['size'],$_FILES['trackdata']['error'],$_FILES['trackdata']['tmp_name']);
echo $sql;
echo "\r\n";
$filen = $_FILES['trackdata']['name'];
//$filen = iconv("UTF-8", "GBK", $filen);
$handle = fopen($filen,"w+");
if($handle == FALSE)
{
exit("Create file error!");
}
$handle2 = fopen($_FILES['trackdata']['tmp_name'],"r");
$data = fread($handle2,$_FILES['trackdata']['size']);
echo $data;
//file_put_contents($handle, "\xEF\xBB\xBF". $data);
//fwrite($handle,pack("CCC",0xef,0xbb,0xbf));
fwrite($handle,$data);
fclose($handle2);
fclose($handle);
exit(0);
?>
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