Include a PHP filename after extracting the id from Database - php

So when I add a product, an id is assigned and a file is created with the product id, eg 1000.php. I don't know how to call it in the product.php file to be included:
I know what I did in the code pasted below is wrong but I don't know how to make it call the 1000.php file by extracting the id from sql first and then include it in the same file. Any advice?
<?php
function between($start, $end, $string) {
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$pid = $_GET['id'];
$pid = trim($pid);
include('php/config.php');
$sql = "SELECT * FROM products WHERE pid='".$pid."'";
$result = $config->query($sql);
$num_row = mysqli_num_rows($result);
if($num_row == 1 ) {
$row = mysqli_fetch_array($result);
extract($row);
$display = 1; } else { $display = 0; }
include('".$pid.".php');

If I'm understanding well what you are asking help for, before this line:
include('".$pid.".php');
you should create the file and write in it all the data you need in it; something like this could work:
<?php
function between($start, $end, $string) {
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$pid = $_GET['id'];
$pid = trim($pid);
include('php/config.php');
$sql = "SELECT * FROM products WHERE pid='".$pid."'";
$result = $config->query($sql);
$num_row = mysqli_num_rows($result);
if($num_row == 1 ) {
$row = mysqli_fetch_array($result);
extract($row);
$display = 1; } else { $display = 0; }
try {
$handle = fopen($dir.$filename, 'x');//look at https://www.php.net/manual/en/function.fopen.php on why to use 'x'
fwrite($fp, $allTheDataYouWantToWrite);
fclose($handle);
}catch(\Exception $e){
//do something if exception happens
}
After that you have the file created in that directory and its ready for using it
Take in account that include is used to read php code and maybe is not that what you want...

Related

php listing specific file extension only

I want to make my code to list specific file extension only. I have list of php files and I use this code to list all of then in page
so what I need here is to list specific extiontion only. php files only
right now my code lists all files in same folder
<?php
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);
}
$files1 = scandir(dirname(__FILE__));
?>
<?php
foreach($files1 as $myfile){
if($myfile!='.' && $myfile!='..' && $myfile!='index.php'){
$value = file_get_contents($myfile);
$fullstring = $value;
$parsed = get_string_between($fullstring, '$Cont1 = \'', '\'');
$parsed1 = get_string_between($fullstring, '$Con2 = \'', '\'');
?>
<?php
}
}
?>
can some one please post an answer with editing this and show me how do I make it to list php files only?
Hope this helps. It will only read files which filenames end with php
<?php
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);
}
$files1 = scandir(dirname(__FILE__));
?>
<?php
foreach($files1 as $myfile){
if (substr($myfile, -3) != "php")
continue;
if($myfile!='.' && $myfile!='..' && $myfile!='index.php'){
$value = file_get_contents($myfile);
$fullstring = $value;
$parsed = get_string_between($fullstring, '$Cont1 = \'', '\'');
$parsed1 = get_string_between($fullstring, '$Con2 = \'', '\'');
?>
<?php
}
}
?>
glob() is pretty much made to do this exactly, and it avoids regex in a loop, substringing on an arbitrary number of chars, etc.
foreach (glob("*.php") as $script) {
echo "$script size " . filesize($script) . PHP_EOL;
}
Something like this ( untested )
$Dir = new DirectoryIterator($dir);
$iterator = new RegexIterator($Dir, '/\.php$/i', RegexIterator::MATCH);
foreach($iterator as $fileinfo) {
if ($fileinfo->isDot()) continue;
var_dump( $fileinfo );
}
Or even better
$Dir = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS | FilesystemIterator::KEY_AS_PATHNAME );
$iterator = new RegexIterator($Dir, '/\.php$/i', RegexIterator::MATCH);
foreach($iterator as $fileinfo) {
if ($fileinfo->isDot()) continue;
var_dump( $fileinfo );
}
This second one lets you skip the dots ('.', '..' etc) and changes all the \ Windows to / Linux style ( mainly for use on windows ), auto-magically.

echo hyperlinks in array

