<?php
include_once("database.php");
Header("content-type: application/x-javascript");
if(isset($_GET["files"])){
$src = explode("+",$src);
for($i = 0;$i<=count($src);$i++){
echo "console.log('$src');";
echo "console.log('$src[$i]');";
$file = preg_replace('#[^a-z0-9]#','',$src[$i]);
echo "console.log('You\'ve select $file');";
}
exit();
}else{
echo "console.error('No Files were found. Please try again, make sure your request is correct')";
}
?>
I'm trying to create a dynamic JavaScript file, and the consoles are working but my iteration of the $src is not working.
EX:
$_GET["files"] ===> file1+file2+file3+file4
url looks like myfile.php?files=file1+file2+file3+file4
So basically I want to split these up into an array by seperating the + in the $_GET I'm new to PHP and I'm trying to learn this on my own but there is not clear cut documentation that I can find quickly.
ALSO
Am I do my preg_replace correctly? I want to ensure there is no malicious injection going on
UPDATE
if(isset($_GET["files"])){
$src = explode("+",$_GET["files"]);
foreach($src as $files){
$file = preg_replace('#[^a-z0-9]#','',$files);
echo "console.log('$file');";
}
exit();
}
//Direct Output:
==>You've Selected aweelemtawe
//Output should be:
==>You've Selected awc
==>You've Selected elemt
==>You've Selected awe
For the incorrect usage of explode()
The following line contains your explode() call
$src = explode("+",$src);
At this stage (using the code example you've posted above) $src will not contain any data to be explode()ed. You want to use the $_GET['files'] value as the parameter
$src = explode("+", $_GET['files']);
See the php docs on explode for more info on how it works.
For your looping/iteration
For your loop you may also want to change your loop to check for $i < count($src). If you have file1+file2+file3+file4 the array will have 4 items at index 0, 1, 2 and 3. You want that statement to read $i < 4 not $i <= 4.
However... as #TML suggested, using foreach is preferred over for when directly iterating over an array.
foreach(explode('+', $_GET['files']) as $file)
{
// work with $file here (each one will be an element of the exploded array)
}
For the sake of simplifying the example, the above is essentially equivalent to
$src = explode('+', $_GET['files']);
foreach($src as $file)
{
// work with $file here (each one will be an element of the exploded array)
}
Related
I have managed to get this code to work for an application -- http://twitter.github.io/typeahead.js/ but, the problem I have run into, is that I need to be able to re-load the data. I would rather not duplicate the code to do this, although it's an option, it seems kind of silly. I have inserted some PHP into my JavaScript to create an array for the dropdown list, and it works great. But if I stuff it into a function, and then try to call the function in the document open, it doesn't work (nothing appears to happen).
$(document).ready(function()
{
// call function when page loads(?)
getAwards();
}); // end document.ready ...
This is the PHP code, if I comment out the JavaScript function parts it runs and the typeahead code sees the value of the array. If I put it into the function, it doesn't execute despite being called above, and I have no data for the typeahead code ...
function getAwards(
{
// build array for use with typeahead:
<?php
$sql_statement = "select title from awards order by title desc limit 1";
$aw_result = mysqli_query( $connect, $sql_statement );
$aw_row = mysqli_fetch_array( $aw_result );
$last_award = $aw_row["title"];
// need to rewind table:
mysqli_data_seek( $aw_result, 0);
// start from the top:
$sql_statement = "select title from awards order by title";
$aw_result = mysqli_query( $connect, $sql_statement );
$count = 0;
$out = 'awards = [';
while ( $aw_row = mysqli_fetch_array( $aw_result ) )
{
// the quotes deal with forcing this to handle
// branch names with apostrophes in them ...
$count++;
$out .= '"'. $aw_row["title"] . '"';
if( $aw_row["title"] != $last_award )
{
$out .= ',';
}
}
$out .= ']';
echo $out . "\n";
?>
})
I need to be able to update the data, and reload the list while working on the form (I am working that out in my fuzzy brain, but anyway I'll get to that -- currently intend to click a button to update the list used by the typeahead, which is why I want a function ...)
Any suggestions are gratefully accepted. I am at a loss ...
My 1 file is city.html which contains the following code
<script language="javascript">alert("Page Called"); </script>
'Bhubaneshwar', 'Orissa', 'India'
My another file index.php contains the following code
$x=file_get_contents("city.html");
$x=array($x);
echo $x[0];
It shows the following output
'Bhubaneshwar', 'Orissa', 'India'
But I want single word output like this.
When I print $x[0], it should be Bhubaneshwar
When I print $x[1], it should be Orissa
When I print $x[2], it should be India
First you need to remove script tags
$x = file_get_contents("city.html");
$x = preg_replace('%<script[^>]*>.*?</script>%/m', '', $x);
and then you can use explode:
$array = explode(',', $x);
then you can trim and remove quotes:
$array = array_map(function($item) {
return preg_replace("/^'|'$/", trim($item));
}, $array);
Use explode to convert string to array:-
// Remove script tag
$string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $x);
// $string = str_replace(' ', '', $string); // Remove space from string
$string = preg_replace('/\s+/', '', $string); // Remove whitespace from string
// explode string
$x = explode(',',$string);
Hope it will help you :)
Try,
$x=file_get_contents("city.html");
$x=array($x);
$html = preg_replace('#<script[^>]*?.*?</script>#', '', $x);
$str = str_replace(', ', ',', $html);
$x = explode(',',trim($str[0]));
$remove[] = "'";
$result = str_replace( $remove, "", $x );
foreach($result as $cities)
{
echo $cities . "<br>";
}
Here is code that first removes the preceding script tag(s) and breaks down the remainder into an array:
$x=array_pop(explode('</script>', $x));
$x=preg_split("/'\s*,\s*'/", trim(trim($x), "'"));
The first of those two statements is only needed if you keep that script tag inside your HTML, which seems to be there for testing only.
To display the result, you could do this:
foreach($x as $item) {
echo $item . "<br>";
}
Output:
Bhubaneshwar
Orissa
India
Considerations
It is unusual to have such data format inside HTML files. HTML is intended for rendering data in a user-friendly manner, and that representation does not really fit.
If you are the creator of the HTML file, then consider moving to a JSON format. In that case your file would be named city.json and would have this content (the double quotes and brackets are required):
["Bhubaneshwar", "Orissa", "India"]
And the code would make use of JSON functions like this:
$json=file_get_contents("city.json");
$x=json_decode($json);
This way you really use standards, and the code is compact.
You could again display the contents of $x like before:
foreach($x as $item) {
echo $item . "<br>";
}
Output:
Bhubaneshwar
Orissa
India
If you are the creator of that file, and use PHP to create it, then make use of JSON functions as well, as follows:
$x = array("Bhubaneshwar", "Orissa", "India");
file_put_contents ("city.json", json_encode($x));
I am developing a simple image gallery which shows images and related caption.
All images are inside a directory and caption in another (as single files). A php script lists all files in both directories and pass arrays to a javascript wich change image and caption when the user press a button.
[...]
for($x = 2; $x < $lenght; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x];
}
for($x = 2; $x < $lenght; $x++) {
$filename = $capdirectory."/".$lsc[$x];
$filesc[$x] = file_get_contents($filename);
}
//Create array for JS
$captions = '["' . implode('", "', $filesc). '"]';
$images = '["' . implode('", "', $filesi). '"]';
?>
<script>
var captions = <?php echo $captions; ?>;
var images = <?php echo $images; ?>;
[...]
Images work properly and I can also print caption's file name instead of caption
i.e.
$filesc[$x] = $filename;
but when I use "file_get_contents()" to read file the gallery stops working.
If I echo $captions and manually set $captions with the very same output
e.g.
$captions='["first caption","second caption", "..."]';
the gallery works properly, so the array should be properly formatted...
Thank you in advance
SOLUTION
I was creating an array with two empty elements (0,1) in order to avoid ./ and ../ in file list, so I have added a +2 to the lsi index.
for($x = 0; $x < $lenght-2; $x++) {
$filesi[$x] = $imgdirectory."/".$lsi[$x+2];
}
In addition I have used json_encode, as suggested, instead of manual json encodig. The output seems to be the same but now the gallery works!
var images = <?php echo json_encode($filesi); ?>;
In JS you have to escape new lines in strings like this:
var multilineString = "this is\
just an example";
Maybe try to use trim() and str_replace() if you don't want to make it easier with json_encode().
UPDATE
Then I was wrong. Did you know that you can push items to arrays with just $array[] = 'item';?
I am using the same script from the link given below to display the files in the directory.
Link list based on directory without file extension and hyphens in php
$directory = 'folder/';
$blacklist = array(
'index'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}
The above script displays all the files (except index.php) in a folder. But I just want to display five random files. Is this possible?
http://s30.postimg.org/hbb1ce67l/screen.jpg
Based off your edit, I think this is what you're trying to do?
<?php
// Get all files ending in .php in the directory
$rand_files = glob("*.php");
// If the string "index.php" is contained in these results, remove it
// array_search returns the key of the $needle parameter (or false) if not found
if (($location = array_search("index.php", $rand_files)) !== false) {
// If "index.php" was in the results, then delete it from the array using unset()
unset($rand_files[$location]);
}
// Randomly choose 5 of the remaining files:
foreach (array_rand($rand_files, 5) as $rand_index) {
$fname = $rand_files[$rand_index];
echo "<a href='$fname'>$fname</a>\n";
}
?>
Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:
$user_id = $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";
which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;
I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!
$user_id = (int) $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") {
$dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
$pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}
echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>
Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.