Use of .ini file and getting values from .ini file - ini

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"

Related

Powershell script causing overflow

I am running the following Powershell Script against a list of SQL Instances to return Instance information, including users and roles. I want to use Powershell to do this as I'm collating the data and will import into another system which will do some analysis.
I created the following script which creates an XML file output for each instance found. The script works great (yes, it's probably clunky and an awful way to do this, but I'm learning so please feel free to give me a shove in the right direction), however for one of the servers with a few hundred SQL logins I get an overflow message appear on screen, the XML file is not closed correctly and as a result I can't import the results into my analysis system.
I would like either:
Ideas on what could be causing the overflow. For reference, the output XML that crashes out is 2.5MB in size, with approx 39,000 lines in the XML output before the overflow occurs
[OR]
Another way to get this output - CSV is an option but I don't know enough how to output this - can anyone provide tips?
Thank you in advance
#Input file is a plain text file with the name of each of the instances listed in it
$InputFile="C:\Tasks\SQL\Permissions\in\Instances.txt"
$OutputFolder="\\networkdrive\sharedfolder\"
Function GetDBUserInfo($Dbase)
{
if ($dbase.status -eq "Normal") # ensures the DB is online before checking
{$users = $Dbase.users | where {$_.login -eq $SQLLogin.name} # Ignore the account running this as it is assumed to be an admin account on all servers
foreach ($u in $users)
{
if ($u)
{
$XmlWriter.WriteStartElement("Login")
$XmlWriter.WriteElementString('DBName', $dbase.name)
$XmlWriter.WriteElementString('LoginName', $SQLLogin.name)
$XmlWriter.WriteStartElement('Login_Roles')
$DBRoles = $u.enumroles()
foreach ($role in $DBRoles)
{
$XmlWriter.WriteElementString('Role', $Dbase.name)
}
$XmlWriter.WriteEndElement()#Login_Roles
#Get any explicitly granted permissions
$XmlWriter.WriteStartElement('Login_Permissions')
$XmlWriter.WriteElementString('Instance', $svr.name)
$XmlWriter.WriteElementString('DBName', $dbase.name)
$XmlWriter.WriteElementString('LoginName', $SQLLogin.name)
foreach($perm in $Dbase.EnumObjectPermissions($u.Name))
{
$XmlWriter.WriteElementString('Permissions', $perm.permissionstate.tostring() + " " + $perm.permissiontype.tostring() + " on " + $perm.objectname.tostring() + " in " + $DBase.name.tostring())
}
$XmlWriter.WriteEndElement() #Login_Permissions
$XMLWriter.WriteEndElement() #Login
} # Next user in database
}
#else
#Skip to next database.
}
}
#Main portion of script start
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null #ensure we have SQL SMO available
foreach ($SQLsvr in get-content $InputFile) # read the instance source file to get instance names
{
$svr = new-object ("Microsoft.SqlServer.Management.Smo.Server") $SQLsvr
#Cycle through each instance and write the instance information to the file
#Output file is base folder for each of the text files (which will be named for the instance)
$OutputFile = $svr.name
$OutputFile = $OutputFolder+$OutputFile.Replace("\", "-")+".xml"
# get an XMLTextWriter to create the XML
$XmlWriter = New-Object System.XMl.XmlTextWriter($OutputFile,$Null)
# choose a pretty formatting:
$xmlWriter.Formatting = 'Indented'
$xmlWriter.Indentation = "4"
# write the header
$xmlWriter.WriteStartDocument()
# set XSL statements
$XLSPropText="type='text/xsl' href='style.xsl'"
$xmlWriter.WriteProcessingInstruction("xml-stylesheet", $XSLPropText)
# create root element "instances" and add some attributes to it
$xmlWriter.WriteStartElement("Root")
$XmlWriter.WriteStartElement("Instance")
$XmlWriter.WriteElementString("SQLInstance", $svr.name)
$XmlWriter.WriteElementString("SQLVersion", $svr.VersionString)
$XmlWriter.WriteElementString("Edition", $svr.Edition)
$XmlWriter.WriteElementString("LoginMode", $svr.loginmode)
$XmlWriter.WriteEndElement #instance
$SQLLogins = $svr.logins
foreach ($SQLLogin in $SQLLogins)
{
#Iterate through each login, writing the details into the login details
#$XmlWriter.WriteComment("Login Details")
$xmlWriter.WriteStartElement("Logins")
$XmlWriter.WriteElementString("InstanceName", $svr.Name)
$XmlWriter.WriteElementString("LoginName", $SQLLogin.Name)
$XmlWriter.WriteElementString("LoginType", $SQLLogin.LoginType)
$XmlWriter.WriteElementString("Created", $SQLLogin.CreateDate)
$XmlWriter.WriteElementString("DefaultDatabase", $SQLLogin.DefaultDatabase)
$XmlWriter.WriteElementString("Disabled", $SQLLogin.IsDisabled)
$SQLRoles = $SQLLogin.ListMembers()
If ($SQLRoles)
{ $XmlWriter.WriteElementString("ServerRole", $SQLRoles) }
else
{ $XmlWriter.WriteElementString("ServerRole", "Public") }
If ( $SQLLogin.LoginType -eq "WindowsGroup" )
{ #get individuals in any Windows domain groups
$XmlWriter.WriteStartElement("WindowsLogins")
$XmlWriter.WriteElementString("InstanceName", $svr.name)
$XmlWriter.WriteElementString("Login", $SQLLogin.name)
try {
$ADGRoupMembers = get-adgroupmember $SQLLogin.name.Split("\")[1] -Recursive
foreach($member in $ADGRoupMembers)
{ $XmlWriter.WriteElementString("Account", $member.name.tostring() + "(" + $member.SamAccountName.tostring() +")") }
}
catch
{
#Sometimes there are 'ghost' groups left behind that are no longer in the domain, this highlights those still in SQL
$XmlWriter.WriteElementString("Account", "Unable to locate group " + $SQLLogin.name.Split("\")[1] + " in the AD Domain")
}
$XmlWriter.WriteEndElement()
}
#Check the permissions in the DBs the Login is linked to.
If ($SQLLogin.EnumDatabaseMappings())
{
$XmlWriter.WriteStartElement('Permissions')
$XmlWriter.WriteElementString('InstanceName', $svr.name)
$xmlwriter.WriteElementString('Login', $SQLLogin.name)
foreach ( $DB in $svr.Databases)
{
try {
GetDBUserInfo($DB)
}
catch
{
echo $_.Exception|format-list -force
}
} # Next Database
$XmlWriter.WriteEndElement()
}
Else
{
$XmlWriter.WriteStartElement('Permissions')
$XmlWriter.WriteElementString('InstanceName', $svr.name)
$xmlwriter.WriteElementString('Login', $SQLLogin.name)
$XmlWriter.WriteElementString('Permissions', 'No Permissions')
$XmlWriter.WriteEndElement()
}
$xmlWriter.WriteEndElement() #End Logins element
}
}
# close the "machines" node:
$xmlWriter.WriteEndElement() #root node
# finalize the document:
$xmlWriter.WriteEndDocument()
$xmlWriter.Flush()
$xmlWriter.Close()
When running, error message is:
OverloadDefinitions
--------------------
void WriteEndElement()
void WriteEndElement()
No other error or message is given. The file does get written but is incomplete.

"Error formatting string" when using variable from string replacement in PowerShell DSC

I'm trying to set up replication in RavenDB by using PowerShell DSC, but I get this error in the TestScript scriptblock when I try to compile the configuration:
PSDesiredStateConfiguration\Node : Error formatting a string: Input string was not in a correct format.
Here is my scriptblock:
TestScript = {
$result = Invoke-WebRequest -Method GET "http://localhost:8080/Databases/Test/Docs/Raven/Replication/Destinations" -UseBasicParsing
$ravenSlaves = "{0}".Split(",")
foreach($ravenSlave in $ravenSlaves)
{
if($result -notmatch $ravenSlave)
{
return $false
}
}
return $true
} -f ($Node.RavenSlaves)
And RavenSlaves is defined like a string in my ConfigurationData for the nodes like this:
#{
NodeName = "localhost"
WebApplication = "test"
Role = "Master server"
RavenSlaves = "server1,server2"
}
The problem seems to be connected to when I'm using the foreach to iterate over the $ravenSlaves variable, because if I remove the foreach (and the if inside the foreach) the configuration compiles and the mof file is created.
Kiran led me to the right solution by his comment about using the $using modifier in the configuration.
I edited the RavenSlaves property on the node to be an array like this:
#{
NodeName = "localhost"
WebApplication = "test"
Role = "Master server"
RavenSlaves = #("server1,server2")
}
And then I changed the TestScript-block to be like this:
TestScript = {
$result = Invoke-WebRequest -Method GET "http://localhost:8080/Databases/Test/Docs/Raven/Replication/Destinations" -UseBasicParsing
$ravenSlaves = $Node.RavenSlaves
foreach($ravenSlave in $using:ravenSlaves)
{
if($result -notmatch $ravenSlave)
{
return $false
}
}
return $true
}
The script compiled and ran on the server and the replication document in RavenDB was correct.

I want remove file extension or rename the file extension before uploaded in php codeigniter

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;
}
}

