Extract xml artist name nusic for string "SONGTITLE" for
<div class="data">
<p class="music">Loading</p>
<p class="singer">Loading</p>
</div>
PHP Warning: Attempt to read property "SONGTITLE" on bool in
Erro part code
$music = htmlspecialchars(addslashes($shoutcast->SONGTITLE));
Userd php 5,6
====
<?php
function Streaming(){
global $radio;
$shoutcast = simplexml_load_file("http://live.radiosoundfm.com.br:8578/stats?sid=1");
$music = htmlspecialchars(addslashes($shoutcast->SONGTITLE));
$singer = ''; $name = $music;
if(strpos($music, '-') !== false && substr_count($music, '-') == 1){
$data = explode('-', $music);
$singer = trim($data[0]) != '' ? trim($data[0]) : '';
$name = trim($data[1]) != '' ? trim($data[1]) : '';
}
$data = array(
'music' => $music,
'name' => $name,
'singer' => $singer
);
return $data;
}
https://github.com/saniellocutor/radiosoundfm.com.br-Site
PHP Warning: Attempt to read property "SONGTITLE" on bool in
The first warning message indicates that the XML load failed and the function returned false. You need to add some error validation at this point.
$shoutcast = simplexml_load_file(...);
if ($shoutcast) {
// read XML
} else {
// log error
}
Also, some servers expect valid user agents. You can use libxml_set_streams_context() provide additional request headers.
PHP Deprecated: addslashes(): Passing null to parameter #1 ($string) of type string is deprecated
So $shoutcast is false and $shoutcast->SONGTITLE is an undefined value. However addslashes() expects a mandatory string parameter in the current PHP versions. You old PHP still allows it, but it warn about the change in newer versions.
The whole line $music = htmlspecialchars(addslashes($shoutcast->SONGTITLE)); looks like pre-emptive escaping. Don't do that. Only escape if you know the target and just before you insert it. Most of the time here are better options (Prepared statements for the database, DOM for HTML outputs, ...).
Reading a string value from SimpleXMLElement:
The 'SimpleXMLElement' instance: $shoutcast->SONGTITLE;
Fallback for missing node: $shoutcast->SONGTITLE ?? '';
Cast to string: (string)($shoutcast->SONGTITLE ?? '');
Assign to variable: $music = (string)($shoutcast->SONGTITLE ?? '');
Related
I got this error every time run the application. I got everything ok. I have checked every steps and I got nothing. is it for php update ? I am using php 8. Here is my code.
class ViewProducts extends AddNewProduct
{
private $to_array2, $to_array1;
public function viewAllProducts() {
// get image name
$text_path = $this->getTextFilePath();
//extract file contents
$file_contents = file_get_contents($text_path);
// convert string to array
$this->to_array1 = explode('$', $file_contents);
foreach ($this->to_array1 as $item => $value) {
$this->to_array2 = explode(',', $value);
if(isset($this->to_array2[0])){
echo '<pre>';
var_dump($this->to_array2[$item][$value]);
echo '</pre>';
//$to_array[$item]['id'] = $this->to_array2[0];
//$to_array[$item]['name'] = $this->to_array2[1];
} else {
echo 'Nothing found';
}
}
return $this->to_array2;
}
}
Error details:
Please fill with data.
Warning: Uninitialized string offset 11 in D:\PROJECTS\IDE\xampp\htdocs\tenth-project\app\classes\ViewProducts.php on line 24
string(0) ""
Fatal error: Uncaught TypeError: Cannot access offset of type string on string in D:\PROJECTS\IDE\xampp\htdocs\tenth-project\app\classes\ViewProducts.php:24
Stack trace:
#0 D:\PROJECTS\IDE\xampp\htdocs\tenth-project\pages\action.php(24): App\classes\ViewProducts->viewAllProducts()
#1 {main}
thrown in D:\PROJECTS\IDE\xampp\htdocs\tenth-project\app\classes\ViewProducts.php on line 24
Look carefully at these two lines:
this->to_array2 = explode(',', $value);
And:
var_dump($this->to_array2[$item][$value]);
You have a string, which you split into a list of parts; you then try to access that list as though it was a two-dimensional array, using the original string as one of the keys. This doesn't even begin to make sense.
Unless you've changed them to hide details of the real program, one of your problems is probably that your variable names are poorly chosen. See how much clearer this is:
$item_list = explode('$', $file_contents);
foreach ($item_list as $item_number => $item_details) {
$field_list = explode(',', $item_details);
if(isset($field_list[0])){
echo '<pre>';
var_dump($field_list[$item_number][$item_details]); // clearly nonsense
echo '</pre>'!
} else {
echo 'Nothing found';
}
}
With knowledge of what the program is actually doing, you can probably do better than "item" and "field".
We are a tennis and squash club running nBill, an invoicing system that is no longer actively supported. I nursed it on upgrade from PHP 5 to 7 but on further upgrading to PHP7.1 the application does not load and I get the following fatal error message:
Fatal error: Only variables can be passed by reference in /xxxxxxxx/public_html/administrator/components/com_nbill/classes/base/data_mapper.php on line 98.
I understand what is wrong but I cannot solve it, it is beyond my limited knowledge of PHP. Removing the section of code enables the application to work and then it seems to work fine.
The statement at fault is:
$string = nbf_common::get_param(array($key=>$value), $key, '', false, (string)#$col[0]->encode_html != "false", (string)#$col[0]->allow_html == "true", (string)#$col[0]->allow_html == "true");
The full section of code reads:
* Return an appropriate string to use for the value in an SQL statement
(escaped, or intval'd as appropriate for the data type, based on the XML
schema file, if found, or just treated as a string [and escaped] otherwise)
* #param string $key Column name
* #param mixed $value Literal value
*/
protected function getValueSqlString($key, $value)
{
$string = "";
if ($this->schema)
{
$col = $schema->xpath("columns/column[#name='$key']");
switch (#$col->type)
{
case "int":
case "tinyint":
case "smallint":
case "mediumint":
case "bigint":
case "integer":
case "long":
$string = strval(intval($value));
break;
default:
$string = nbf_common::get_param(array($key=>$value),
$key, '', false, (string)#$col[0]->encode_html != "false",
(string)#$col[0]->allow_html == "true",
(string)#$col[0]->allow_html == "true");
break;
}
}
if (!$string) {
$string = "'" . $this->db->getEscaped($value) . "'";
}
return $string;
}
/**
Any help most gratefully received. Note we are actively seeking a replacement invoicing system and are trialling CBSubs.
CBSheen
<?php
$array = array($key=>$value);
$string = nbf_common::get_param(strtolower(array_pop($array)), $key, '', false, (string)#$col[0]->encode_html != "false", (string)#$col[0]->allow_html == "true", (string)#$col[0]->allow_html == "true");
Try the above code. I am not a joomla expert but based on your error i think the problem is when you try to pass an array inside the get_param function.
nbf_common::get_param()
Look this function up, see which of the params is passed by reference, then check if the value actually passed as that parameter can be passed as reference. It is probably what pr1nc3 says.
PHP Version: 7.0
Script is sent data from a different website.
For some reason, the data is not being inserted into the database like it should be, and I don't think I have any SQL errors (this is done with PDO).
Here is the included functions code:
<?php
function escape($string){
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
?>
Script Code:
<html>
<head>
<title>Data from Roblox</title>
<h3>Data from Roblox</h3>
</head>
<body>
<?php
include '../includes/connection.php';
include '../scripts/functions.php'; //Remove if unknown error as well as the escapes
error_reporting(E_ALL);
ini_set('display_errors', 1);
$array = json_decode(file_get_contents('php://input'),1);
$SenderName = escape($array['SenderName']);
$SenderID = escape($array['SenderID']);
$PlayerName = escape($array['PlayerName']);
$PlayerID = escape($array['PlayerID']);
$Reason = escape($array['Reason']);
$PlaceLink = escape($array['PlaceLink']);
if(!$Reason){ $Reason = "Reason not provided."; }
if($SenderName !=NULL and $SenderID != NULL and $PlayerName != NULL and $PlayerID !=NULL and $PlaceLink !=NULL){
$query = $handler->prepare("INSERT INTO PlayerBans (`ID`, `Username`,`Reason`, `BannedDate`, `BannedBy`, `BannedAt`) VALUES (:pid, :pname, :reason, NOW(), :sname, :pl)");
$query->bindParam(':pid', $PlayerID);
$query->bindParam(':pname', $PlayerName);
$query->bindParam(':reason', $Reason);
$sender = $SenderName . " - " . $SenderID;
$query->bindParam(':sname', $sender);
$query->bindParam(':pl', $PlaceLink);
$query->execute();
}
?>
</body>
</html>
When go to the script URL in my web browser, the HTML shows up, and no errors.
Your problem is almost certainly with the request coming in, but here are a few issues you could address with your code.
htmlspecialchars() is not for inserting into a database. It's used when you want to display something as HTML.
none of those values you're checking will ever be null, because you're running them through htmlspecialchars() which returns a string.
there's no need to use PDOStatement::bindParam() unless you need to do something special with data types. Just pass an array to PDOStatement::execute() instead.
it sounds like you're not recording any error messages. If you aren't using this page interactively, you need to have some way to know if there's a problem.
With that in mind, I'd recommend trying this:
<?php
include("../includes/connection.php");
error_reporting(E_ALL);
ini_set("display_errors", true);
ini_set("error_log", "/var/log/php.log");
$json = file_get_contents("php://input");
$array = json_decode($json, true);
$SenderName = $array['SenderName'] ?? null;
$SenderID = $array['SenderID'] ?? null;
$PlayerName = $array['PlayerName'] ?? null;
$PlayerID = $array['PlayerID'] ?? null;
$Reason = $array['Reason'] ?? "Reason not provided";
$PlaceLink = $array['PlaceLink'] ?? null;
if($SenderName !== null && $SenderID !== null && $PlayerName !== null && $PlayerID !== null && $PlaceLink !== null) {
// prepare using ? for a shorter query; don't mix placeholders with other values
$query = $handler->prepare("INSERT INTO PlayerBans (`ID`, `Username`,`Reason`, `BannedBy`, `BannedAt`, `BannedDate`) VALUES (?,?,?,?,?,NOW())");
// double quotes interpolate variables!
$sender = "$SenderName - $SenderID";
// pass the values directly to execute
$result = $query->execute([$PlayerID, $PlayerName, $Reason, $sender, $PlaceLink]);
// check the result of this call and log some details if there's a problem
if (!$result) {
$e = $query->errorInfo();
error_log("SQL Error $e[0]: $e[2] ($e[1]) while inserting data: $json");
}
}
?>
You'll want to make sure that you create the log file ahead of time, with the correct permissions for your web server to be able to write to it. On a Linux platform this might look like sudo touch /var/log/php && sudo chown www-data /var/log/php
Also I'm assuming you're using a current version of PHP that supports the null coalesce operator; you'll need to replace $foo = $bar ?? null with $foo = isset($bar) ? $bar : null if that's not the case.
One more point, if each user on your system has an entry in a user table, you should really have UserID and SenderID columns in the PlayerBans table that are foreign keys back to your users table. If you're querying this column regularly it makes a whole lot more sense than having an unstructured text column.
I'm building a simple JS terminal shell emulator which posts its commands via AJAX to PHP.
Please leave security aside, this is only for learning and demo purposes.
Now my problem is, str_replace() won't work as expected, in fact, it returns the unchanged input string. It should work like this:
The name of this host is $hostname --> Yes, this string contains a variable --> Replace $hostname with testserver --> return The name of this host is testserver
What am I doing wrong?
This is my respond script for echo and export:
<?
// get environment variables from JSON
$vars = json_decode(file_get_contents('environment.json'), true);
// get request params
$method = $_SERVER['REQUEST_METHOD'];
$action = $_POST['action'];
$data = $_POST['data'];
switch ($action) {
case 'echo':
$cmd = $data;
// if the string in question contains a variable, eg. "the time is $time"
if (strpos($cmd,'$')) {
$output = '';
// for each environment variable as variable => value
foreach ($vars as $var => $val) {
// replace every variable in the string with its value in the command
$output = str_replace($var,$val,$cmd);
}
echo $output;
} else {
// if it does not contain a variable, answer back the query string
// ("echo " gets stripped off in JS)
echo $cmd;
}
break;
case 'export':
// separate a variable declaration by delimiter "="
$cmd = explode('=',$data);
// add a $-sign to the first word which will be our new variable
$var = '$' . array_shift($cmd);
// grab our variable value from the array
$val = array_shift($cmd);
// now append everything to the $vars-array and save it to the JSON-file
$vars[$var] = $val;
file_put_contents("environment.json",json_encode($vars));
break;
}
Better using :
if (strpos($cmd,'$') !== false) {
Then, every single replace will take the "first" data as its input data. You should proceed like this :
$output = $cmd;
// for each environment variable as variable => value
foreach ($vars as $var => $val) {
// replace every variable in the string with its value in the command
$output = str_replace($var, $val, $output);
}
I'm making a link and text service, but I have a problem, which is: there is only 1 input text form, and the user could paste something like this:
http:// asdf .com - which would register as a link, or 'asdf http:// test .com' because of the http://, it would register as a url, or
asdf - which would register as a string, because it doesn't contain http://
BUT my problem arises when the user writes something like:
asdf http://asdf.com, which in my current program outputs a "url" value. I've been experimenting for about an hour now, and I've got 3 bits of code (they were all in the same document being commented, so forgive me if they give errors!)
<?
$str = $_POST['paste'];
if(stristr($str, "http://")) {
$type = "url";
}
if(stristr($str, "https://")) {
$type = "url";
}
if($type!="url") {
$type = "string";
}
?>
Next:
<?
$type = "url";
if($type=="url"){
$t = substr($str, 8);
if(stristr($t, "https://")==$t){
$type = "url";}
if(stristr($t, "https://")==$t){
$type = "url";}
if(stristr($t, "http://")!=$t){
$type = "string";}
if(stristr($t, "https://")!=$t){
$type = "string";}
}
echo $type;
?>
Next:
<?
$url = "hasttp://cake.com";
if(stristr($url, "http://")=="") {
$type = "string"; } else {
$type = "url";
$sus = 1;}
if(stristr($url, "http://")==$url) {
$type = "url"; }
if($sus==1) {
$r = substr($url, 7);
if(stristr($r,"http://")!="http://") {
$type = "url"; }
if($r=="") {
$type = "string";
}
}
echo $type;
?>
I have no clue how I could go about classifying a string like 'asdf http://asdf.com' as a string, whilst classifying 'asdf' as a string, and classifying 'http://asdf.com' as a url.. Another idea I haven't tried yet is strpos, but that's what I'm working on now.
Any ideas?
Thanks alot! :)
Some parts of this question are getting cut off for some reason, apologies!
$type = '';
if (preg_match('%^https?://[^\s]+$%', $url)) {
$type = 'url';
} else {
$type = 'string';
}
This will match any value which starts with http:// or https://, and does not contain any space in it as type url. If the value does not start with http:// or https://, or it contains a space in it, it will be type string.
PHP parse_url is your function:
On seriously malformed URLs, parse_url() may return FALSE.
If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:
scheme - e.g. http
host
port
user
pass
path
query - after the question mark ?
fragment - after the hashmark #
If the component parameter is specified, parse_url() returns a string (or an integer, in the case of PHP_URL_PORT) instead of an array. If the requested component doesn't exist within the given URL, NULL will be returned.
If I'm understanding the problem correctly you want to detect when the user inputs both a string and a url and parse each of them correspondingly.
Try using explode(" ", $userInput);, this will return an array containing all strings separated by a space. Than you can check that for each element in the array and set the type.
$type = strpos($str, 'http') === 0 ? 'url' : 'string':
The strpos function returns the position of a match within a string or FALSE if no match. The tripple equals checks that the result does not only translates to 0 (as FALSE would have done), but that it is in fact integer as well (i.e., the string begins with http).
You could also use something like
switch (true) {
case strpos(trim($str), 'http://') === 0:
case strpos(trim($str), 'https://') === 0:
$type = 'url';
break;
default:
$type = 'string';
break; // I know this is not needed, but it is pretty :-)
}
You should use a regular expression to check if the string starts with http
if(preg_match('/^http/',$string_to_check)){
//this is a url
}