Can file_get_content be used along with preg_replace? - php

How can I get the file content from preg_replace?
<?php
function get($it) {
$r = array("~<script src='(.*?)'></script>~");
$w = array("<script type='text/javascript'>' . file_get_contents($1) . '</script>");
$it = preg_replace($r, $w, $it);
return $it;
}
$it = "<script src='/script.js'></script>";
echo get($it);
?>
It returns <script type='text/javascript'>' . file_get_contents(/script.js) . '</script>

If the path is relative as in your example the file_get_contents won't work but this should get you closer:
function get($it) {
return preg_replace_callback("~<script src='(.*?)'></script>~", function($match){
return "<script type='text/javascript'>" . file_get_contents($match[1]) . '</script>';
}, $it);
}
$it = "<script src='/script.js'></script>";
echo get($it);

Related

PHP: Create arrays from a function call inside a foreach loop and merge them

The purpose of this code is to identify all the image files from the folder in which the code is being invoked in order to create an image gallery. The images are listed in alphanumeric order but I require a specific order so reordering with a standard PHP array sorting function doesn't meet my needs.
I am using an if statement to place image collections into different arrays then merging the arrays into my required order.
When I run the code as part of my foreach loop it works fine. I want to put the if conditional into a function to reuse the code but I just get a blank page when I copy and paste the code into the function:
// echo statements are just for testing.
foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var03){
$img_src03 = basename($var03);
$img_label03 = pathinfo($var03, PATHINFO_FILENAME);
// Assign specific values to the arrays as you cycle through $img_src03 values:
if (substr($img_src03, 0, 5) == 'ext_f'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 5) == 'ext_r'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 6) == 'ext_po'){
if (!isset($array34)) {
$array34 = array();
}
$array34[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bed'){
if (!isset($array35)) {
$array35 = array();
}
$array35[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bth'){
if (!isset($array36)) {
$array36 = array();
}
$array36[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
}
}
$arrayFinal = array_merge($array33, $array34, $array35, $array36);
echo 'This is $arrayFinal:<br><pre>'; print_r($arrayFinal); echo '</pre><br>';
When the exact same if conditional is placed inside function findImage03($img_src03, $img_label03), which is located outside the foreach loop, then called from inside the foreach loop the code fails to work.
foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var03){
$img_src03 = basename($var03);
$img_label03 = pathinfo($var03, PATHINFO_FILENAME);
// Trying to use a function call to run the if conditional. Function is outside the foreach loop. Nothing returned.
findImage03($img_src03, $img_label03);
}
function findImage03($img_src03, $img_label03){
// Assign specific values to the arrays as you cycle through $img_src03 values:
if (substr($img_src03, 0, 5) == 'ext_f'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 5) == 'ext_r'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 6) == 'ext_po'){
if (!isset($array34)) {
$array34 = array();
}
$array34[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bed'){
if (!isset($array35)) {
$array35 = array();
}
$array35[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bth'){
if (!isset($array36)) {
$array36 = array();
}
$array36[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
}
}
$arrayFinal = array_merge($array33, $array34, $array35, $array36);
echo 'This is $arrayFinal:<br><pre>'; print_r($arrayFinal); echo '</pre><br>';
In researching this I think I have found a couple of issues so I'm not sure if this is down to not being a programmer or not.
I found a solution running foreach() in a function() rather than a function() within a foreach(). The new array is then created using the result of the function call.
array_merge() works only if all the arrays being merged hold values otherwise it fails. Not sure if that could be resolved with !isset.
So this is the code running the foreach() in a function() which can be located in an included file for reuse efficiency plus a single source to maintain/update:
// Define the function to get all the images in the current folder:
function getImages(){
foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var){
$img_src = basename($var);
// Assign specific values to the array as you cycle through the collection. Order here will not affect final array order.
if (substr($img_src, 0, 5) == 'bed_1'){
if (!isset($arrayBed_1)) {
$arrayBed_1 = array();
}
$arrayBed_1[] = $img_src;
} elseif (substr($img_src, 0, 5) == 'bed_2'){
if (!isset($arrayBed_2)) {
$arrayBed_2 = array();
}
$arrayBed_2[] = $img_src;
} elseif (substr($img_src, 0, 5) == 'bed_3'){
if (!isset($arrayBed_3)) {
$arrayBed_3 = array();
}
$arrayBed_3[] = $img_src;
// continue for each type required.
} }
} //End of foreach().
// Create the pre final array for other arrays to push to which defines the sort order:
$arrayPreFinal = array();
if (isset($arrayExt_f)){ // ext_f = exterior front
foreach ($arrayExt_f as $val){
array_push($arrayPreFinal, $val);
}
}
if (isset($arrayExt_r)){ // ext_r = exterior rear
foreach ($arrayExt_r as $val){
array_push($arrayPreFinal, $val);
}
}
if (isset($arrayBed_1)){ // bed_1 = bedroom 1
foreach ($arrayBed_1 as $val){
array_push($arrayPreFinal, $val);
}
}
if (isset($arrayBed_2)){ // bed_2 = bedroom 2
foreach ($arrayBed_2 as $val){
array_push($arrayPreFinal, $val);
}
}
// continue for as many variances as require.
return $arrayPreFinal;
} // End of function()
The code run from the folder where the images are located:
// Set $iwd Image Working Directory:
// Required before gallery_ctrl_body.php inlcude as $iwd is needed before include.
// class IWD changes outside the class.
class IWD {
// Properties
public $iwd;
}
$var = new IWD();
$var->name = getcwd();
$iwd = $var->name;
// Script include needs to be run before function pid_text().
include_once ('../gallery_ctrl_body.php');
# Function to identify the property sub-division from directory path characters using preg_match()
# and define a Property ID Text:
function pid_text($sub_div) { //Need parameter/s in function():
$sub_div_abb = sub_div_abb($sub_div); //20200220 code
$psc = 'ORL'; // Start of Property System Code.
$str = getcwd();
if(preg_match("/{$sub_div}/i", $str)) {
$psc = $psc . $sub_div_abb . strtoupper(basename(__DIR__)); //sub_div_abb may already defined in UPPERCASE.
$pid_textname = constant("PROPERTY_TEXT") . $psc; //strtoupper($psc);
}
return $pid_textname; //Return value AFTER IF statement. REQUIRED!
}
$pid_text = pid_text($sub_div = 'test_200828');
// Define the imagepath and variables:
define('IMAGEPATH', dirname(__FILE__).'/'); // '/' is required.
$img_height = 'height: 400px'; // default image height for gallery.
$img_width = 'width: 600px'; // default image width for gallery.
$img_counter = 0;
$img_style = 'style="' . $img_width . '"'; // only needs to be set once here.
$img_total = 0;
// Create the final array with function call to get images:
$arrayFinal = getImages();
// Calculate total number of images before displaying <div>
// If calculated inside a foreach() $img_counter always equals $img_total.
$img_total = count($arrayFinal);
echo '<div class="property_text-container">';
echo 'Gallery for ' . $pid_text;
echo '</div>';
//<!-- Slideshow container -->
echo '<div class="slideshow-container">';
// foreach ($array1 as $value){
foreach ($arrayFinal as $value){
$img_counter ++; // Set before function() when using function call.
// Call the function located in gallery_ctrl_body:
createGallery($img_width, $img_style, $filename, $img_name, $img_src, $img_counter, $img_total, $value, $pid_text);
}
// <!-- Next and previous buttons -->
echo '<a class="prev" onclick="plusSlides(-1)">❮</a>';
echo '<a class="next" onclick="plusSlides(1)">❯</a> ';
echo '</div>';
// <!-- END: div class="slideshow-container"-->
echo '<br>';
// <!-- Dot container -->
echo '<div class="dot-container">';
// <!-- The dots/circles -->
echo '<div style="text-align:center">';
$slide_counter = 0;
while ($slide_counter < $img_total) {
$slide_counter ++;
echo '<span class="dot" onclick="currentSlide(' . $slide_counter . ')"></span> ';
}
echo '</div>';
echo '</div>';
// Script include needs to be run at end of page including it.
include_once ('../gallery_ctrl_script.php');
So, this code works but I'm not sure if it's the correct way or approach. If works for me as I have a set image naming convention and my galleries can be controlled from a single source file. It will work for any number of images, if they exist, in the folder where the function is being called from although my properties generally will have less than 50.

