programing

PHP-PHP 파일을 포함하고 쿼리 매개 변수도 전송

nasanasas 2020. 10. 6. 08:17
반응형

PHP-PHP 파일을 포함하고 쿼리 매개 변수도 전송


특정 조건에 따라 내 PHP 스크립트의 페이지를 표시해야합니다. if 조건이 있고 조건이 충족되면 "include"를 수행하고 있습니다.

if(condition here){
  include "myFile.php?id='$someVar'";
}

이제 문제는 서버에 "myFile.php"파일이 있지만 인수 (id)를 사용하여이 파일을 호출하고 "id"값이 호출 할 때마다 변경된다는 것입니다.

누군가 이것을 달성하는 방법을 말해 줄 수 있습니까? 감사.


포함이 무엇인지 상상해보십시오. 포함 된 PHP 파일의 내용을 복사하여 붙여 넣으면 해석됩니다. 범위 변경이 전혀 없으므로 포함 된 파일에서 $ someVar에 직접 액세스 할 수 있습니다 ($ someVar를 매개 변수로 전달하거나 몇 가지 전역 변수를 참조하는 클래스 기반 구조를 고려할 수도 있음).


원하는 효과를 얻기 위해 다음과 같이 할 수 있습니다.

$_GET['id']=$somevar;
include('myFile.php');

그러나 이것은 일종의 함수 호출과 같은 포함을 사용하는 것처럼 들립니다 (다른 인수로 반복적으로 호출한다고 언급합니다).

이 경우 한 번 포함되고 여러 번 호출되는 일반 함수로 바꾸지 않는 이유는 무엇입니까?


포함은 코드 삽입과 같습니다. 포함 된 코드에서 기본 코드에있는 것과 똑같은 변수를 얻습니다. 따라서 주 파일에서 다음을 수행 할 수 있습니다.

<?
    if ($condition == true)
    {
        $id = 12345;
        include 'myFile.php';
    }
?>

그리고 "myFile.php"에서 :

<?
    echo 'My id is : ' . $id . '!';
?>

그러면 다음이 출력됩니다.

내 아이디는 12345입니다!


이것을 PHP 파일에 수동으로 작성하려면 Daff 의 대답 이 완벽합니다.

어쨌든, 초기 질문을해야한다면이를 달성하기위한 작은 간단한 함수가 있습니다.

<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
    // find ? if available
    $pos_incl = strpos($phpinclude, '?');
    if ($pos_incl !== FALSE)
    {
        // divide the string in two part, before ? and after
        // after ? - the query string
        $qry_string = substr($phpinclude, $pos_incl+1);
        // before ? - the real name of the file to be included
        $phpinclude = substr($phpinclude, 0, $pos_incl);
        // transform to array with & as divisor
        $arr_qstr = explode('&',$qry_string);
        // in $arr_qstr you should have a result like this:
        //   ('id=123', 'active=no', ...)
        foreach ($arr_qstr as $param_value) {
            // for each element in above array, split to variable name and its value
            list($qstr_name, $qstr_value) = explode('=', $param_value);
            // $qstr_name will hold the name of the variable we need - 'id', 'active', ...
            // $qstr_value - the corresponding value
            // $$qstr_name - this construction creates variable variable
            // this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
            // the second iteration will give you variable $active and so on
            $$qstr_name = $qstr_value;
        }
    }
    // now it's time to include the real php file
    // all necessary variables are already defined and will be in the same scope of included file
    include($phpinclude);
}

?>

저는이 변수 변수 구성을 자주 사용하고 있습니다.


포함하는 파일에서 html을 함수로 래핑합니다.

<?php function($myVar) {?>
    <div>
        <?php echo $myVar; ?>
    </div>
<?php } ?>

포함시키려는 파일에 파일을 포함시킨 다음 원하는 매개 변수로 함수를 호출하십시오.


나는 이것이 오래되었다는 것을 알고 있지만, 이것을 처리하는 가장 좋은 방법은 be 세션 변수를 활용하는 것 일지 궁금합니다.

myFile.php에서