I have an array that looks like this:
[6625] => Trump class="mediatype"> href="/news/picture">Slideshow: [6628] => href="http://www.example.com/news/picture/god=USRTX1N84J">GOP [6630] => nation
I need to be able to pull out anything within href="" of the array and put into a new one.
I have tried:
<?php
$homepage = file_get_contents('http://www.example.com/');
$arr = explode(" ",$homepage);
function getStringInBetween($string, $start, $end){
$string = " " . $string;
$initial = strpos($string, $start);
if ($initial == 0) return "";
$initial += strlen($start);
$length = strpos($string, $end, $initial) - $initial;
return substr($string, $initial, $length);
}
echo getStringInBetween($arr[0], 'href="', '"')
?>
Try this code, adapt it to suit you,
<?php
$homepage = file_get_contents('http://www.example.com/');
$arr = explode(" ",$homepage);
function getStringInBetween($string, $start, $end){
$string = " " . $string;
$initial = strpos($string, $start);
if ($initial == 0) return "";
$initial += strlen($start);
$length = strpos($string, $end, $initial) - $initial;
return substr($string, $initial, $length);
}
foreach ($arr as $val) {
if (strpos($val, 'href') !== false) {
echo getStringInBetween($val, 'href="', '"');
}
}
?>
This example when ran outputted google.com/hello.

Get substring between two strings PHP - Reading HTML

I am having a ton of trouble running through finding a string between two strings.
This is the code i currently have
<?
$html = file_get_contents('mywebsite');
$tags = explode('<',$html);
foreach ($tags as $tag)
{
// skip scripts
if (strpos($tag,'script') !== FALSE) continue;
// get text
$text = strip_tags('<'.$tag);
// only if text present remember
if (trim($text) != '') $texts[] = $text;
//print_r($text);
echo($text);
}
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);
}
$fullstring = $text;
$parsed = get_string_between($fullstring, "tag1", "tag2");
print_r($parsed);
echo ($parsed);
?>
I think the problem happens on this line:
$fullstring = $text;
I am not entirely sure if $text has the stripped down HTML from the above function. When i run this code i get the stripped out webpage like i expect but i got nothing between the tags i am setting.
Does anyone know why this might be happening or what i am missing?
I think its because you are declaring text as a local variable inside for loop. so , after when you are assigning $text to fullstring It's actually null. I don't understand what you are trying to do , but do this and see if it works
$fullstring = ""
foreach ($tags as $tag){
#your code as usual
echo($text);
$fullstring = $fullstring.$text;
}
and delete the $fullstring = $text line.
you can use this:
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);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
Reference

PHP sort array by same value twice