PHP if statement not working in preg_replace

I have a simple PHP of statement but it keeps giving me 'Internal 500'.
Can anyone see what is wrong with this code?
(It works without the 'if')
$fullyfiltered = preg_replace('/<span>(.*?)<\/span>/', '<div class="chat-message ' if('$1'=="MichaelD"){'me'}else{'chat-midnightblue'}'"><div class="chat-contact"><img src="/assets/demo/avatar/tswan.png" alt=""></div><div id="chat-text" class="chat-text">$1: ', $nearlyfiltered);
EDIT - Full script:
<script>
setInterval(function(){
document.getElementById('chat-text').innerHTML = '';
<?php
$fh = fopen('chat.txt','r');
while ($line = fgets($fh)) {
//echo "<p>" . $line . "</p>";
$filtered = str_replace("'", "\\'", $line);
$almostfiltered = str_replace("<span></span>\n", "", $filtered);
$nearlyfiltered = trim(preg_replace('/\s\s+/', ' ', $almostfiltered));
$fullyfiltered = preg_replace('/<span>(.*?)<\/span>/', '<div class="chat-message ' if('$one'=="MichaelD"){'me'}else{'chat-midnightblue'}'"><div class="chat-contact"><img src="/assets/demo/avatar/tswan.png" alt=""></div><div id="chat-text" class="chat-text">$1: ', $nearlyfiltered);
if(!empty($fullyfiltered)){
$endingp = "</div></div>';";
} else {
$endingp = "';";
}
echo "document.getElementById('chat-text').innerHTML = document.getElementById('chat-text').innerHTML + '" . $fullyfiltered . $endingp;
}
fclose($fh);
?>
},5000);
</script>
callback must be a function, not just random script parts. Please read the manual (http://php.net/manual/en/function.preg-replace-callback.php)

PHP - Parse error: syntax error, unexpected T_IF

Im getting Parse error from:
$uphalfh = if(isset($price30in)) { echo $price30in->textContent;}
if(isset($price30out)) { echo ", " . $price30out->textContent; }
How can I improve this code to avoid Parse error? I understand that I can't use IF statement in $var
When I Echo Variable's its works like a charm and I get the results that I want. But how can I assign the result of Echo Variable's (on Line:10) to $uphalfh
include_once './wp-config.php';
include_once './wp-load.php';
include_once './wp-includes/wp-db.php';
// A name attribute on a <td>
$price30in = $xpath->query('//td[#class=""]')->item( 1);
$price30out = $xpath->query('//td[#class=""]')->item( 2);
// Echo Variable's
if(isset($price30in)) { echo $price30in->textContent;} if(isset($price30out)) { echo ", " . $price30out->textContent; }
// The wrong CODE i tried:
// $uphalfh = if(isset($price30in)) { echo $price30in->textContent;}
// if(isset($price30out)) { echo ", " . $price30out->textContent; }
// Create post object
$my_post = array();
$my_post['post_title'] = 'MyTitle';
$my_post['post_content'] = 'MyDesciprion';
$my_post['post_status'] = 'draft';
$my_post['post_author'] = 1;
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
update_post_meta($post_id,'30_min',$uphalfh);
$uphalfh = isset($price30in);
if(isset($price30in)) {
echo $price30in->textContent;
}
if(isset($price30out)) {
echo ", " . $price30out->textContent;
}
remove the assignment.
if(isset($price30in)) { echo $price30in->textContent;}
if(isset($price30out)) { echo ", " . $price30out->textContent; }
// $uphalfh = you have to complete the variable initialising here and then continue with the conditional statement or remove the variable initialising and continue with the conditional statement because $var = if(conditon){ }else{ }; is wrong syntax in php
if(isset($price30in)) {
echo $price30in->textContent;
}
if(isset($price30out)) {
echo ", " . $price30out->textContent;
}
echo $uphalf = (isset($price30in)) ? $price30in->textContent : "";
The if clause does not return a value, which means you can't use it in the context of assigning a value to variable because there is no value to be had.
$uphalfh = if(isset($price30in)) {
echo $price30in->textContent;
} if(isset($price30out)) {
echo ", " . $price30out->textContent;
}
The above code will not work as you expected it, the bellow code should work as expected -- the value of $uphalf will be set to either $price30in->textContent or $price30out->textContent.
if(isset($price30in)) {
$uphalfh = $price30in->textContent;
} if(isset($price30out)) {
$uphalfh = ", " . $price30out->textContent;
}
Only if you also want this result to be outputted to the browser (directly visible to a visitor) you could use echo.
if(isset($price30in)) {
$uphalfh = $price30in->textContent;
}
if(isset($price30out)) {
$uphalfh = ", " . $price30out->textContent;
}
echo $uphalfh;
A simple edit did the trick! That solved my problem :-)
I replaced:
$uphalfh = if(isset($price30in)) { echo $price30in->textContent;}
if(isset($price30out)) { echo ", " . $price30out->textContent; }
With this:
$uphalfh = $price30in->textContent. ', ' . $price30out->textContent;

