I've been trying to create a directory following a specific structure, yet nothing appears to be happening. I've approached this by defining multiple variables as follows:
$rid = '/appicons/';
$sid = '$artistid';
$ssid = '$appid';
$s = '/';
and the function I've been using runs thusly:
$directory = $appid;
if (!is_dir ($directory))
{
mkdir($directory);
}
That works. However, I want to have the following structure in created directories: /appicons/$artistid/$appid/
yet nothing really seems to work. I understand that if I were to add more variables to $directory then I'd have to use quotes around them and concatenate them (which gets confusing).
Does anyone have any solutions?
$directory = "/appicons/$artistid/$appid/";
if (!is_dir ($directory))
{
//file mode
$mode = 0777;
//the third parameter set to true allows the creation of
//nested directories specified in the pathname.
mkdir($directory, $mode, true);
}
This should do what you want:
$rid = '/appicons/';
$sid = $artistid;
$ssid = $appid;
$s = '/';
$directory = $rid . $artistid . '/' . $appid . $s;
if (!is_dir ($directory)) {
mkdir($directory);
}
The reason your current code doesn't work is due to the fact you're trying to use a variable inside a string literal. A string literal in PHP is a string enclosed in single quotes ('). Every character in this string is treated as just a character, so any variables will just be parsed as text. Unquoting the variables so your declarations look like the following fixes your issue:
$rid = '/appicons/';
$sid = $artistid;
$ssid = $appid;
$s = '/';
This next line concatenates (joins) your variables together into a path:
$directory = $rid . $artistid . '/' . $appid . $s;
Concatenation works like this
$directory = $rid.$artistid."/".$appid."/"
When you're assigning one variable to another, you don't need the quotes around it, so the following should be what you're looking for.
$rid = 'appicons';
$sid = $artistid;
$ssid = $appid;
and then...
$dir = '/' . $rid . '/' . $sid . '/' . $ssid . '/';
if (!is_dir($dir)) {
mkdir($dir);
}
Related
Is that possible to get variable from other function in same Controller ?
So I just updated my code ... the huge code is my real code ... so I wish to get the $hashfilename_filename to another function so I able to save it into DB
Example:
class HappyController extends Controller{
public function actionUploadFile()
{
if (isset($_FILES['Filedata']['tmp_name']) && is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
$today = date("Ymd");
$slash = Yii::app()->params['slash'];
$tmp_folder = Yii::app()->params['tmp_folder'];
$tmp_folder_with_index_file = $tmp_folder . $slash . 'index.html';
$tmp_folder_with_date = Yii::app()->params['tmp_folder'] . $today;
if (!is_dir($tmp_folder_with_date)){
mkdir($tmp_folder_with_date, 0755);
copy($tmp_folder_with_index_file, $tmp_folder_with_date . $slash . 'index.html');
}
$filesize = sprintf("%u", filesize( $_FILES['Filedata']['tmp_name'] ));
$hashfilename_filename = md5(time() + 1) . '.apk';
$full_path = $tmp_folder_with_date . $slash . $hashfilename_filename;
if (!move_uploaded_file ($_FILES['Filedata']['tmp_name'], $full_path)){
$result['statusCode'] = "500";
echo json_encode($result);
die();
}
$result['statusCode'] = "200";
$result['today'] = $today;
$result['tmp_folder_with_date'] = $tmp_folder_with_date;
$result['filesize'] = $filesize;
$result['hashfilename_filename'] = $hashfilename_filename;
$result['full_path'] = $full_path;
}else{
$result['statusCode'] = "400";
}
echo json_encode($result);
die();
}
public function actionLife(){
$model = new ThisisLife();
$model->sad = $hashfilename_filename;
$model->save();
}
}
In public function actionLife , I wish to get the variable from other function, any suggestion to do that ?
try storing it in a session variable;
public function actionAbc(){
$full_path = a + b;
Yii::app()->user->setState('full_path', $full_path);
}
public function actionXyz(){
$full_path = Yii::app()->user->getState('full_path');
}
In this way you can access this variable from anywhere across whole platform.
What you are trying to do is not the right way in my opinion. The idea behind OOP i to encapsulate code belonging together. So if you need to determine a path which is needed in more than one place (or action) just extract it into its own private function within the controller. That way you could call this method from both actions and reuse your code.
If you need this variable between two calls I'd rather pass it as a GET/POST-Parameter as the otherway around you risk using the same filename again if you forget to reset the var...as it says, it lasts the whole session!
Your method could look like this:
private function generatePath()
{
$folder = Yii::app()->params['tmp_folder'] . date("Ymd");
$folderWithIndex = Yii::app()->params['tmp_folder'] . DIRECTORY_SEPARATOR . 'index.html';
if (!file_exists($folder)) {
mkdir($folder, 0755);
copy($folderWidthIndex, $folder . DIRECTORY_SEPARATOR . 'index.html');
}
$filename = md5(time() + 1) . '.apk';
return $folder . DIRECTORY_SEPARATOR . $filename;
}
The constant DIRECTORY_SEPARATOR is a php default constant to automatically fill in the "slash" of the current filesystem.
One more input: Instead of defining the path in your params, you could set it as a yii-alias. This makes life much easier in the long run. Make sure to check it out here: https://github.com/yiisoft/yii2/blob/master/docs/guide/concept-aliases.md
I hope it helped!
cheers, pascal
If you need to access variable through controllers, why don't u make it a private field in controller. So that you can access it in whole Controller class. You then may have getter, setters if needed, as it should as we are talking about OOP.
Long time reader, first time poster. I know just enough about php to be dangerous and this is my first BIG project using it.
Some background:
I have over 1 million (yes, million) .html files that were generated from an old news gathering program. These .html files contain important archive information that needs to be searched on daily basis. I have yet to get to other servers which might very well have more so 2-3 million+ is not out of the question.
I am taking these .html files and transferring them into a mysql database. At least, so far, the code has worked wonderfully with several hundred test files. I'll attach the code at the end.
The problem starts when the .html files are archived, and it's a function of the box generating the archive which cannot be changed, is the files go into folders. They are broken down like this
archives>year>month>file.html
so an example is
archives>2002>05may>lots and lots of files.html
archives>2002>06june>lots and lots of files.html
archives>2002>07july>lots and lots of files.html
With help and research, I wrote code to strip the files of markup that includes html2text and simple_html_dom and put the information from each tag in the proper fields in my database, which works great. But ALL of the files need to be moved to the same directory for it to work. Again, over a million and possibly more for other severs takes a REALLY long time to move. I am using a batch file to robocopy the files now.
My question is this:
Can I use some sort of wildcard to define all of the subdirectories so I don't have to move all of the files and they can stat in their respective directories?
Top of my code:
// Enter absolute path of folder with HTML files in it here (include trailing slash):
$directory = "C:\\wamp1\\www\\name\\search\\files\\";
The subdirectories are under the files directory.
In my searches for an answer, I have seen "why would you want to do that?" or other questions asking about .exe files or .bat files in the directories and how it could be dangerous so don't do it. My question is just for these html files so there is nothing being called or running and no danger.
Here is my code for stripping the html into the database. Again, works great, but I would like to skip the step of having to move all of the files into one directory.
<?php
// Enter absolute path of folder with HTML files in it here (include trailing slash):
$directory = "C:\\wamp1\\www\\wdaf\\search\\files\\";
// Enter MySQL database variables here:
$db_hostname = "localhost";
$db_username = "root";
$db_password = "password";
$db_name = "dbname";
$db_tablename = "dbtablename";
/////////////////////////////////////////////////////////////////////////////////////
// Include these files to strip all characters that we don't want
include_once("simple_html_dom.php");
include_once("html2text.php");
//Connect to the database
mysql_connect($db_hostname, $db_username, $db_password) or trigger_error("Unable to connect to the database host: " . mysql_error());
mysql_select_db($db_name) or trigger_error("Unable to switch to the database: " . mysql_error());
//scan the directory and look for all the htmls files
$files = scandir($directory);
for ($filen = 0; $filen < count($files); $filen++) {
$html = file_get_html($directory . $files[$filen]);
// first check if $html->find exists
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
//Get the filename of the file from which it will extract
$filename = $files[$filen];
//define the path of the files
$path = "./files/";
//Combine the patha and filename
$fullpath = $path . $filename;
// Get our variables from the HTML: Starts with 0 as the title field so use alternate ids starting with 1 for the information
$slug = mysql_real_escape_string(convert_html_to_text($html->find('td', 8)));
$tape = mysql_real_escape_string(convert_html_to_text($html->find('td', 9)));
$format0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 10)));
$time0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 11)));
$writer = mysql_real_escape_string(convert_html_to_text($html->find('td', 12)));
$newscast = mysql_real_escape_string(convert_html_to_text($html->find('td', 13)));
$modified = mysql_real_escape_string(convert_html_to_text($html->find('td', 14)));
$by0 = mysql_real_escape_string(convert_html_to_text($html->find('td', 15)));
$productionCues = mysql_real_escape_string(convert_html_to_text($html->find('td', 16)));
$script = mysql_real_escape_string(convert_html_to_text($html->find('td', 18)));
// Insert variables into a row in the MySQL table:
$sql = "INSERT INTO " . $db_tablename . " (`path`, `fullpath`, `filename`, `slug`, `tape`, `format0`, `time0`, `writer`, `newscast`, `modified`, `by0`, `productionCues`, `script`) VALUES ('" . $path . "', '" . $fullpath . "', '" . $filename . "', '" . $slug . "', '" . $tape . "', '" . $format0 . "', '" . $time0 . "', '" . $writer . "', '" . $newscast . "', '" . $modified . "', '" . $by0 . "', '" . $productionCues . "', '" . $script . "');";
$sql_return = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error());
}
}
}
?>
Thanks in advance,
Mike
Just wanted to update this post with a answer to my question that works quite well. With some help, we found that scandir used recursively to create an array would work.
I thought I'd post this so if anyone else was looking to do something similar, they would be able wouldn't have to look far! I know I like to see answers!
The code is from the second user-contributed note here with a few modifications: http://php.net/manual/en/function.scandir.php
so in my code above, I replaced
//scan the directory and look for all the htmls files
$files = scandir($directory);
for ($filen = 0; $filen < count($files); $filen++) {
$html = file_get_html($directory . $files[$filen]);
with
function import_dir($directory, $db_tablename) {
$cdir = scandir($directory);
foreach ($cdir as $key => $value)
{
if (!in_array($value,array(".","..")))
{
if (is_dir($directory . DIRECTORY_SEPARATOR . $value))
{
// Item in this directory is sub-directory...
import_dir($directory . DIRECTORY_SEPARATOR . $value,$db_tablename);
}
else
// Item in this directory is a file...
{
$html = file_get_html($directory . DIRECTORY_SEPARATOR . $value);
and then for the filenames, replaced
//Get the filename of the file from which it will extract
$filename = $files[$filen];
//define the path of the files
$path = "./files/";
//Combine the patha and filename
$fullpath = $path . $filename;
with
//Get the filename of the file from which it will extract
$filename = mysql_real_escape_string($value);
//define the path of the files
$path = mysql_real_escape_string($directory . DIRECTORY_SEPARATOR);
//Combine the patha and filename
$fullpath = $path . $value;
Thanks to those who answered!
Mike
I'm not sure how long it would take before your PHP query times out, but there is an inbuilt function RecursiveDirectoryIterator which sounds like it might do the trick for you.
I'm trying to recursively iterate through a group of dirs that contain either files to upload or another dir to check for files to upload.
So far, I'm getting my script to go 2 levels deep into the filesystem, but I haven't figured out a way to keep my current full filepath in scope for my function:
function getPathsinFolder($basepath = null) {
$fullpath = 'www/doc_upload/test_batch_01/';
if(isset($basepath)):
$files = scandir($fullpath . $basepath . '/');
else:
$files = scandir($fullpath);
endif;
$one = array_shift($files); // to remove . & ..
$two = array_shift($files);
foreach($files as $file):
$type = filetype($fullpath . $file);
print $file . ' is a ' . $type . '<br/>';
if($type == 'dir'):
getPathsinFolder($file);
elseif(($type == 'file')):
//uploadDocsinFolder($file);
endif;
endforeach;
}
So, everytime I call getPathsinFolder I have the basepath I started with plus the current name of the directory I'm scandirring. But I'm missing the intermediate folders in between. How to keep the full current filepath in scope?
Very simple. If you want recursion, you need to pass the whole path as a parameter when you call your getPathsinFolder().
Scanning a large directory tree might be more efficient using a stack to save the intermediate paths (which would normally go on the heap), rather than use much more of the system stack (it has to save the path as well as a whole frame for the next level of the function call.
Thank you. Yes, I needed to build the full path inside the function. Here is the version that works:
function getPathsinFolder($path = null) {
if(isset($path)):
$files = scandir($path);
else: // Default path
$path = 'www/doc_upload/';
$files = scandir($path);
endif;
// Remove . & .. dirs
$remove_onedot = array_shift($files);
$remove_twodot = array_shift($files);
var_dump($files);
foreach($files as $file):
$type = filetype($path . '/' . $file);
print $file . ' is a ' . $type . '<br/>';
$fullpath = $path . $file . '/';
var_dump($fullpath);
if($type == 'dir'):
getPathsinFolder($fullpath);
elseif(($type == 'file')):
//uploadDocsinFolder($file);
endif;
endforeach;
}
Trying to turn this:
href="/wp-content/themes/tray/img/celebrity_photos/photo.jpg"
into:
href="/img/celebrity_photos/photo.jpg"
So I'm simply trying to remove /wp-content/themes/tray/ from the url.
Here's the plug in's PHP code that builds a variable for each anchor path:
$this->imageURL = '/' . $this->path . '/' . $this->filename;
So I'd like to say:
$this->imageURL = '/' . $this->path -/wp-content/themes/tray/ . '/' . $this->filename;
PHP substr()? strpos()?
Given that:
$this->imageURL = '/' . $this->path . '/' . $this->filename;
$remove = "/wp-content/themes/tray";
This is how to remove a known prefix, if it exists:
if (strpos($this->imageURL, $remove) === 0) {
$this->imageURL = substr($this->imageURL, strlen($remove));
}
If you are certain that it always exists then you can also lose the if condition.
This is one option:
$h="/wp-content/themes/tray/img/celebrity_photos/photo-on-4-6-12-at-3-23-pm.jpg";
$prefix="/wp-content/themes/tray/";
print str_replace($prefix, "/", $h, 1);
It suffers from one major flaw, which is that it doesn't anchor itself to the left-hand-side of $h. To do this, you'd either need to use a regular expression (which is heavier on processing) or wrap this in something that detects the position of your prefix before running the str_replace().
$h="/wp-content/themes/tray/img/celebrity_photos/photo-on-4-6-12-at-3-23-pm.jpg";
$prefix="/wp-content/themes/tray/";
if (strpos(" ".$h, $prefix) == 1)
$result = str_replace($prefix, "/", $h, 1);
else
$result = $h;
print $result;
Note this important element: the prefix ends in a slash. You don't want to match other themes like "trayn" or "traypse". Beware writing things for just your specific use case. Always try to figure out how code might break, and program around problematic hypothetical use cases.
Try this :
$href = str_replace("/wp-content/themes/tray","",$href);
Or in your specific case, something like this :
$this->imageURL = '/' . str_replace("/wp-content/themes/tray/","",$this->path) . '/' . $this->filename;
I wonder whether someone could help me please.
I'm using Image Uploader from Aurigma, and to save the uploaded images, I've put this script together.
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
//Do not forget about the slash in the end of the folder name.
$galleryPath = 'UploadedFiles/';
require_once 'Includes/gallery_helper.php';
require_once 'ImageUploaderPHP/UploadHandler.class.php';
/**
* FileUploaded callback function
* #param $uploadedFile UploadedFile
*/
function onFileUploaded($uploadedFile) {
$packageFields = $uploadedFile->getPackage()->getPackageFields();
$userid = $packageFields["userid"];
$locationid= $packageFields["locationid"];
global $galleryPath;
$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;
$absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR;
if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) {
initGallery($absGalleryPath, $absThumbnailsPath, FALSE);
}
$dirName = $_POST['folder'];
$dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $dirName);
if (!is_dir($absGalleryPath . $dirName)) {
mkdir($absGalleryPath . $dirName, 0777);
}
$path = rtrim($dirName, '/\\') . '/';
$originalFileName = $uploadedFile->getSourceName();
$files = $uploadedFile->getConvertedFiles();
// save converter 1
$sourceFileName = getSafeFileName($absGalleryPath, $originalFileName);
$sourceFile = $files[0];
/* #var $sourceFile ConvertedFile */
if ($sourceFile) {
$sourceFile->moveTo($absGalleryPath . $sourceFileName);
}
// save converter 2
$thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName);
$thumbnailFile = $files[1];
/* #var $thumbnailFile ConvertedFile */
if ($thumbnailFile) {
$thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName);
}
//Load XML file which will keep information about files (image dimensions, description, etc).
//XML is used solely for brevity. In real-life application most likely you will use database instead.
$descriptions = new DOMDocument('1.0', 'utf-8');
$descriptions->load($absGalleryPath . 'files.xml');
//Save file info.
$xmlFile = $descriptions->createElement('file');
$xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName);
$xmlFile->setAttribute('source', $sourceFileName);
$xmlFile->setAttribute('size', $uploadedFile->getSourceSize());
$xmlFile->setAttribute('originalname', $originalFileName);
$xmlFile->setAttribute('thumbnail', $thumbnailFileName);
$xmlFile->setAttribute('description', $uploadedFile->getDescription());
//Add additional fields
$xmlFile->setAttribute('userid', $userid);
$xmlFile->setAttribute('locationid', $locationid);
$xmlFile->setAttribute('folder', $dirName);
$descriptions->documentElement->appendChild($xmlFile);
$descriptions->save($absGalleryPath . 'files.xml');
}
$uh = new UploadHandler();
$uh->setFileUploadedCallback('onFileUploaded');
$uh->processRequest();
?>
What I'd like to do is replace the files element of the filename and replace it with the username, so each saved folder and associated files can be indentified to each user.
I've added a username text field to the form which this script saves from
I think I'm right in saying that this is line that needs to change $descriptions->save($absGalleryPath . 'files.xml');.
So amongst many attempts I've tried changing this to $descriptions->save($absGalleryPath . '$username.xml, $descriptions->save($absGalleryPath . $username '.xml, but none of these have worked, so I'm not quite sure what I need to change.
I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong.
Many thanks
'$username.xml' will be interpreted as $username.xml, you need to use "$username.xml". Single quotes "disable" the variable use inside strings.
What you are tryiing can be a bad idea, as you are making so a username can't contain 'special characters' like "/". Perhaps is not a problem if you aready have a rule that stop "/" being part of a username.