Drupal 7 file module + php ftp function

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

Sharepoint delete files from documents library

I don't know what I'm doing wrong, I can't delete files, I'm working with a console application, the method SPFile.Delete() does nothing.
Here is some code:
for (int ii = web.Folders[url + documentsfolder].ItemCount - 1; ii >= 0; ii--)
{
SPFile file = web.GetFile(web.Folders[url + documentsfolder].Files[ii].UniqueId);
if (file.Exists)
{
file.Delete();
}
}
It doesn't throw an exception. It just stops in the first file, I don't know why.
Hope you can help
Hi Here is the code snippet for Deleting folders or files of shared Documents. This might give you clue for using proper command DeleteItemById for deletion.
$web = Get-SPWeb -Identity "http://sharepoint2010/myweb/"
$list = $web.GetList("http://sharepoint2010/myweb/Shared%20Documents/")
function ProcessFolder {
param($folderUrl)
$folder = $web.GetFolder($folderUrl)
foreach ($file in $folder.Files) {
#Delete file by deleting parent SPListItem
$list.Items.DeleteItemById($file.Item.Id)
}
}
#Collect files to delete
ProcessFolder($list.RootFolder.Url)
#Download files in folders
foreach ($folder in $list.Folders) {
ProcessFolder($folder.Url)
}
#Delete folders
foreach ($folder in $list.Folders) {
try {
$list.Folders.DeleteItemById($folder.ID)
}
catch {
#Deletion of parent folder already deleted this folder
#I really hate this
}
}

Resources