CodeIgniter run library before database settings - codeigniter

I test my Codeigniter site on localhost then update it on a server. Switching between them involves a lot of adjustment-related problems.
So I want to config it by only one constant: MYCUSTOM_SERVER_LOCATION
Then my database connection and password is configured according to location of my server(localhost or myhost). The only problem is that database.php is run before mysettings library. Even doing settings in a config file instead of a library has the same result.
[UPDATED]
application/config/autoload.php:
...
$autoload['libraries'] = array('mysettings','database','session');
...
application/libraries/mysettings.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
define("MYCUSTOM_SERVER_LOCATION", "localhost");
class mysettings {
//////////////////////////////////////////////////
// option: localhost
// option: 000webhost
//$config["mycustom_server"]="localhost";
}
application/config/database.php
if(MYCUSTOM_SERVER_LOCATION=="localhost")
{
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '...';
$db['default']['password'] = '...';
$db['default']['database'] = '...';
}
else if(MYCUSTOM_SERVER_LOCATION=="myserver")
{
$db['default']['hostname'] = '...';
$db['default']['username'] = '...';
$db['default']['password'] = '...';
$db['default']['database'] = '...';
}
else
{
echo "Unknown server.";
}
output result:
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant MYCUSTOM_SERVER_LOCATION - assumed 'MYCUSTOM_SERVER_LOCATION'
Filename: config/database.php
Line Number: 51
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant MYCUSTOM_SERVER_LOCATION - assumed 'MYCUSTOM_SERVER_LOCATION'
Filename: config/database.php
Line Number: 58
Unknown server.

You can set the $active_group variable in application/config/database.php
Example Usage:
/*
The $active_group variable lets you choose which connection group to
make active. By default there is only one group (the 'default' group).
*/
$active_group = "development";
$db['development']['hostname'] = "localhost";
$db['development']['username'] = "us";
$db['development']['password'] = "";
$db['development']['database'] = "db1";

Related

How can I show up the errors in Laravel when response is 500?

I have a Laravel application working on different urls. example.ch and app.example.net are working will. On the same server like app.example.net i like to run app-stage.example.net.
The application return an error 500 without an error log.
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
var_dump($kernel); // returns an object. Everything ok
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
var_dump($response) //returns error 500
I checked the php version.
I checked the fpm version.
I checked the .env file
I did "sudo chmod -R 777 bootstrap/cache storage"
I restarted the server.
I tried to show the errors.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
No success.
What can I do in addition to find the error?
use this package Dotenv
make a file like this
and then use multiple .env for example acceptnace.env . production.env , staging.env
make a file like environment.php in bootstrap directory like this
<?php
$envPath = realpath(dirname(__DIR__));
$env = get_current_user();
if ($env == 'staging') {
$envFile = ".staging.env";
} elseif ($env == "acceptance") {
$envFile = ".acceptance.env";
} elseif ($env == "development") {
$envFile = ".development.env";
} elseif ($env == "production") {
$envFile = ".production.env";
} elseif ($env == "beta") {
$envFile = ".beta.env";
} else {
$envFile = ".local.env";
}
Dotenv\Dotenv::create($envPath, $envFile)->load();
and this will load multiple env for your app

PHPMailer not running with Xampp on Windows10