<?php 

$MySomeVAR = $_SESSION['SomeVar'];

?> 

그리고 호출 파일에서

<?php

session_start(); 
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;

?> 

이것이 전체 프로세스를 기능화하기 위해 "제안 된"요구를 우회 할 수 있습니까?


여러 필드 세트를 포함하는 ajax 양식을 수행 할 때이 문제가 발생했습니다. 예를 들어 고용 신청서를 보자. 하나의 전문 참조 세트로 시작하고 "추가"라는 버튼이 있습니다. 이것은 입력 세트 (이름, 연락처, 전화 등)를 다시 포함하기 위해 $ count 매개 변수로 ajax 호출을 수행합니다. 이것은 다음과 같이 첫 번째 페이지 호출에서 잘 작동합니다.

<?php 
include('references.php');`
?>

사용자가 ajax 호출을하는 버튼을 누른 ajax('references.php?count=1');다음 references.php 파일 안에 다음과 같은 내용이 있습니다.

<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>

매개 변수를 전달하는 사이트 전체에 이와 같은 다른 동적 포함도 있습니다. 사용자가 제출을 누르고 양식 오류가있을 때 문제가 발생합니다. 이제 동적으로 포함 된 추가 필드 세트를 포함하기 위해 코드를 복제하지 않기 위해 적절한 GET 매개 변수로 포함을 설정하는 함수를 만들었습니다.

<?php

function include_get_params($file) {
  $parts = explode('?', $file);
  if (isset($parts[1])) {
    parse_str($parts[1], $output);
    foreach ($output as $key => $value) {
      $_GET[$key] = $value;
    }
  }
  include($parts[0]);
}
?>

이 함수는 쿼리 매개 변수를 확인하고 자동으로 $ _GET 변수에 추가합니다. 이것은 내 사용 사례에서 꽤 잘 작동했습니다.

다음은 호출 될 때 양식 페이지의 예입니다.

<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
  if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
   include_get_params(DIR .'references.php?count='. $i);
 } else {
   break;
 }
}
?>

Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.


Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :

if(condition){
    $someVar=someValue;
    include "myFile.php";
}

As long as the variable is named $someVar in the myFile.php


I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:

<?php
   header("Location: http://localhost/planner/layout.php?page=dashboard"); 
   exit();
?>

If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:

one.php:

<?php
    $vars = array('stack','exchange','.com');

    include('two.php'); /*----- "paste" contents of two.php */

    testFunction(); /*----- execute imported function */
?>

two.php:

<?php
    function testFunction(){ 
        global $vars; /*----- vars declared inside func! */
        echo $vars[0].$vars[1].$vars[2];
    }
?>

You can use $GLOBALS to solve this issue as well.

$myvar = "Hey";

include ("test.php");


echo $GLOBALS["myvar"];

Do this:

NSString *lname = [NSString stringWithFormat:@"var=%@",tname.text];
NSString *lpassword = [NSString stringWithFormat:@"var=%@",tpassword.text];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://localhost/Merge/AddClient.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"insert" forHTTPHeaderField:@"METHOD"];

NSString *postString = [NSString stringWithFormat:@"name=%@&password=%@",lname,lpassword];
NSString *clearpost = [postString stringByReplacingOccurrencesOfString:@"var=" withString:@""];
NSLog(@"%@",clearpost);
[request setHTTPBody:[clearpost dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:clearpost forHTTPHeaderField:@"Content-Length"];
[NSURLConnection connectionWithRequest:request delegate:self];
NSLog(@"%@",request);

And add to your insert.php file:

$name = $_POST['name'];
$password = $_POST['password'];

$con = mysql_connect('localhost','root','password');
$db = mysql_select_db('sample',$con);


$sql = "INSERT INTO authenticate(name,password) VALUES('$name','$password')";

$res = mysql_query($sql,$con) or die(mysql_error());

if ($res) {
    echo "success" ;
} else {
    echo "faild";
}

참고URL : https://stackoverflow.com/questions/1232097/php-include-a-php-file-and-also-send-query-parameters

반응형