Using Zend framework 2 and saving files to cloud using "Zendservice-rackspace", here is my code for saving the file. The code is saving the file but in text format as when i go the link it show the text format, not the image or pdf format of the file
$fileName = $fileName.'_'.date('Ymd-His').".".$fileExt;
$fileData = file_get_contents($file['tmp_name']);
$rackspace = new Files($user,$key);
if ($rackspace->authenticate()) {
$rackspace->storeObject('Photos', $fileName, $fileData);
if ($rackspace->isSuccessful()) {
$cdnInfo = $rackspace->getInfoCdnContainer($module);
$url = $cdnInfo['cdn_uri_ssl'] . '/' . $fileName;
return $url;
} else{
echo json_encode(array(
'success'=>true,
'msg'=>'File uploading failed to server'));
exit;
}
Related
I've a file called config.ini and the location and contents are
/var/www/private/config.ini
[database]
servername=localhost
username=root
password=root
dbname=database
calling this file in a database connection function. and the location is /var/www/includes/connection.php
function db_connect() {
static $connection;
if (!isset($connection)) {
$config = parse_ini_file("/var/www/private/config.ini",true);
//$config = parse_ini_file("../private/config.ini",true);
print_r($config);
$connection = mysqli_connect($config['servername'], $config['username'], $config['password'], $config['dbname']);
}
if ($connection == false) {
echo 'error';
return mysqli_connect_error();
} else {
return $connection;
}
}
// Connect to the database
$connection = db_connect();
But i'm not getting the values of config.ini or i couldn't print the whole file. Is there any mistake in this code? or anyone has any suggestion?
Finally i find out the mistake!
string values must be in double quotes.
format of .ini file should be like
[database]
servername="localhost"
username="root"
password="root"
dbname="database"
when user select the file then in server side file extension will be removed or rename and uploaded it to the server using php codeigniter library
This should remove your file extension
<?php
$var = "testfile.php";
$explode = explode( '.', $var );
array_pop( $explode);
$var = implode( '.', $explode );
var_dump( $var );
As for uploading you will need to read the manual on file uploading
http://www.codeigniter.com/user_guide/libraries/file_uploading.html
file name can be changed using the following codes:
$your_given_name = time().rand().$_FILES["userfiles"]['name'];
$config['file_name'] = $your_given_name;
for changing extension you can use:
if ($this->upload->do_upload('file_name')) {
$file_data=$this->upload->data();
$new_name_by_you='anything'.$file_data['file_ext'];
$new_path=$file_data['file_path'].$new_name_by_you;
rename($file_data['full_path'], $new_path);
}
rename() is a php built in function. for details please visit http://php.net/manual/en/function.rename.php
I recently just had the same issue, and found it really annoying that even when you specified a file_name in code igniter it would append the file extension. Which i did not want.
Blinkydamo's link is not helpfull, since that is the link i was following in the first place and makes no mention of this dilema, although it does demontrate that it is not possible idrectly through Code Igniter - by ommission of the answer.
I haven't tried md asif rahman's method, but it looks sound.
Alternatively you can just forget about using Code Igniter's upload function, and fall back onto PHPs standard one, which is what I have done :
move_uploaded_file($_FILES['imageFile']['tmp_name'], '/path/'.$filename);
where $filename is the exact name of the file including extension, therefore if none is specified - it wont have one.
it is so easy
change code in
libraries/Upload.php
public function set_filename($path, $filename)
{
if ($this->encrypt_name === TRUE)
{
$filename = md5(uniqid(mt_rand()));
}
if ($this->overwrite === TRUE OR ! file_exists($path.$filename))
{
return $filename;
}
$filename = str_replace($this->file_ext, '', $filename);
$new_filename = '';
for ($i = 1; $i < $this->max_filename_increment; $i++)
{
if ( ! file_exists($path.$filename.$i))
{
$new_filename = $filename.$i;
break;
}
}
if ($new_filename === '')
{
$this->set_error('upload_bad_filename', 'debug');
return FALSE;
}
else
{
return $new_filename;
}
}
Using Cake version 2.4.3 stable
So I am having a time here, I have modified this plug in to save files to the app folder https://github.com/srs81/CakePHP-AjaxMultiUpload/
The uploaded files are being saved to /public_html/app/files
Now the strange thing is, when trying to serve these files to the view, I can read the file name, the file size, but not the file itself, image, pdf, etc.
When I try to access the file via direct url, i get this error :
Error: FilesController could not be found.
How can it be that I can read the file name, the file size, but not the file itself?
There is a need to save the files in the app folder. These files should be protected and therefore only be accessed by users who are logged into the application. I have tried to use cake send file response with no outcome.
Edit : I guess the real question at hand here is how can I read files from APP . DS . 'files' ?
View code :
public function view ($model, $id, $edit=false) {
$results = $this->listing ($model, $id);
$directory = $results['directory'];
$baseUrl = $results['baseUrl'];
$files = $results['files'];
$str = "<dt>" . __("Pictures") . "</dt>\n<dd>";
$count = 0;
$webroot = Router::url("/") . "ajax_multi_upload";
foreach ($files as $file) {
$type = pathinfo($file, PATHINFO_EXTENSION);
$filesize = $this->format_bytes (filesize ($file));
$f = basename($file);
$url = $baseUrl . "/$f";
if ($edit) {
$baseEncFile = base64_encode ($file);
$delUrl = "$webroot/uploads/delete/$baseEncFile/";
$str .= "<a href='$delUrl'><img src='" . Router::url("/") .
"ajax_multi_upload/img/delete.png' alt='Delete' /></a> ";
}
$str .= "<img src='$url' /> ";
$str .= "<a href='$url'>" . $f . "</a> ($filesize)";
$str .= "<br />\n";
}
$str .= "</dd>\n";
return $str;
}
And the upload / save
public function upload($dir=null) {
// max file size in bytes
$size = Configure::read ('AMU.filesizeMB');
if (strlen($size) < 1) $size = 20;
$relPath = Configure::read ('AMU.directory');
if (strlen($relPath) < 1) $relPath = "files";
$sizeLimit = $size * 1024 * 1024;
$this->layout = "ajax";
Configure::write('debug', 0);
$directory = APP . DS . $relPath;
if ($dir === null) {
$this->set("result", "{\"error\":\"Upload controller was passed a null value.\"}");
return;
}
// Replace underscores delimiter with slash
$dir = str_replace ("___", "/", $dir);
$dir = $directory . DS . "$dir/";
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$uploader = new qqFileUploader($this->allowedExtensions,
$sizeLimit);
$result = $uploader->handleUpload($dir);
$this->set("result", htmlspecialchars(json_encode($result), ENT_NOQUOTES));
}
The only real change from the original plug in is changing WWWROOT to APP to make the switch. Saving works fine and lovely. But its just weird that I can read the file name, file size in the view no problem but cannot view an image, pdf, etc.
The problem:
You cannot display files that are outside the webroot via a direct URL - that's the whole point in putting them above the webroot in the first place - to make them NOT directly accessible.
So building the image src path in the controller first (not good practice anyway) won't change the fact that when that path gets to the browser, and it reads the source of the image as trying to pull an image from above webroot, it won't/can't.
The Solution:
The solution is to use a CakePHP's Sending files (what used to be Media Views). Then, you set your img's "src" to a controller/action. In that action, it basically says "display this action as an image" (or pdf, or whatever else).
Path to use in Controller:
took this from one of my apps which is doing exactly the above, and here's the path I used for a file in 'files' (same level as webroot):
file_exists(APP . 'files' . DS . $your_filename)
Create a symbolic link to your folder inside of the webroot ;-)
I am using the file module to get some files from a form locally and upload to another server. When i try to upload large files it gives me timeout error (i have tried changing php.ini but that's not how i want it to work). That's why I am trying to upload the files via ftp functions. However, i cannot get the source path of the file that i just selected to upload (e.g filepath, not uri). I want to pass this filepath into fopen() function as a source. But i keep getting the error: *ftp_nb_fput() [function.ftp-nb-fput]: Can't open that file: No such file or directory in assets_managed_file_form_upload_submit() (line 303 of FILE_DIRECTORY).*
function assets_managed_file_form_upload_submit($form, &$form_state) {
for ($i = 0; $i < $form_state['num_files']; $i++) {
if ($form_state['values']['files_fieldset']['managed_field'][$i] != 0) {
// Make the file permanent.
$file = file_load($form_state['values']['files_fieldset']['managed_field'][$i]);
$local_path = file_create_url($file->uri);
//drupal_set_message(t("file->uri: " . $file->uri . " local path: " . $local_path));
$file->status = FILE_STATUS_PERMANENT;
$directory = 'private://cubbyhouse/'. $form_state['values']['allowed_user'];
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$source = fopen($local_path,"r");
$conn = ftp_connect("FTP SERVER") or die("Could not connect");
ftp_login($conn,"USERNAME", "PASS");
$ftp_directory = TheDirectoryIwantToPutTheFile . $form_state['values']['allowed_user'];
$uri_parts = explode("/",$file->uri);
$filename = $uri_parts[sizeof($uri_parts)-1];
$target = $ftp_directory . "/" . $filename;
//drupal_set_message(t($target . " " . $file->uri));
$ret = ftp_nb_fput($conn,$target,$source,FTP_ASCII);
while ($ret == FTP_MOREDATA)
{
// Do whatever you want
//echo ".";
// Continue upload...
$ret = ftp_nb_continue($conn);
}
ftp_close($conn);
//$file->uri = file_unmanaged_copy($file->uri, $directory, FILE_EXISTS_REPLACE);
$file->uid = $form_state['values']['allowed_user'];
drupal_chmod($file->uri);
file_save($file);
// Need to add an entry in the file_usage table.
file_usage_add($file, 'assets', 'image', 1);
drupal_set_message(t("Your file has been uploaded!"));
}
}
}
I solved the problem. The problem was mainly because I gave the wrong path as the target. it had to be /public_html/...... instead of /home/our_name/public_html
I want to use only PEAR DB class, I try follow:
$pearPfad ="PEAR_DB-1.7.14/DB-1.7.14/DB.php";
error_reporting(E_ALL);
require_once($pearPfad);
$DB_dbType ="mysql";
$DB_user = "myuser";
$DB_pass = "mypassword";
$DB_host = "localhost";
$DB_dbName ="mydatabase";
$dsn = $DB_dbType . "://" // Build a DSN string (Data Source Name)
. $DB_user . ":" // Required by DB::connect()
. $DB_pass . "#"
. $DB_host . "/"
. $DB_dbName;
$db = DB::connect($dsn, TRUE);
if (DB::isError($db)) {
die("FEHLER: ".$db->getMessage() );
}
$sql = "SELECT id, title , created FROM h1z4e_content";
$res = $db->query($sql);
if (DB::isError($res)) {
die($res->getMessage());
}
while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) {
if (DB::isError($row)) {
die($row->getMessage());
}
print ("<p>Hey, it s:<br />" . $row->id . " " . $row->title . " ... and their freaky et: " . $row->created. "</p>\n");
}
$res->free();
// Similar to: mysql_free_resul
$db->disconnect();
But I get this error:
Warning: require_once(PEAR.php): failed to open stream: No such file or directory in /var/www/PEAR/PEAR_DB-1.7.14/DB-1.7.14/DB.php on line 30 Fatal error: require_once(): Failed opening required 'PEAR.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/PEAR/PEAR_DB-1.7.14/DB-1.7.14/DB.php on line 30
I found here in Stack Overflow this link: PHP-PEAR require_once('DB.php');
I don't want install PEAR on my computer.
I want only user PEAR DB class, is this possible without install PEAR?
Yes, but you need to set the include path correctly - in your case, to /full/path/to/PEAR_DB-1.7.14/DB-1.7.14/