php outputs part of code without any echo

Here's my piece of code(full body code):
<body>
<script type='text/javascript'>
function AddEvent(Syear, Smonth, Sday, Eyear, Emonth, Eday, hallNumber){
...
}
</script>
<?php
function GetMonthByCoding($first , $second , $third) {
...
}
function GetDateByCoding($coding){
...
}
function GetDateFromLine($line){
...
}
$userid = '...';
$magicCookie = 'cookie';
$feedURL = "...";
$sxml = simplexml_load_file($feedURL);
foreach ($sxml->entry as $entry) {
$title = stripslashes($entry->title);
if ($title == "HALL") {
$summary = stripslashes($entry->summary);
$date = GetDateFromLine($summary);
echo ("<script type='text/javascript' language='JavaScript'> AddEvent(" . $date['start']['year'] . ", " . $date['start']['month'] . ", " . $date['start']['day'] . ", " . $date['end']['year'] . ", " . $date['end']['month'] . ", " . $date['end']['day'] . "); </script>");
}
}
?>
</body>
AddEvent() is JavaScript function defined earlier.
What I get in my browser is:
entry as $entry) { $title = stripslashes($entry->title); if ($title == "HALL") { $summary = stripslashes($entry->summary); $date = GetDateFromLine($summary); echo (""); } } ?>
Looks like it was an echo but as you can see there is no echo right in the middle of foreach.
Can anyone say what I am doing wrong?
PHP is not installed, or it is not enabled, or the file is not a .php file or the server has not been told to recognise it as a file to parse.
Try View Source and you should see all your PHP code. The only reason part of it shows up is because everything from <?php to the first > is considered by the browser to be an invalid tag.
I found the problem, it was in the name of variable sxml. I renamed it and the problem escaped.

