jQuery load() can't load php page with text file? - php

jQuery code:
function sorting(){
$(".search_result_employee").load("include/searchedResult.php", {sort: "SORT_DESC"});
}
php code:
$array = file("data/employees.txt");
$row = intdiv(count($array), 4);
if (count($array)%4 != 0){
$row++;
}
//$row = round(count($array)/4);
$x = $z = 0;
for ($x; $x < $row; $x++){
echo '<div class="row my-4">';
for ($y=0; $y <= 3; $y++){
if (isset($array[$z])) {
$name = explode("| ", $array[$z]);
$eName = $name[0];
$eDepartment = $name[7];
$eProfile = end($name);
echo '
<div class="col-md">
<a href="displayInfo.php?name='."$eName".'" class="grey_bg p-2 m-1 employeeCard">
<img src="employeesProfile/'."$eProfile".'" alt="profile" class="profile"/>
'."$eName".'<br/>
<span>'."$eDepartment".'</span>
</a>
</div>
';
}
$z++;
}
echo '</div>';
}
First go in the page using
<?php include("include/searchedResult.php"); ?>
The page can found the file. Howver, after clicked the button, the jQuery load() the include/searchResu;t.php page. Then, the file doesn't exist. First time is working properly thensecond time can't. Anyone know how to solve this?
this is the error:
Warning: file(data/employees.txt): failed to open stream: No such file or directory in C:\xampp\htdocs\COS30020\include\searchedResult.php on line 14

When including files in PHP, all relative paths will be relative from the first entry PHP-file.
If index.php includes searchResult.php, then file('data/employees.txt') will be relative from the index.php-file, not the searchResult.php-file.
If you call the searchResult.php-file directly, then it will be relative from searchResult.php (which then is the entry file).
Solve this by using the magic constant __DIR__, which contains the absolute path to the file it's written in.
So it should be:
file(__DIR__ . '/relative/path/from/this/file/data/employees.txt')

Related

My code crashes Elementor for me easily (WP + PHP )

I wrote a code for a loop but it disrupts everything for me, I have a file
file.php that is inside my template (let's say it's called test)
Now I call the file from the function (function file by include_once ('file.php'); )
Now it works, but my elementor display is broken and I can't update anything, and it also ruins my main pages, but the post pages look great
<?php
function video() {
echo '<link rel="stylesheet" href="/style.css">';
$x = 1;
$number = get_field_object('number');
echo '<div class="col-lg-2-1">
<div class="carousel">
<div class="video"><iframe src="" allowfullscreen frameborder="0" name="slider1"></iframe></div>
<span class="kfir">';
while($x <= $number['value']) {
$prak = 'video '.$x;
$num = 'chapter_'.$x;
$chapter1 = get_field_object($num);
echo '<div class="text">'.$prak.'</div>';
$x++;
}
echo '
</span>
</div>
</div>';
}
add_shortcode('video_live', 'video');
?>
Does anyone know where my mistake is?
And can someone guide me how to make it work only within the posts pages?

PHP change directory according to parameter ($GET from url)

I try to run project and get localhost:8000/fishes.php and then change it to localhost:8000/fishes.php?fish=pike (or trout).
I have directories on same project /info/pike (or trout) and in these directories there is info.txt where first line has fish latin name and second line has average size.
My question is, How can I get text from that file to "site". Code doesn't include html-code, I don't have the code right now with me. But it is fine and runs normally.
Thanks
<?php
$species = $_GET["fish"];
if (file_exists("info.txt")) {
$array = explode("/n", file_get_contents('$species/info.txt'));
$name = $array[0];
$size = $array[1];
} else {
}
global $name;
global $size;
?>
<h1><?php$name?> (<?php$size?>)</h1>
In your Markup, you're opening the php tag, and calling a variable. This variable is not actually printing to the STDOUT. You have a few options:
<?php echo $name; ?>
or
<?php print $name; ?>
or if you have shorttags enabled
<?=$name;?>
You need to use echo or print for variables.
<?php
$name = '';
$size = '';
$species = $_GET["fish"];
if (file_exists("info.txt")) {
$array = explode("/n", file_get_contents('$species/info.txt'));
$name = $array[0];
$size = $array[1];
} else {
//Code for Else
}
//global $name; //No Need of Globals if you have html in same file
//global $size; //No Need of Globals if you have html in same file
?>
<h1><?php echo $name?> (<?php echo $size?>)</h1>
I think you need to use double quotes in "$species/info.txt"
if you server support short tags you can:
<h1><?=$name;?> (<?=$size;?>)</h1>

