simplexml_load_file error in PHP 5.3 - simplexml

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.

Related

Laravel - Sending mail not working, tinker hanging when trying to use sendmail via Laragon on Windows

In facts I found this question: Laragon and Laravel - sendmail not working ... but I decided to post a detailed new question, to get a response, that this issue is possibly a laravel bug... Thank you.
OS: Windows 10
Laravel Version: 8.75
PHP Version: 7.4.27
Database Driver & Version: sqlite
Description:
I trying around getting sendmail (Laragon) to work, but without luck.
File '.env' got adjusted to use sendmail instead of smtp on a fresh laravel project.
Steps To Reproduce:
created new laravel project
laravel new test
adjusted .env file:
MAIL_MAILER=sendmail
MAIL_SENDMAIL_PATH='C:\LARAGON\bin\sendmail\sendmail.exe -bs'
run command:
php artisan tinker
run tinker command:
Mail::raw('Hello World!', function($msg) {$msg->to('mail#example.com')->subject('Test Email'); });
After running the tinker command, the cmd is hanging...
Also tried different options on the sendmail flags:
sendmail.exe -t -i <<< tinker hangs
sendmail.exe -t <<< tinker hangs
sendmail.exe -bs <<< tinker hangs
I can see that the sendmail.exe is running (in task manager), but seems not be able to finish (waited several minutes).
Cancelation (CTRL-c) will close the tinker session and the sendmail.exe ist terminated.
With other php built-in mail function Laragon is working fine and also successfully catching the sent mails in the mail folder.
I always tried to clear configuration cache after every change of the .env file.
php artisan config:clear
Sending mail via php works fine as expected with the following code:
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "xyz#somedomain.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:abc#somedomain.com \r\n";
$header .= "Cc:afgh#somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>
Any help really appreciated.
Generally this happens when there is an authentication issue with sendmail.
Make sure you have setup sendmail with your gmail credentials, as suggested by the Laragon Documentation
Additionally, gmail disables "less secure apps" by default. Make sure your account has less secure apps enabled here too (or even better, use an Application Specific Password): https://myaccount.google.com/lesssecureapps
output phpinfo() and check if you have the exact location define on sendmail_path
you also need to define it inside config/mail.php like
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
or pull the value from your .env file MAIL_SENDMAIL_PATH
'path' => env('MAIL_SENDMAIL_PATH')
Additionally, you may try using smtp driver with localhost info in your .env file, you can see these details in phpinfo() as well
MAIL_DRIVER=smtp
MAIL_HOST=localhost
MAIL_PORT=25
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=null
try creating a route to send the email or dump the error
Route::get('/test-mail', function () {
try {
$send = \Illuminate\Support\Facades\Mail::mailer('sendmail')->send([], [], function ($message) {
$message
->to('to#email.com')
->from('from#email.com', 'Test')
->subject( 'My Subject' )
->setBody('Test Content', 'text/html');
});
dd($send);
} catch (\Exception $e ) {
throw new \Exception( $e->getMessage() );
}
});

symfony 4 app on heroku with remote database

I really need some help here hehe
Ok i got a symfony 4 application that is working perfectly in local environement.
I installed the app on heroku, but i want to access my Mysql database on my web hosting.
To be able to do that i had to install the Fixie app on heroku to have two ip adress and be able to whitelist those address for the remote access of my database.
The app is running good, but if i go to any links that have a call to do at the database i got a timeout.
I think the problem is in my index.php file, when installing Fixie you have to add code to the trust proxy
Heres what i have right now in my index.php file
<?php
use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
require dirname(__DIR__).'/config/bootstrap.php';
if ($_SERVER['APP_DEBUG']) {
umask(0000);
Debug::enable();
}
$trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false;
$trustedProxies = $trustedProxies ? explode(',', $trustedProxies) : [];
if($_SERVER['APP_ENV'] == 'prod') $trustedProxies[] = $_SERVER['REMOTE_ADDR'];
if($trustedProxies) {
Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_AWS_ELB);
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts([$trustedHosts]);
}
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Thats the log message i get when i try to access a page that have a call to the database
2019-11-28T22:13:12.218311+00:00 app[web.1]: [2019-11-28 22:12:42] request.INFO: Matched route "publicResultat". {"route":"publicResultat","route_parameters":{"_route":"publicResultat","_controller":"App\\Controller\\PublicController::index"},"request_uri":"https://jugement.herokuapp.com/public","method":"GET"} []
2019-11-28T22:13:12.218435+00:00 app[web.1]: [2019-11-28 22:12:42] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
2019-11-28T22:13:12.220033+00:00 app[web.1]: [2019-11-28 22:13:12] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\ConnectionException: "An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out" at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 93 {"exception":"[object] (Doctrine\\DBAL\\Exception\\ConnectionException(code: 0): An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:93, Doctrine\\DBAL\\Driver\\PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31, PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27)"} []
When you install fixie in heroku you have to add something this is the example they give for php but i don't understand how to do that in my symfony app
PHP cURL is the easiest way to get your PHP application working correctly with Fixie. Here’s how:
<?php
function proxyRequest() {
$fixieUrl = getenv("FIXIE_URL");
$parsedFixieUrl = parse_url($fixieUrl);
$proxy = $parsedFixieUrl['host'].":".$parsedFixieUrl['port'];
$proxyAuth = $parsedFixieUrl['user'].":".$parsedFixieUrl['pass'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyAuth);
curl_close($ch);
}
$response = proxyRequest();
print_r($response);
?>
Hope that i am clear on my problem
any help would be very useful
I also found strange that i have no header present when the call is done
Request URL: https://jugement.herokuapp.com/public
Referrer Policy: no-referrer-when-downgrade
Thats all i have in the header

Laravel 5.3 response()->download - File(.doc, .docx) becomes unreadable after downloading

Laravel 5.3
When I download a file (.doc, .docx) from my storage folder it becomes unreadable. If I go to the local folder and open the file however it is valid and readable.
I am using the standard download function, using headers and stuff.. Have a look at my code:
$fileNameGenerate = 'example_filename';
$fileArr = [ 'wierd_filename', 'docx' ];
$cvPath = storage_path('app/example_folder/subfolder/wierd_filename.docx');
$headers = array(
'Content-Type: application/' . $fileArr[1],
);
try {
return response()->download($cvPath, $fileNameGenerate . '.' . $fileArr[1], $headers);
} catch (\Exception $e) {
//Error
return redirect()->back()->with('error', trans('locale.file_does_not_exists'));
}
Does anyone know what is wrong here? Thank you!
Update: I removed headers, it doesn't work with or without them.
Here is how the files render in the 2 different cases:
Try this
public function getDownload()
{
//doc file is stored under storagepath/download/info.docx
$file= pathofstorage. "/download/info.docx";
return response()->download($file);
}
I added:
ob_end_clean();
before:
response -> download
and it worked for me.

CodeIgniter run library before database settings

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

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