my problem is that PHPMailer (PHPMailer-master 6.0.3 to be exact) does not deliver emails when I run it with Xampp and Windows10.
(I found a lot of comments on that subject but none of them led to a solution.)
The following code runs fine on a remote server:
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// 'PHPMailer' here actually is the original folder 'PHPMailer-master'
// from unpacking the downloaded file PHPMailer-master.zip
require 'vendor/PHPMailer/src/Exception.php';
require 'vendor/PHPMailer/src/PHPMailer.php';
require 'vendor/PHPMailer/src/SMTP.php';
echo (extension_loaded('openssl')?'SSL loaded':'SSL not loaded')."\n";
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->$mail->isSendmail(); // corrected
$mail->Host = 'smtp.kabelmail.de'; //smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'myname#kabelmail.de'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('myname#kabelmail.de', 'myname'); // Add a recipient
// $mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('myname#web.de', 'Antwort');
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
//Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject:localhost';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = ' body in plain text for non-HTML mail lients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>
I left the script above as it is and modified php.ini for Xampp in accordance with the comments at Phpmailer not working running from localhost (XAMPP):
[mail function]
SMTP=smtp.kabelmail.de
smtp_port=465
sendmail_from = to#kabelmail.de
sendmail_path ="C:\xampp\sendmail\sendmail.exe\"
;(I also tried sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t" but without success.)
mail.log="C:\xampp\php\logs\php_mail.log"
These are the modifications to sendmail.ini:
[sendmail]
smtp_server=smtp.kabelmail.de
smtp_port=465
smtp_ssl=auto
error_logfile=error.log
debug_logfile=debug.log
auth_username=myname#kabelmail.de
auth_password=mypassword
Results:
1. With the settings above I got this message:
SSL loaded 2018-01-11 12:06:10 SERVER -> CLIENT: 421 4.3.2 Too many open connections.
2018-01-11 12:06:10 CLIENT -> SERVER: EHLO localhost
2018-01-11 12:06:10 SERVER -> CLIENT:
2018-01-11 12:06:10 SMTP ERROR: EHLO command failed:
2018-01-11 12:06:10 SMTP NOTICE: EOF caught while checking if connected
SMTP Error: Could not connect to SMTP host.
SMTP Error: Could not connect to SMTP host.
Message could not be sent.Mailer Error: SMTP Error: Could not connect to SMTP host.
I then replaced $mail->isSendmail(); by $mail->isMail();
The message that showed up now was
SSL loaded Message has been sent
That is what I was looking for, but - there was no message in the mailbox.!!!
php_mail.log had this information, which doesn't look suspicious to me:
[11-Jan-2018 13:09:32 Europe/Berlin] mail() on [C:\xampp\htdocs\to\vendor\PHPMailer\src\PHPMailer.php:768]: To: "name" <myname#kabelmail.de> -- Headers: Date: Thu, 11 Jan 2018 13:09:32 +0100 From: Mailer <from#example.com> Reply-To: Antwort <myname#web.de> Message-ID: <VuAQ3BR022MQyNd3hKCoguqr50Ry9TPG4vIRL2ZmFg#localhost> X-Mailer: PHPMailer 6.0.3 (https://github.com/PHPMailer/PHPMailer) MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="b1_VuAQ3BR022MQyNd3hKCoguqr50Ry9TPG4vIRL2ZmFg" Content-Transfer-Encoding: 8bit
Can somebody give me a hint what might be wrong?
I have been working on that for several days now but obviously I am missing something basic.
--- Edit Jan. 12, 2018 -------------------------------------------------
$mail->isSendmail(); is the setting that is ok on the remote server!
Solved.
The breakthrough was reached when I moved to smtp.web.de.
I now get the the messages from client and server ($mail->SMTPDebug = 2;).
The server still complained about
$mail->setFrom('from#example.com', 'Mailer');
saying
"MAIL FROM command failed: 550-Requested action not taken: mailbox unavailable550 Sender address is not allowed".
Replacing it by
$mail->setFrom('myname#web.de', 'via web.de');
did the job. But not all servers complain about that. Dogado.de for instance does not.
Finally:
$mail->SMTPDebug = 0; // suppresses server and client messages for production use
$mail->CharSet = "UTF-8"; // for correct umlauts
Summary:
The following code can be used on a local machine (Xampp, Netbeans) as well as on a remote server.
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// adjust path accordingly!
require 'vendor/PHPMailer/src/Exception.php';
require 'vendor/PHPMailer/src/PHPMailer.php';
require 'vendor/PHPMailer/src/SMTP.php';
// is ssl loaded? (test only):
//echo (extension_loaded('openssl')?'SSL loaded, ':'SSL not loaded, ')."\n";
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
$mail->SMTPDebug = 0; // production use
$mail->isSMTP(); // Set mailer to use SMTP
//=== using web.de ========================================
// adjust settings to your project!
$mail->Host = 'smtp.web.de'; //smtp1.example.com;smtp2.example.com';
// Specify main and backup SMTP servers
$mail->Username = 'myname#web.de'; // SMTP username
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('myname#web.de', 'über web.de'); // required by web.de
$mail->Password = 'mypassword'; // SMTP password
//==========================================================
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
//Recipients
$mail->addAddress('myname#kabelmail.de', 'my name'); // Add a recipient
$mail->addAddress('myname#web.de'); // Name is optional
$mail->CharSet = "UTF-8"; // because of umlauts
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
//Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold! groß süß ähnlich Ökonom</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients: groß süß ähnlich Ökonom';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}

ZipArchive::extractTo doesn't working on Windows Platform

I'm using the following code (Windows Hosting - Plesk/Win) :
<?php
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$path = getcwd();
$path = str_replace("/","\\",$path);
echo $path;
$zip->extractTo('E:\\Vhosts\\domain.com\\httpdocs\\test\\');
$zip->close();
echo 'Ok!';
} else {
echo 'Error!';
}
?>
When I run this code, the following message appears:
Warning:
ZipArchive::extractTo(E:\Vhosts\domain.com\httpdocs\test/image1.jpg)
[ziparchive.extractto]: failed to open stream: Permission denied in
E:\Vhosts\domain.com\httpdocs\test\extractphp.php on line 10
I don't now why this command put a slash before the unzipped file (test/image1.jpg).
How can I resolve this issue ?

