Images not writing with my routines

It just another way to get img base64.

Yes i see but your not getting the base code from the file image like i am which didnt work

Edwin i mean this bit to get it from file not from page

var image = document.createElement("img");
    image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png';

    var base64file1;
   
    toDataURL("/images/nowplaying_artwork_2.png", function(data) {
        then(dataUrl => console.log('RESULT:', dataUrl));
        base64file1 = dataUrl;
        });
    
    image.remove();

I have no idea why this doesn’t work
Hugs

i am just trying

 var image = document.createElement("#img999");
    image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png';

    var base64file1;
    var base64file1 = $("img999").attr("src");

It may can’t not the url issue. because you declared the variable out of function.

Note: javascript run on web browser client. Not at server
Combine with xhr ajax to do save on file then.

You made everything too complicated, but it could be simpler
as far as I understand, you actually have something similar to an online radio station.

I just don’t know the purpose of all that you are doing
 is it some project of yours that you hope will become commercial or do you just want to play songs on the air?

if it’s the first - then I have a feeling that you use us to build your code
if it is the other - there is a lot of ready-made code for “radio stations”


I think it’s much simpler to use the user’s browser, which will find the album cover itself (rather than going through the server and some uploads, etc.)



here is an example for

try to change the text in that URL (search data)

and that search returns the album cover img

which you then put in a DIV (you can refresh it with JS as well)

means:

  1. you need to know the active song that is playing (via JS ?)
  2. grab the name of the album you wrote from your list
  3. return that data (album string) to some JS that will do a search and when it gets albumArt.img
  4. make an update of the image in a certain div = img src (again via JS in the user’s browser / assign some variable to img src - or use jQuery)

and then everything is simply dynamically changed automatically (next song = next cover)


As far as I can see, this uses the Spotify API
 probably you can request an API key there, etc


means, in short, everything is done by the user’s browser

more info + JS + other

There are probably better solutions, just search GitHub or online in general.

And all that you do will never come to the fore
because the front page as well as the code is outdated,
the layout of your site is not mobile-friendly, I mentioned that you have over 500 errors,
PHP that you have, I think it will cause a lot of REQs to the server and internal work that will later result in suspension due to exceeding the limit, etc.

So it is in your interest that the user’s browser does as many actions as possible
and it’s easier for you to maintain the site (playlist - album covers, etc) that way as well as code.

4 Likes

@anon14276620 In short if you’re looking for cover, do what OxyDac has said.
However take a look at this nice api

It can fetch cover, singer name, album, release and much more.
This is called a song’s metadata.

1 Like

Well Its not true i had everything shut down it had all night to resolve it selvf opened up in chrome wrong like this


I then opened image from this page right click


refreshed this page

Went back to original refreshed that too


it does this on my fetch page too
running http://www.deniserose.epizy.com/fetch_sql.php You should not this has no scripts on it but does same not fetching image that has changed in your cache. I can in formed as for over complicating this most of it has run before on this other site who wont surrender my data legally as part of article 12/. There fore I am experiencing cost of my time .

It is doing this every-time music changes which updated image by ftp as your write routines wont work from php see my previous post and will not upload and run fetch as far as I can tell . It looks at image on screen and image on disk to check they have same base64 they both according to f12 debugger come back with both empty even following an example Edwin did I presume this is as he is not using jscript in separate file . I cant get this to work currently even on these basic pages. As you system is not returning what i expect to give a base 64 string it says in debugger both are undefined . I did not understand what Edwin said next

