Database information from txt using pdo class - pdo

I am new on pdo and classes. I use this code to connect to database if i write the database information manually. But i want to read all these information from text file which has 4 lines. I use this code below but something is wrong.
$sqlsrv_txt = "evrak_tip.txt";
$satirlar = file($sqlsrv_txt);
$host = substr($satirlar[0], strpos($satirlar[0], ":") + 1);
$db_name = substr($satirlar[1], strpos($satirlar[1], ":") + 1);
$username = substr($satirlar[2], strpos($satirlar[2], ":") + 1);
$password = substr($satirlar[3], strpos($satirlar[3], ":") + 1);
class Database
{
private $host = "HOST NAME";
private $db_name = "DB NAME";
private $username = "USER NAME";
private $password = "PASSWORD";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("sqlsrv:server=" . $this->host . ";Database="
.$this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING,
PDO::SQLSRV_ENCODING_UTF8);
}
catch(PDOException $e)
{
echo "Connection error: " . $e->getMessage();
}
return $this->conn;
}
}
As you can see in the code, i need to write host,db_name,username and password accoridng to variables coming from txt file.
Can anybody help me about this?

i fixed it by creating and reading ini file.
$config = parse_ini_file("config.ini");
$this->conn = new
PDO($config['type'].":server=".$config['host'].";Database=".$config['dbname'],
$config['user'], $config['password']);

Related

Unable to unload DLL in .NET Core 3