Get album art from MP3 PHP

I am using this code to get ID3 information of an MP3 File.
<?php
class CMP3File {
var $title;var $artist;var $album;var $year;var $comment;var $genre;
function getid3 ($file) {
if (file_exists($file)) {
$id_start=filesize($file)-128;
$fp=fopen($file,"r");
fseek($fp,$id_start);
$tag=fread($fp,3);
if ($tag == "TAG") {
$this->title=fread($fp,30);
$this->artist=fread($fp,30);
$this->album=fread($fp,30);
$this->year=fread($fp,4);
$this->comment=fread($fp,30);
$this->genre=fread($fp,1);
fclose($fp);
return true;
} else {
fclose($fp);
return false;
}
} else { return false; }
}
}
?>
I am then using this code to call it.
include ("CMP3File.php");
$filename="music_file.mp3";
$mp3file=new CMP3File;
$mp3file->getid3($filename);
echo "Title: $mp3file->title<br>\n";
echo "Artist: $mp3file->artist<br>\n";
echo "Album: $mp3file->album<br>\n";
echo "Year: $mp3file->year<br>\n";
echo "Comment: $mp3file->comment<br>\n";
echo "Genre: " . Ord($mp3file->genre) . "<br>\n";
Is there a way to also get and echo out the album art as an image?

Categories