lundi 30 mars 2015

PHP Replace multiple parts of a string

I'm building an article poster for my small website, and the problem I've come across is being able to upload images, so I wanted it to be much easier for users by letting them simply dragging images into the article field which would be placed in base64 image format.


What I want to do is once the user is done writing the article, they'll submit it and while it is being submitted, the php script will look for image src instances, grab the base64 image url and execute a script to upload that base64 image and then replace the article html with a http:// url instead of a base64:image URI


Here is the script I'm using to return a url instead of a base64 encoded URI: function get_string_between($string, $start, $end){



$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
function generateRandomString($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function base64_to_jpeg($base64_string, $output_file) {

$type = get_string_between($base64_string, "image/", ";");
$output_dir = "../images/";
$output_file = "$output_dir$output_file.$type";
$ifp = fopen($output_file, "wb");

$data = explode(',', $base64_string);

fwrite($ifp, base64_decode($data[1]));
fclose($ifp);

return $output_file;
}
$rand = generateRandomString(17);
$ran = generateRandomString(7);
$tstamp = date("dmyHi");
$output_file = $rand."_".$tstamp."_".$ran;


The above code will be called when the article is being processed after submission, the code below is the code that will check for images within the HTML and if any are present, the base64 will be replaced with real links. Could I have any insight as to what I'm doing wrong with the code below, why they aren't being replaced?



$content = "<div class='article'>This is a random article with multiple images <img src='data:image/png;base64,iVBORw0...' alt='loading.png'/><img src='data:image/png;base64,oHBOsnfjjRw0...' alt='loading.png'/><img src='data:image/png;base64,fejfke...' alt='loading.png'/></div>"

$doc = new DomDocument();
$doc->loadHTML($content);
$sub = $doc->getElementsByTagName("img");
foreach ($sub as $sub) {
$src = $tag->getAttribute('src');
str_replace("$src",base64_to_jpeg($src, $output_file),"$content");

}

$qry = "INSERT INTO article(..,kb_article,..) VALUES(..'$content'..)";
$result = @mysqli_query($GLOBALS["___mysqli_ston"], $qry);

Aucun commentaire:

Enregistrer un commentaire