PHP include() wiping rest of HTML document?

So I have a simple html page that looks like this.
<html>
<head>
<?php include("scripts/header.php"); ?>
<title>Directory</title>
</head>
<body>
<?php include("scripts/navbar.php"); ?>
<div id="phd">
<span id="ph">DIRECTORY</span>
<div id="dir">
<?php include("scripts/autodir.php"); ?>
</div>
</div>
<!--Footer Below-->
<?php include("scripts/footer.php"); ?>
<!--End Footer-->
</body>
</html>
Now, the problem is, when I load the page, it's all sorts of messed up. Viewing the page source code reveals that everything after <div id="dir"> is COMPLETELY GONE. The file ends there. There is no included script, no </div>'s, footer, or even </body>, </html>. But it's not spitting out any errors whatsoever. Just erasing the document from the include onward without any reason myself or my buddies can figure out. None of us have ever experienced this kind of strange behavior.
The script being called in question is a script that will fetch picture files from the server (that I've uploaded, not users) and spit out links to the appropriate page in the archive automatically upon page load because having to edit the Directory page every time I upload a new image is a real hassle.
The code in question is below:
<?php
//Define how many pages in each chapter.
//And define all the chapters like this.
//const CHAPTER_1 = 13; etc.
const CHAPTER_1 = 2; //2 for test purposes only.
//+-------------------------------------------------------+//
//| DON'T EDIT BELOW THIS LINE!!! |//
//+-------------------------------------------------------+//
//Defining this function for later. Thanks to an anon on php.net for this!
//This will allow me to get the constants with the $prefix prefix. In this
//case all the chapters will be defined with "CHAPTER_x" so using the prefix
//'CHAPTER' in the function will return all the chapter constants ONLY.
function returnConstants ($prefix) {
foreach (get_defined_constants() as $key=>$value) {
if (substr($key,0,strlen($prefix))==$prefix) {
$dump[$key] = $value;
}
}
if(empty($dump)) {
return "Error: No Constants found with prefix '" . $prefix . "'";
}
else {
return $dump;
}
}
//---------------------------------------------------------//
$archiveDir = "public_html/archive";
$files = array_diff(scandir($archiveDir), array("..", "."));
//This SHOULD populate the array in order, for example:
//$files[0]='20131125.png', $files[1]='20131126.png', etc.
//---------------------------------------------------------//
$pages = array();
foreach ($files as $file) {
//This parses through the files and takes only .png files to put in $pages.
$parts = pathinfo($file);
if ($parts['extension'] == "png") {
$pages[] = $file;
}
unset($parts);
}
//Now that we have our pages, let's assign the links to them.
$totalPages = count($pages);
$pageNums = array();
foreach ($pages as $page) {
//This will be used to populate the page numbers for the links.
//e.g. "<a href='archive.php?p=$pageNum'></a>"
for($i=1; $i<=$totalPages; $i++) {
$pageNums[] = $i;
}
//This SHOULD set the $pageNum array to be something like:
//$pageNum[0] = 1, $pageNum[1] = 2, etc.
}
$linkText = array();
$archiveLinks = array();
foreach ($pageNums as $pageNum) {
//This is going to cycle through each page number and
//check how to display them.
if ($totalPages < 10) {
$linkText[] = $pageNum;
}
elseif ($totalPages < 100) {
$linkText[] = "0" . $pageNum;
}
else {
$linkText[] = "00" . $pageNum;
}
}
//So, now we have the page numbers and the link text.
//Let's plug everything into a link array.
for ($i=0; $i<$totalPages; $i++) {
$archiveLinks[] = "<a href='archive.php?p=" . $pageNums[$i] . "'>" . $linkText[$i] . " " . "</a>";
//Should output: <a href= 'archive.php?p=1'>01 </a>
//as an example, of course.
}
//And now for the fun part. Let's take the links and display them.
//Making sure to automatically assign the pages to their respective chapters!
//I've tested the below using given values (instead of fetching stuff)
//and it worked fine. So I doubt this is causing it, but I kept it just in case.
$rawChapters = returnConstants('CHAPTER');
$chapters = array_values($rawChapters);
$totalChapters = count($chapters);
$chapterTitles = array();
for ($i=1; $i<=$totalChapters; $i++) {
$chapterTitles[] = "<h4>Chapter " . $i . ":</h4><p>";
echo $chapterTitles[($i-1)];
for ($j=1; $j<=$chapters[($i-1)]; $j++) {
echo array_shift($archiveLinks[($j-1)]);
}
echo "</p>"; //added to test if this was causing the deletion
}
?>
What is causing the remainder of the document to vanish like that? EDIT: Two silly syntax errors were causing this, and have been fixed in the above code! However, the links aren't being displayed at all? Please note that I am pretty new to php and I do not expect my code to be the most efficient (I just want the darn thing to work!).
Addendum: if you deem to rewrite the code (instead of simply fixing error(s)) to be the preferred course of action, please do explain what the code is doing, as I do not like using code I do not understand. Thanks!
Without having access to any of the rest of the code or data-structures I can see 2 syntax errors...
Line 45:
foreach ($pages = $page) {
Should be:
foreach ($pages as $page) {
Line 88:
echo array_shift($archiveLinks[($j-1)];
Is missing a bracket:
echo array_shift($archiveLinks[($j-1)]);
Important...
In order to ensure that you can find these kinds of errors yourself, you need to ensure that the error reporting is switched on to a level that means these get shown to you, or learn where your logs are and how to read them.
See the documentation on php.net here:
http://php.net/manual/en/function.error-reporting.php
IMO all development servers should have the highest level of error reporting switched on by default so that you never miss an error, warning or notice. It just makes your job a whole lot easier.
Documentation on setting up at runtime can be found here:
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
There is an error in scripts/autodir.php this file. Everything up to that point works fine, so this is where the problem starts.
Also you mostlikely have errors hidden as Chen Asraf mentioned, so turn on the errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Just put that at the top of the php file.

PHP link to include header

I have php reading a text file that contains all the names of images in a directory, it then strips the file extension and displays the file name without the .jpg extension as a link to let the user click on then name, what I am looking for is a easy way to have the link that is clicked be transferred to a variable or find a easier solution so the link once it is clicks opens a page that contains the default header and the image they selected without making hundreds of HTML files for each image in the directory.
my code is below I am a newbie at PHP so forgive my lack of knowledge.
thank you in advance. also I would like a apple device to read this so I want to say away from java script.
<html>
<head>
<title>Pictures</title>
</head>
<body>
<p>
<?php
// create an array to set page-level variables
$page = array();
$page['title'] = ' PHP';
/* once the file is imported, the variables set above will become available to it */
// include the page header
include('header.php');
?>
<center>
<?php
// loads page links
$x="0";
// readfile
// set file to read
$file = '\filelist.txt' or die('Could not open file!');
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line) {
$page[$x]=$line;
$x++;
}
$x--;
for ($i = 0; $i <= $x; $i++)
{
$str=strlen($page[$i]);
$str=bcsub($str,6);
$strr=substr($page[$i],0,$str);
$link[$i]= "<a href=".$page[$i]."jpg>".$strr."</a>";
echo "<td>".$link[$i]."<br/";
}
?>
</P></center>
<?php
// include the page footer
include('/footer.php');
?>
</body>
</html>
add the filename to the url that you want to use as a landing page, and catch it using $_GET to build the link.
<a href='landingpage.php?file=<?php echo $filename; ?>'><?php echo $filename; ?></a>
Then for the image link on the landing page
<img src='path/to/file/<?php echo $_GET['file'] ?>.jpg' />

How do I use PHP to supply info to JavaScript?

I have a simple image-looping script that changes the src of an image.
function cycleNext()
{
++imgIndex;
if(imgIndex>imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.
How can I use PHP to supply this script with the number of images in the folder?
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>
Repeat the 2nd line for each extension you wish to count.
function cycleNext()
{
++imgIndex;
if (imgIndex > <?php echo $filecount;?>)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
That should do it.
EDIT:
function cycleNext(imgCount)
{
++imgIndex;
if (imgIndex > imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
Then when you call cycleNext, call it with the variable.
cycleNext(<?php echo $filecount; ?>);
if the .js file is a separate file. then you can do this:
change the .js for a .php
then you can add <?php ?> tags just like you do in your .php files.
just don't forget to add the header in the code, indicating that the file is a javascript file. like that:
<?php header("Content-type: text/javascript"); ?>
and you will call the file with it's actual name src="file.php"
You can do it in three ways:
Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
include the javascript to the <head> tag of your page
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
<script type="text/javascript">
var imgCount = <?php echo $imagecount ?>
</script>;
During the generation of the HTML code, simply insert a <script> line, for instance
echo '<script type="text/javascript">';
echo 'var imgCount=' . $NumberOfImages . ';';
echo '</script>';
Just ensure that line is provided before cycleNext() is called (or imgCount is used).

Categories