I am trying to unload an external assemble but it still sitting in the memory and I can not delete the dll file. Here is my code - What am I doing wrong ?
The uploaded dll is very simple - just 1 class and one method. no dependencies.
I had a look at many samples and see no issue in the code but it still does not work.
Thank you !
class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
public SimpleUnloadableAssemblyLoadContext( ) : base(isCollectible: true)
{
}
protected override Assembly Load(AssemblyName name)
{
return null;
}
}
public class PluginLoader2
{
[MethodImpl(MethodImplOptions.NoInlining)]
public string getExternalText()
{
string res = "";
var sourcesPath = Path.Combine(Environment.CurrentDirectory, "Plugins");
string[] fileEntries = Directory.GetFiles(sourcesPath);
foreach (string fileName in fileEntries)
{
SimpleUnloadableAssemblyLoadContext context = new SimpleUnloadableAssemblyLoadContext();
WeakReference w_r = new WeakReference(context, trackResurrection: true);
var myAssembly = context.LoadFromAssemblyPath(fileName);
context.Unload();
for (var i = 0; i < 10 && w_r.IsAlive; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
res += "<br /><br />" + fileName + " live status is " + w_r.IsAlive.ToString();
}
return res;
}
}

why PDOException didnt show an error in my browser?

<?php
class MyConnection {
protected $username = 'root';
protected $password = '';
protected $host = 'localhost';
protected $db_name = 'testdbewewewewe';
public function connection() {
try {
$this->dbh = new PDO("mysql:host=". $this->host . ";dbname=". $this->db_name, $this->username, $this->password);
} catch (PDOException $e) {$e->getMessage();}
}
}
?>
hi im new in PDO i hope someone can asnwer my curiousity on this one, i try to make a connection in mysql using php with PDO, but when i already make this code the browser doesn't show any error all is doing good, but when i tried to intentionally make the database name wrong the browser didn't show any error at all and i'm just curious if im i really doing it right?
Just because your error reporting is wrong.
You should not catch error exceptions to show them in the browser - PHP can already do it for you.
So, make your class this way
class MyConnection {
protected $username = 'root';
protected $password = '';
protected $host = 'localhost';
protected $db_name = 'testdbewewewewe';
public function connection() {
$this->dbh = new PDO("mysql:host=". $this->host . ";dbname=". $this->db_name, $this->username, $this->password);
}
}
Then tell PHP to show errors in the browser,
error_reporting(E_ALL);
ini_set('display_errors', 1);
$conn = new MyConnection();
$conn->connection();
And have your exception shown first class.

How to fetch list of all distinguished names (DNs) from LDAP server using JNDI?

I wish to fetch the list of all distinguised names (DNs) from LDAP server using JNDI. I am able to fetch the base DN using following code:
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://" + ldapServer + ":" + ldapPort);
env.put(Context.REFERRAL, "follow");
if(sslEnabled) {
env.put("java.naming.ldap.factory.socket", TrustAllSSLSocketFactory.class.getName());
}
// Create the LDAP context
LdapContext context = new InitialLdapContext(env, null);
String base = "";
String filter = "(objectclass=*)";
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.OBJECT_SCOPE);
// Search the directory for retrieving namingContexts attribute
// which contains all the base DNs values
NamingEnumeration<SearchResult> results = context.search(base, filter, controls);
List<String> namingContextsList = new ArrayList<String>();
// Process attributes
if(results.hasMore()) {
Attributes attrs = results.next().getAttributes();
if (attrs != null) {
Attribute namingContexts = attrs.get("namingContexts");
NamingEnumeration enumeration = namingContexts.getAll();
while(enumeration.hasMore()) {
namingContextsList.add((String) enumeration.next());
}
}
}
System.out.println(namingContextsList);
Could you please help in fetching all the possible DNs in similar manner or other?
Just change OBJECT_SCOPE to SUBTREE_SCOPE.
This is all documented, you know.
Following code works for me: (Note that you need to provide credentials to perform this operation and the attribute name is "distinguishedName")
String ldapServer = "192.168.0.11";
String ldapPort = "389";
String principal = "CN=user";
String password = "password";
Hashtable<String,String> environment = new Hashtable<String,String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://" + ldapServer + ":" + ldapPort);
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, principal);
environment.put(Context.SECURITY_CREDENTIALS, password);
environment.put(Context.REFERRAL, "follow");
environment.put("com.sun.jndi.ldap.connect.pool", "true");
// Create the LDAP context
LdapContext context = new InitialLdapContext(environment, null);
String baseDN = "DC=domain,DC=com" // Put your base DN here
String filter = "(objectclass=*)";
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); // Use this for first level DNs only
NamingEnumeration<SearchResult> results = context.search(baseDN, filter, controls);
List<String> searchDNsList = new ArrayList<String>();
try {
// Process attributes
while(results.hasMore()) {
Attributes attrs = results.next().getAttributes();
if (attrs != null) {
Attribute distinguisedNames = attrs.get("distinguishedName");
if(distinguisedNames != null) {
NamingEnumeration enumeration = distinguisedNames.getAll();
while(enumeration.hasMore()) {
String searchDN = (String) enumeration.next();
searchDNsList.add(searchDN);
}
}
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println(searchDNsList);

File upload after rename the file in zend

This is my form
class Admin_Form_RoomtypeForm extends Zend_Form
{
public function init()
{
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name :');
$imagePath = '/home/dinuka/image';
$image = new Zend_Form_Element_File('image');
$image->setLabel('Image URL :');
$image->setDestination($imagePath);
$image->addValidators(array(array('IsImage', false)));
$submit = new Zend_Form_Element_Submit('submit');
$this->addElements(array($name, $image, $submit));
}
}
This is my controller
class Admin_RoomtypesController extends Zend_Controller_Action
{
public function addAction()
{
$form = new Admin_Form_RoomtypeForm();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
$form->populate($formData);
$name = $form->getValue('name');
}
}
}
Now i want to upload file after change file name as $name value. How can i do it?
I had to do something like this for one of my projects, except i needed unique filenames. This isn't a perfect solution, but it may put you on the right track:
<?php
class My_Filter_UniqueFilename implements Zend_Filter_Interface
{
public function filter($value)
{
$upload_dir = pathinfo($value, PATHINFO_DIRNAME);
$ext = pathinfo($value, PATHINFO_EXTENSION);
$filename = $upload_dir . "/" . md5(microtime()) . "." . $ext;
$result = rename($value, $filename);
if($result === true) {
return $upload_dir . $filename;
}
require_once 'Zend/Filter/Exception.php';
throw new Zend_Filter_Exception(sprintf("File '%s' could not be renamed. An error occured while processing the file.", $value));
}
}
Finally I done it as following.
-Form -
class Admin_Form_RoomtypeForm extends Zend_Form
{
public function init()
{
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name :');
$image = new Zend_Form_Element_File('image');
$image->setLabel('Image URL :');
$image->addValidators(array(array('IsImage', false)));
$submit = new Zend_Form_Element_Submit('submit');
$this->addElements(array($name, $image, $submit));
}
}
-Controller -
class Admin_RoomtypesController extends Zend_Controller_Action
{
public function addAction()
{
$form = new Admin_Form_RoomtypeForm();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
$form->populate($formData);
$name = $form->getValue('name');
$image = $form->getValue('image');
$temp = explode(".", $image);
$ext = $temp[count($temp)-1];
$imageName = $name .'.'. $ext;
$fullPath = $imagePath ."/". $imageName;
copy("/tmp/". $image, $fullPath);
}
}
}
default image is upload to /tmp folder. We can change it using setDestination() method as my example.
Thank for All

Java LDAP Authentication using username and password

I have a working code snippet by which i can authenticate a user by dn and password. My requirement is that the user will be entering his username(sAMAccountName) and I want to authenticate using sAMAccountName and password. How can I modify this code to achieve it?
String userName = "John P R-Asst General Manager";
String passWord = "asdfgh123";
String base ="OU=SOU,DC=example,DC=com";
String dn = "cn=" + userName + "," + base;
String ldapURL = "ldap://mdsdc3.example.com:389";
authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
authEnv.put(Context.PROVIDER_URL, ldapURL);
authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
authEnv.put(Context.SECURITY_PRINCIPAL, dn);
authEnv.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext authContext = new InitialDirContext(authEnv);
return true;
} catch (NamingException namEx) {
return false;
}
I hope this helps many of you.
You don't need to all user hierarchy with CN, DN, etc.
You can login just passing domain\user and password.
I've my code working as it is bellow:
try
{
// Set up the environment for creating the initial context
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap_server:389");
//
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "domain\\user"); //we have 2 \\ because it's a escape char
env.put(Context.SECURITY_CREDENTIALS, "test");
// Create the initial context
DirContext ctx = new InitialDirContext(env);
boolean result = ctx != null;
if(ctx != null)
ctx.close();
return result;
}
catch (Exception e)
{
return false;
}
Can you try to complete Context.PROVIDER_URL like this :
String ldapURL = "ldap://mdsdc3.example.com:389/DC=example,DC=com";
I Think it would be better to use GSSAPI, perhaps you can have a look here and here