My applications provide song art and uploads them separate with track info I expected my php code to do this but it fails with fwrite( as far as i can tell as I explained I am uploading this as ftp as it failed i don’t need to grab art else where its sent up by command to your sql service and server with add_track.php it just doesn’t to seem to work either as it appears your system is having problems locating image after it is ftp’d up to its location as your sysem wont support fwrite(

I don’t think i understand this sorry hugs D

the ahr ajax doe not do this

All file and sql are places on the system by add_track.php , however for some reason fwrite( is not supported and sdoesnt work so I am forced to ftp the image up to server location in /images/nowplaying_artwork_2.png which produces no error

my function in /js/fetch_updater.js in the debugger is loaded and run bbut does not provide base 64 information I dont know why

function CheckResponse(transport)
{
    var content = transport.responseText;
    
    var image = document.createElement("img");
    image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png';

    var base64file1;
   
    toDataURL("/images/nowplaying_artwork_2.png", function(data) {
        then(dataUrl => console.log('RESULT:', dataUrl));
        base64file1 = dataUrl;
        });
    
    //image.remove();
    //base64file1 = base64_encode(base64file1);
    //var base64file2 =  document.getElementById("outer_img").GetElementsById("np_track_artwork").src.data;
    var base64file2 = $("img#np_track_artwork").attr("src", "data:image/png;base64,"+data);
    
    if(base64file1 != base64file2) {
    

       
      gCurrentCheck = content;
       
      new Ajax.Request(gContentUrl, {
            method: "get",onSuccess:function t() { 
                this.document.getElementById(gUpdateDiv).innerHTML = t.responseText;  /*t.response.json()*/
            }
      });
      
      $time = new Date().getTime();
      new Ajax.Request("outer_img2", {
          method: "get",onSuccess:function s() { 
                this.document.getElementById("outer_img").innerHTML = "<img id=#np_track_artwork src=/images/nowplaying_artwork_2.png?t="+$time+" alt='Playing track artwork' width=200 height=200>"}
      });
    
    }
  
}

Additionally my main page reading from the sql database is loosing information

And here when refreshed after several songs looses the information in red and some songs there appear to be no integrity in data?

The data base shows Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available . But the time is for a unknow reason not unique suggesting its been changed when i run

ALTER TABLE epiz_33087480__song_history.played_songs DROP INDEX datetime, ADD PRIMARY KEY (datetime) USING BTREE;

I get

# Error

**SQL query:**

``

```
ALTER TABLE `epiz_33087480__song_history`.`played_songs` DROP INDEX `datetime`, ADD PRIMARY KEY (`datetime`) USING BTREE
```

**MySQL said:** [![Documentation](http://185.27.134.10/themes/dot.gif "Documentation")](http://185.27.134.10/url.php?url=https%3A%2F%2Fdev.mysql.com%2Fdoc%2Frefman%2F5.7%2Fen%2Ferror-messages-server.html)

`#1062 - Duplicate entry '2022-12-03 14:15:58' for key 'PRIMARY'`

I have deleted all data truncating it to put new primary key in

Exactly THAT is the complication!

instead of the client browser doing it


What you are doing is the same as if someone has a security camera and uploads images through FTP here to the server (which is not allowed - too many connections to FTP)

I don’t know why album covers matter at all :slight_smile:

Here is my example of behavior:
I’m doing something on the computer and I want music to play along the way

I go to your page, press play, and minimize that window
and I continue to work on the computer

I don’t constantly look at your page or ask myself “hmm, I’m really interested in what kind of album cover this song has”

if I’m interested, I can find it on google.

what would be better in my opinion is if you have a history in the list (a song that was playing 5 minutes ago but is no longer visible because it has disappeared) so that if I like a song I can find it.

6 Likes

Everything I see here only strengthens my belief that this is just caused by browser cache. The fact that you could refresh the page to fetch the latest image means that the image has been correctly written to disk and is being served to the visitor browser if the browser requests this file, which it doesn’t because our hosting enforces quite strong browser cache by default.

I don’t see any evidence that your upload code is not working or that there is something wrong with the server storage.

The simplest way to fix this is to add a query parameter to the URL, and the easiest way to do this is through the PHP code. Simply having any query parameter will disabled caching functionality. So simply changing the code to this will result in browsers always downloading the latest image:

<img  src='images/nowplaying_artwork_2.png?version=latest' ...>

If you want to make it fancy and make sure you’re really getting a different URL each time, you could do it like this:

<img  src='images/nowplaying_artwork_2.png?t=<?= time() ?>' ...>

But again, this isn’t necessary because just having a query string disables all caching.


There are a lot of ways to make this nicer though.

The LastFM API recommendations are really cool additions to help you make sure you’ll have album art for all your tracks without having to manage the images yourself.

If you do want to mange the images yourself and still want to leverage browser cache, the most common way to do this is to simply store the images per song under a unique URL. So instead of storing every image as nowplaying_artwork_2.png, you could also store the image as pet-shop-boys-a-different-point-of-view.png or track-1234.png, where the current track depends on the results in the database.

5 Likes

My album data is fed else where

my update add record is as follows currently

<!DOCOTYPE html>
<head>
    <title>Add Record</title>
    <meta charset="UTF-8">
    
</head>
<?php
$servername = "sql111.epizy.com";
$username = "epiz_33087480";
$password = "";
$dbname = "epiz_33087480__song_history";


//uses https://www.ascii-code.com/
function _clean($clean) {
$clean = utf8_encode($clean); 
$array_find =    array("Ăš",      "ĂȘ",      "Ă©",   "(" , ")" ,   "," , "#" ,  "'" , "@" , ";" , ":" , "&",".");
$array_replace = array("e","&ecirc","&eacute","(",")","","&#35","&#39","@","&#59","&#58","&","&#46");
$cleaned  = str_replace( $array_find,$array_replace, $clean);
return $cleaned;
}

function clean_Num($num_cl) {
 return str_replace(array( "0","1","2","3","4","5","6","7","8","9"),array("\x00","\x01","\x02","\x03","\x04","\x05","\x06","\x07","\x08","\x09"),$str);
   
}
/*$bpm = $_REQUEST['bpm'];
$length =$_REQUEST['len'];
$artist = $_REQUEST['artist'];
$artist= _clean($artist);
$title = $_REQUEST['title'];
$title= _clean($title);
$album = $_REQUEST['album'];
$album= _clean( $album);
$comment  =$_REQUEST['comment'];
$comment= _clean($comment);
*/

//MSQ 8.0
 $bpm = /*isset(*/$_REQUEST['bpm'];//) : throw new \InvalidArgumentException('value not set bpm.');
 $length = /*isset(*/$_REQUEST['len'];// : throw new \InvalidArgumentException('value not set len.');
 $artist = /*isset(*/$_REQUEST['artist'];//) : throw new \InvalidArgumentException('value not set artist.');
$artist= _clean($artist);
$title = /*isset(*/$_REQUEST['title'];//) : throw new \InvalidArgumentException('value not set title.');
$title= _clean($title);
$album = /*isset(*/$_REQUEST['album'];//) : throw new \InvalidArgumentException('value not set album.');
$album= _clean( $album);
$comment = $_REQUEST['comment'];
$comment= _clean($comment);
$genre= $_REQUEST['genre'];
$listeners =  $_REQUEST['listeners'];

// Does not cater for ' " / 3 & in input ' presently.


// note there is now num_rows  in PDO so we have to calculate.
try {
  $n = 0;    
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "SELECT COUNT(`datetime`) FROM `played_songs` ORDER BY `datetime` ASC";
  $result = $conn->query($sql); // Use query as we are returning records.
  $row=$result->fetch();
  $n = $row["COUNT(`datetime`)"] - 150;
  if( $n >1) { $conn->exec("DELETE FROM `played_songs` LIMIT ".$n );}
  
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
// Add record to database.
$base64="";
if($artwork2 !== false) {$base64 = base64_decode($artwork2);    
} else {
        ReturnError(500, 'Failed to write artwork to a file');
}

var image = document.createElement("img");
image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png?tr=w-200,h-200'
$b64Data= base64_decode($artwork);
const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: contentType});

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $datetime =date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);

   $sql = "INSERT INTO `played_songs` (`datetime`,`song`, `artist`, `album`, `length`, `bpm`, `listeners`,`track_user_num`,`track_user_rating`,`genre`,`comment`,`ImageBase64`) VALUES ('$datetime','$title','$artist', '$album', '$length', '$bpm','$listeners',0,0,'$genre', '$comment','blob')";
  $conn->exec($sql);
  echo "New record created successfully";
} catch(PDOException $e) {
  ReturnError(500, 'Failed to write artwork to a file'. $e->getMessage());
}
image.remove();
$conn = null;

//album cover
$artwork = isset($_REQUEST['artwork']) && ($_REQUEST['artwork'] !== '') ? $_REQUEST['artwork'] : false;
if ($artwork !== false) {
    $artwork = base64_decode($artwork);
    $r = fopen('images/nowplaying_artwork_2.png', 'wb');
    if ($r !== false) {
        fwrite($r, $artwork);
        fclose($r);
    } else {
        ReturnError(500, 'Failed to write artwork to a file');
    }
    
} else ReturnError(500, 'Failed to supply artwork in url');

function ReturnError($code, $text) {
    $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
    header($protocol . ' ' . $code . ' ' . $text);
    exit();
}

?>

The blob version is here but didnt work but its here

<!DOCOTYPE html>
<head>
    <title>Add Record</title>
    <meta charset="UTF-8">
    
</head>
<?php
$servername = "sql111.epizy.com";
$username = "epiz_33087480";
$password = "";
$dbname = "epiz_33087480__song_history";


//uses https://www.ascii-code.com/
function _clean($clean) {
$clean = utf8_encode($clean); 
$array_find =    array("Ăš",      "ĂȘ",      "Ă©",   "(" , ")" ,   "," , "#" ,  "'" , "@" , ";" , ":" , "&",".");
$array_replace = array("e","&ecirc","&eacute","(",")","","&#35","&#39","@","&#59","&#58","&","&#46");
$cleaned  = str_replace( $array_find,$array_replace, $clean);
return $cleaned;
}

function clean_Num($num_cl) {
 return str_replace(array( "0","1","2","3","4","5","6","7","8","9"),array("\x00","\x01","\x02","\x03","\x04","\x05","\x06","\x07","\x08","\x09"),$str);
   
}
/*$bpm = $_REQUEST['bpm'];
$length =$_REQUEST['len'];
$artist = $_REQUEST['artist'];
$artist= _clean($artist);
$title = $_REQUEST['title'];
$title= _clean($title);
$album = $_REQUEST['album'];
$album= _clean( $album);
$comment  =$_REQUEST['comment'];
$comment= _clean($comment);
*/

//MSQ 8.0
 $bpm = /*isset(*/$_REQUEST['bpm'];//) : throw new \InvalidArgumentException('value not set bpm.');
 $length = /*isset(*/$_REQUEST['len'];// : throw new \InvalidArgumentException('value not set len.');
 $artist = /*isset(*/$_REQUEST['artist'];//) : throw new \InvalidArgumentException('value not set artist.');
$artist= _clean($artist);
$title = /*isset(*/$_REQUEST['title'];//) : throw new \InvalidArgumentException('value not set title.');
$title= _clean($title);
$album = /*isset(*/$_REQUEST['album'];//) : throw new \InvalidArgumentException('value not set album.');
$album= _clean( $album);
$comment = $_REQUEST['comment'];
$comment= _clean($comment);
$genre= $_REQUEST['genre'];
$listeners =  $_REQUEST['listeners'];

// Does not cater for ' " / 3 & in input ' presently.


// note there is now num_rows  in PDO so we have to calculate.
try {
  $n = 0;    
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "SELECT COUNT(`datetime`) FROM `played_songs` ORDER BY `datetime` ASC";
  $result = $conn->query($sql); // Use query as we are returning records.
  $row=$result->fetch();
  $n = $row["COUNT(`datetime`)"] - 150;
  if( $n >1) { $conn->exec("DELETE FROM `played_songs` LIMIT ".$n );}
  
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
// Add record to database.
$base64="";
if($artwork2 !== false) {$base64 = base64_decode($artwork2);    
} else {
        ReturnError(500, 'Failed to write artwork to a file');
}

var image = document.createElement("img");
image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png?tr=w-200,h-200'
$b64Data= base64_decode($artwork);
const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: contentType});

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $datetime =date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);

   $sql = "INSERT INTO `played_songs` (`datetime`,`song`, `artist`, `album`, `length`, `bpm`, `listeners`,`track_user_num`,`track_user_rating`,`genre`,`comment`,`ImageBase64`) VALUES ('$datetime','$title','$artist', '$album', '$length', '$bpm','$listeners',0,0,'$genre', '$comment','blob')";
  $conn->exec($sql);
  echo "New record created successfully";
} catch(PDOException $e) {
  ReturnError(500, 'Failed to write artwork to a file'. $e->getMessage());
}
image.remove();
$conn = null;