simplexml_load_file error in PHP 5.3

I'm using the following code to read an RSS feed and output the results.
function home_page_parser($feedURL) {
$rss = simplexml_load_file($feedURL);
$i = 0;
echo "<ul>";
foreach ($rss->channel->item as $feedItem) {
$i++;
$myDate = ($feedItem->pubDate);
$dateForm = explode(" ", $myDate);
echo "<li class=\"rss-feed\">".$feedItem->title."<br />" .$feedItem->pubDate. "</li>";
if($i >= 3) break;
echo "</ul>";
}
}
It is working fine on my testing site at Rackspace Cloud running PHP 5.2
On the live site at Media Temple running PHP 5.3, I get the following errors:
Warning: simplexml_load_file() [function.simplexml-load-file]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /.../html/includes/functions.php on line 39
Warning: simplexml_load_file(http://www.chinaknowledge.com/Newswires/RSS_News/RSS_News.xml) [function.simplexml-load-file]: failed to open stream: no suitable wrapper could be found in /.../html/includes/functions.php on line 39
Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://www.chinaknowledge.com/Newswires/RSS_News/RSS_News.xml" in /.../html/includes/functions.php on line 39
Warning: Invalid argument supplied for foreach() in /.../html/includes/functions.php on line 44
Line 39 is this:
$rss = simplexml_load_file($feedURL);
What am I doing wrong or needs to change to work on 5.3?
The error is pretty descriptive dont you think?
http:// wrapper is disabled in the server configuration by
allow_url_fopen=0
You will need to edit the PHP configuration file and change the configuration allow_url_fopen. If you cant do this directly try ini_set()
Edit: As #evanmcd pointed out in the comments, this configuration can only be set in php.ini. PHP documentation reference.
This error comes due to "http:// wrapper is disabled in the server configuration by allow_url_fopen=0" .For avoiding this issue we need to override this setting to On instead off.In my view most of shared hosting servers do not allow you to do these setting through either ini_set('allow_url_fopen', 'on'); or htaccess overriding.So instead of trying these methods I suggest a way to fetch that feed is as follows.Using CURL we need to fetch the content of feed xml to a variable.Then process our simplexml file operations .
Example
$feed ='http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=mytwittername';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feed);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get the result of http query
$output = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_file($output);
If you are not allowed to edit php.ini in server you can use curl to get xml and read xml stirng as below.
function home_page_parser($feedURL) {
$rss = simplexml_load_file(curlXML($feedURL);
$i = 0;
echo "<ul>";
foreach ($rss->channel->item as $feedItem) {
$i++;
$myDate = ($feedItem->pubDate);
$dateForm = explode(" ", $myDate);
echo "<li class=\"rss-feed\">".$feedItem->title."<br />" .$feedItem->pubDate. "</li>";
if($i >= 3) break;
echo "</ul>";
}
}
function curlXML($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get the result of http query
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
ini_set("allow_url_fopen", 1);
This will set allow url open = On in php.ini file but you need to restart php in easyphp or xamp or wamp or in hosting.

NuSOAP on XAMPP with PHP5: failed to open stream

Hey guys, I have a problem (again). This time I am trying to use NuSoap w/ XAMPP 1.7.1 which includes PHP5 and MySQL ... I wrote a soap-client:
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/mysql/helloworld2.php');
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<p><b>Constructor error: ' . $err . '</b></p>';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$result = $client->call('hello', array('name' => 'Doro'));
// Check for a fault
if ($client->fault) {
echo '<p><b>Fault: ';
print_r($result);
echo '</b></p>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<p><b>Error: ' . $err . '</b></p>';
} else {
// Display the result
print_r($result);
}
}
?>
and my soap-server:
// Enable debugging *before* creating server instance
$debug = 1;
// Create the server instance
$server = new soap_server;
// Register the method to expose
$server->register('hello');
// Define the method as a PHP function
function hello($name) {
$dbhost = 'blah';
$dbuser = 'blub';
$dbpass = 'booboo';
try{
$conn = MYSQL_CONNECT($dbhost, $dbuser, $dbpass)
or die ('Error connecting to mysql');
if( !$conn ){
return 'Hello, '.$name.' ... too bad, I cannot connect to the db!';
}
else{
$dbname = 'soaperina';
MYSQL_SELECT_DB($dbname) or die('Error connecting to '.dbname);
$queryres = #mysql_db_query(
'response',
'SELECT * FROM farben');
return 'RESPONSE: <br>';
while( $arr = mysql_fetch_array( $queryres ) ){
return $arr["ID"]." - ".$arr["Farben"]." - ".$arr["Rating"]."<br>";
}
}
}
catch(Exception $e){
return 'Sorry, '.$name.', but that did not work at all!';
}
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
I know that PHP works, the Apache works, MySQL works ... it also works together, but when I try to make it work with NuSOAP it does not work. I get following:
Warning:
SoapClient::SoapClient(http://localhost/mysql/helloworld2.php)
[soapclient.soapclient]: failed to
open stream: Ein Verbindungsversuch
ist fehlgeschlagen, da die Gegenstelle
nach einer bestimmten Zeitspanne nicht
richtig reagiert hat, oder die
hergestellte Verbindung war
fehlerhaft, da der verbundene Host
nicht reagiert hat. in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 6
Warning: SoapClient::SoapClient()
[soapclient.soapclient]: I/O warning :
failed to load external entity
"http://localhost/mysql/helloworld2.php"
in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 6
Fatal error: Maximum execution time of
60 seconds exceeded in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 41
I have no idea what that is supposed to mean. I hope ya'll can help!!! Thnx in advance :)
I used NuSOAP version 1.7.3 with PHP5. In this NuSOAP 1.7.3, soapclient class renamed by nu_soapclient.
You can try this:
$client = new nusoap_client('http://localhost/mysql/helloworld2.php');
to give an answer to my own question: nusoap has a problem with php5 ... there are some answers and some solutions on the net (not many), but they didn't work with me. I downgraded to php4 and it works fine ...

Resources