I have array with show names like this:
$shows = array('morning_show_15_02_2014_part2.mp3',
'morning_show_15_02_2014_part1.mp3',
'morning_show_14_02_2014_part2.mp3',
'morning_show_14_02_2014_part1.mp3',
'morning_show_13_02_2014_part2.mp3',
'morning_show_13_02_2014_part1.mp3');
So the list look like:
morning_show_15_02_2014_part2.mp3
morning_show_15_02_2014_part1.mp3
morning_show_14_02_2014_part2.mp3
morning_show_14_02_2014_part1.mp3
morning_show_13_02_2014_part2.mp3
morning_show_13_02_2014_part1.mp3
This is what i get when i loop the directory.
But the list should look like this:
morning_show_15_02_2014_part1.mp3
morning_show_15_02_2014_part2.mp3
morning_show_14_02_2014_part1.mp3
morning_show_14_02_2014_part2.mp3
morning_show_13_02_2014_part1.mp3
morning_show_13_02_2014_part2.mp3
Still ordered by date, but part 1 is first and then comes part 2.
How can i get this list into right order?
Thank you for any help!
Resolved!
Code is prett nasty but i got what i was looking for:
public function getMp3ListAsJSONArray() {
$songs = array();
$mp3s = glob($this->files_path . '/*.mp3');
foreach ($mp3s as $key => $mp3Source) {
$mp3Source = basename($mp3Source);
$mp3Title = substr($mp3Source, 4);
$mp3Title = substr($mp3Title, 0, -4);
$mp3Title = basename($mp3Source, ".mp3");
$mp3Title = str_replace('_', ' ', $mp3Title);
$mp3Title = ucfirst($mp3Title);
$songs[$key]['title'] = $mp3Title;
$songs[$key]['mp3'] = urldecode($this->files_url . '/' . $mp3Source);
}
rsort($songs);
$pairCounter = 1;
$counter = 0;
foreach ($songs as $key => $value) {
$playlist[$pairCounter][] = $value;
$counter = $counter + 1;
if($counter == 2) {
$pairCounter = $pairCounter + 1;
$counter = 0;
}
}
foreach ($playlist as $show) {
$finalList[] = $show[1];
$finalList[] = $show[0];
}
$finalList = json_encode($finalList);
return $finalList;
}
Output is like i described in the topic.
Try to use array sort
Here is an example for you
http://techyline.com/php-sorting-array-with-unique-value/
You must definitely write your own string comparision function. Remember that you have 2 different comparisons. The first compares the first parts for the filenames as strings. The second part compares the numbers, where 20 comes after 2. This is a natural number sorting for the second part. The third part is after the last dot in the filename. This will be ignored.
<?php
function value_compare($a, $b) {
$result = 0;
$descending = TRUE;
$positionA = strpos($a, 'part');
$positionB = strpos($b, 'part');
if ($positionA === $positionB) {
$compareFirstPart = substr_compare($a, $b, 0, $positionA + 1);
if ($compareFirstPart === 0) {
$length = 0;
$offset = $positionA + strlen('part');
$positionDotA = strrpos($a, '.');
$positionDotB = strrpos($b, '.');
$part2A = '';
$part2B = '';
if ($positionDotA !== FALSE) {
$part2A = substr($a, $offset, $positionDotA);
} else {
$part2A = substr($a, $offset);
}
if ($positionDotB !== FALSE) {
$part2B = substr($b, $offset, $positionDotB);
} else {
$part2B = substr($b, $offset);
}
$result = strnatcmp($part2A, $part2B);
} else {
$result = $compareFirstPart;
if ($descending) {
$result = -$result;
}
}
}
return $result;
}
$shows = array('morning_show_15_02_2014_part2.mp3', 'morning_show_15_02_2014_part1.mp3', 'morning_show_14_02_2014_part2.mp3', 'morning_show_14_02_2014_part1.mp3', 'morning_show_13_02_2014_part2.mp3', 'morning_show_13_02_2014_part1.mp3');
usort($shows, 'value_compare');
var_dump($shows);
?>

php substring occurances between two strings in an html file

So i have an HTML file as source, it contains several instances of the following code:
<span itemprop="name">NAME</span>
where the NAME part always changing to something different.
how can i write a php code that would go through the html code, extract all the names between the "<span itemprop="name">" and "</span>" and put it in an array?
i have tried this code but it doesn't work:
$prev=$html;
for($i=0; $i<10; $i++){
$current = explode('<span itemprop="name">', $prev);
$cur = explode('</span>', $current[1]);
$names[] = $cur[0];
$prev = $current[2];
}
print_r($names);
Probably better way would be using php DOMDocument or simple php dom or any DOM representative than the way you planed.
Here is example of working DOMDocument code:
$doc = new DOMDocument();
$doc->loadHTML('<html><body><span itemprop="name">1</span><span itemprop="name">2</span><span itemprop="name">3</span></body></html>');
$finder = new DomXPath($doc);
$nodes = $finder->query("//*[contains(#itemprop, 'name')]");
foreach($nodes as $node)
{
echo $node->nodeValue . '<br />';
}
Outputs:
1
2
3
I kinda feel bad for saying this... but you could use a regular expression
preg_match_all('/<span itemprop="name">(.*?)<\/span>/i', $matches);
var_dump($matches); // results are stored in the variable $matches;
This function will get us the "NAME"
function getbetween($content,$start,$end) {
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
This function will replace only the first occurence
<?php
function str_replace_once($search, $replace, $subject) {
$firstChar = strpos($subject, $search);
if($firstChar !== false) {
$beforeStr = substr($subject,0,$firstChar);
$afterStr = substr($subject, $firstChar + strlen($search));
return $beforeStr.$replace.$afterStr;
} else {
return $subject;
}
}
?>
now a loop
$start = '<span itemprop="name">';
$end = '</span>';
while(strpos($content, $start)) {
$name = getbetween($content, $start, $end);
$content = str_replace_once($start.$name.$end, '',$content);
echo $name.'<br>';
}
use this function:
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);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
Refenter link description here

Categories