//album cover
$artwork = isset($_REQUEST['artwork']) && ($_REQUEST['artwork'] !== '') ? $_REQUEST['artwork'] : false;
if ($artwork !== false) {
    $artwork = base64_decode($artwork);
    $r = fopen('images/nowplaying_artwork_2.png', 'wb');
    if ($r !== false) {
        fwrite($r, $artwork);
        fclose($r);
    } else {
        ReturnError(500, 'Failed to write artwork to a file');
    }
    
} else ReturnError(500, 'Failed to supply artwork in url');

function ReturnError($code, $text) {
    $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
    header($protocol . ' ' . $code . ' ' . $text);
    exit();
}

?>

It should work but doesn’t its behaving a l little better but still no refresh see below

Thank you admin
I am already doing this but the java script is not working on your site in my file js/fetch_updater.js so it never fires up properly only to run and do nothing as the return of the base64 is not being returned but gives result in debugger ‘Unidentified’ meaning i have no data to compare what is on screen to what is on file. I should point out my add_track.php reports no error

Thank you Admin , I put in <img src='images/nowplaying_artwork_2.png?t=<?php echo time();?> id=‘np_track_artwork’ i now refreshes the image when you refresh the page but the fetch is stll not updating it not returning base64 data from screen and from server copy

in regard to my blob version of Add_track fails but not on the command line
I am wondering if this is better practice to create record then upload blob to sql by amending record?