<?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)
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top