dougai3418 2011-09-20 19:19
浏览 48
已采纳

如何将一个变量从一个php传递给另一个由ajax调用的变量,而不会让前端看到它

I have a php function that's run when a build.php page is loaded and creates a $variable. I have save.php also, which is called via an ajax function in scripts.js (taking data sent through POST), but I need to use $variable in save.php.

Is there a good way to send further data through ajax without it being visible on the front end?

I thought of using a $_SESSION variable for this, which seems like it would work, but I understand it may not be totally reliable and is not always a good idea (though this might have been overstated where I was looking).

Is that the best way? Or is there some other way to get a PHP variable to another one via javascript without it being in the front end code?

  • 写回答

2条回答 默认 最新

  • doufen3786 2011-09-20 19:41
    关注

    Session variables exist only on the server, not on the client. For you to save a session variable that was originated by your javascript function in the browser you will need to pass it to the server somehow. And as you probably realize you don't have much control on what happens on the client side. They can pretty much change any post information you send over to the server - there are some programs that do that fairly easily.

    Even if you use ajax, the client can still mess with your variables.

    You could try to encrypt the information before sending it.

    If in the other hand you want to pass variables between two scripts running on the server you can definitively do that using session variables.

    Update

    It seems that you are creating the variable in your first script and then there is a javascript function that calls the second script and you need the second script to access the variable created by the first script.

    In the above scenario you can definitively use session variables. This is the main reason they exist. To allow you to pass information among different scripts.

    First PHP script

    session_start();
    logic to create the variable
    $_SESSION['myVar'] = $myVar;
    rest of the script
    

    Javascript

    calls second script / does not change the value of the variable
    

    Second PHP script

    session_start();
    $myVar = $_SESSION['myVar'];
    execute second script
    

    I hope this makes sense.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