My Iframe Page

php сессия и iframe

Я прочитал пару связанных сообщений здесь, но, похоже, не могу сделать мою работу script по назначению. У меня есть страница входа в систему, в которой пользователь входит в систему. Если пароль совпадает, script записывает два значения в переменную $_SESSION : [‘loggedin’]=’yes’ и [‘loginname’]=»username» . После успешного входа пользователь переходит на другую страницу с 2-мя фреймами. Один iframe использует внешний контент и не требует аутентификации (удаление этого iframe со страницы ничего не меняет). Другой iframe использует динамически созданный контент из того же домена и проверяет, остались ли все переменные сеанса. Одна из функций обновляет содержимое этого динамически генерируемого iframe. Как только это будет сделано, переменные сеанса будут потеряны. Фактически, сам сеанс больше не существует. У меня есть session_start(); на каждой странице, которая используется в связи с этим script. Любая помощь будет принята с благодарностью.

У меня была проблема с сеансами на основе файлов cookie, которые не работали в моем iframe. Это было потому, что в браузере, с которым я тестировал, были отключены сторонние куки .

2 ответа

Короткий ответ: в iframe запустите сеанс следующим образом:

header('P3P: CP="CAO PSA OUR"'); session_start(); 

Думаю, я должен обновить этот ответ, так как я наткнулся на что-то интересное, о котором все должны знать.

Этот заголовок заголовка p3p не работает на сафари.

Ниже я описываю свой логин и как я решил эту проблему.

Мой поток входа выглядит так (приложение страницы):

  • проверка, имеет ли текущий пользователь сеанс,
  • если нет, перенаправляйте URL-адрес входа (сгенерированный PHP SDK),
  • диалог входа в систему перенаправляется обратно на URL-адрес, где я использую параметр «код» GET, который дает мне, чтобы получить токен доступа, который я могу сохранить для последующего использования. (Сохранение в DB и для сеанса.) Если я покончу с этим, я перенаправляю пользователя в свое приложение для страниц, где все будет работать.
  • каждый должен быть счастлив на этом этапе.
Читайте также:  Create set string java

НО здесь идет поиск.

Если пользователь использует сафари и пытается открыть это приложение, когда сеансы уже были уничтожены (через несколько дней для примера), произойдет следующее:

  • Код проверяет сеанс: он находит идентификатор пользователя (метод PHP SDK getUser()), поэтому я сначала проверяю запись в базе данных.
  • С тех пор, как пользователь вошел в систему раньше, у него есть запись в базе данных, поэтому я просто возьму его и сохраню на сеанс, так что будущие вызовы AJAX будут иметь всю необходимую им информацию.

Важно отметить, что этот код работает на вкладке страницы внутри iframe.

Итак, для большинства пользователей код будет работать, из-за взлома заголовка p3p.

Но для пользователей сафари это не будет.

Safari не заботится о данном заголовке, он отказывается сохранять сеанс, поэтому пользователь входит в приложение, все работает нормально, но вызовы ajax не будут работать, так как они не будут иметь любой сеанс для работы.

Обходной путь:

Довольно просто на самом деле — хотя и не слишком изящный, но эй, он работает. -: Я проверяю, является ли клиентский браузер сафари или нет, и если это так, я перенаправляю к настраиваемому URL-адресу, где я запускаю сеанс — за пределами фреймворка iframe, а затем перенаправляю обратно в приложение.

Это создаст файл cookie без проблем, поэтому сеансы будут доступны.

Здесь есть код:

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') && !strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome')) < if (count($_COOKIE) === 0) < echo ' '; > > 
header('P3P: CP="CAO PSA OUR"'); session_start(); $_SESSION = array(); echo '  '; 

Я надеюсь, что этот дополнительный трюк поможет кому-то.

Я еще не пробовал это, но вместо добавления заголовка P3P вы могли бы просто добавить следующие строки в ваш .htaccess:

  Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"" 
# ------------------------------------------------------------------------------ # | Cookie setting from iframes | # ------------------------------------------------------------------------------ # Allow cookies to be set from iframes in IE. # http://msdn.microsoft.com/en-us/library/ms537343.aspx # http://www.w3.org/TR/2000/CR-P3P-20001215/ Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"" 

Все кредиты для этого .htacces кода для парней, стоящих за проектом Yeoman.

для nginx в блоке http / server / location добавьте add_header P3P ‘policyref = «/ w3c / p3p.xml», CP = «IDC DSP COR ADM DEVI TAIi PSA PSD IVAi IVDi CONI СВОЙ ИНД CNT», CP = «CAO PSA НАШ» «’;

Добавьте следующие кадры на каждый из ваших страниц в фреймах:

echo «Session ID: «.session_id();

Это должно выводить идентификатор сеанса на каждой странице. Возможно, что новый сеанс может быть сгенерирован на одном из фреймов, проверив выше, вы можете исключить эту возможность.

Хорошо, я добавил эту строку, и результат меня ошеломляет. Идентификатор сеанса такой же, но сценарий не выполняется условие if ($ _SESSION). Итак, у меня есть этот код: if (!$_SESSION) < echo "no session"; echo session_id(); >Удивительно, но я получаю следующий вывод: «без идентификатора сеанса: 2c49b03084d3a5112e332e0d53008650» В нормальных условиях код «без сеанса» возвращает пользователя обратно на этап аутентификации. Как это возможно, что $ _SESSION var пуст, но все еще есть идентификатор сеанса?

вау, это стыдно Исеть исправил условие. Но у меня все еще есть проблема исчезающих переменных, потому что теперь не выполняется другое условие: if (($_SESSION[‘AdminLoggedIn’]!=»YES») || ($_SESSION[‘AdminName’]==»»))

Это важное различие . сегодня я уже второй раз сталкиваюсь с вопросом, где «if (! $ Var)» считается тем же, что и «if (! Isset ($ var))», и это Легко понять, почему можно предположить, что если что-то не установлено, оно должно быть ложным. Здесь есть хорошее разъяснение: stackoverflow.com/questions/844410/whats-better-isset-or-not

Источник

How 2 Guru

Hi guys, recently i am so busy and not able to update my website often.

But today, I face a problem on the PHP session while using iframe to include a custom php file.
The custom php file just doing some select/update command using session data.
I try my script in Google Chrome & Mozilla Firefox, everything is working fine but not Internet Explorer.
The data inside the session is not retrievable and causing the entitle script not working.

Below is my sample script

 session_start(); //echo session_id(); //PRINT OUT THE SESSION ID if(!isset($_SESSION['mydata']) && $_POST['action'] == 'update') die("unable to get mydata"); $_SESSION['mydata'] = 'ANYTHING'; //PERFORM SELECT/UPDATE ?>

Above just a simple sample, if you using wordpress/joomla (php applications) and iframe the custom page and using Internet Explorer to retrieve and update it. The page should display “unable to get mydata” but not perform the update statement.
After debug for sometime, I try to print out the session_id() and found that everything the iframe page refresh, it will generate another new session_id but not use the previous id (This act differently with Firefox and Chrome) and this is the main issue causing my script is not working.

Then I google a bit and find the solution below.

What you need to do it just add in a single line command into your custom php page.

 header('P3P: CP="CAO PSA OUR"'); //ADD IN THIS LINE IN ORDER TO SOLVE THE INTERNET EXPLORER ALWAYS GET NEW SESSION ISSUE session_start(); //echo session_id(); //PRINT OUT THE SESSION ID if(!isset($_SESSION['mydata']) && $_POST['action'] == 'update') die("unable to get mydata"); $_SESSION['mydata'] = 'ANYTHING'; //PERFORM SELECT/UPDATE ?>

Источник

How 2 Guru

Hi guys, recently i am so busy and not able to update my website often.

But today, I face a problem on the PHP session while using iframe to include a custom php file.
The custom php file just doing some select/update command using session data.
I try my script in Google Chrome & Mozilla Firefox, everything is working fine but not Internet Explorer.
The data inside the session is not retrievable and causing the entitle script not working.

Below is my sample script

 session_start(); //echo session_id(); //PRINT OUT THE SESSION ID if(!isset($_SESSION['mydata']) && $_POST['action'] == 'update') die("unable to get mydata"); $_SESSION['mydata'] = 'ANYTHING'; //PERFORM SELECT/UPDATE ?>

Above just a simple sample, if you using wordpress/joomla (php applications) and iframe the custom page and using Internet Explorer to retrieve and update it. The page should display “unable to get mydata” but not perform the update statement.
After debug for sometime, I try to print out the session_id() and found that everything the iframe page refresh, it will generate another new session_id but not use the previous id (This act differently with Firefox and Chrome) and this is the main issue causing my script is not working.

Then I google a bit and find the solution below.

What you need to do it just add in a single line command into your custom php page.

 header('P3P: CP="CAO PSA OUR"'); //ADD IN THIS LINE IN ORDER TO SOLVE THE INTERNET EXPLORER ALWAYS GET NEW SESSION ISSUE session_start(); //echo session_id(); //PRINT OUT THE SESSION ID if(!isset($_SESSION['mydata']) && $_POST['action'] == 'update') die("unable to get mydata"); $_SESSION['mydata'] = 'ANYTHING'; //PERFORM SELECT/UPDATE ?>

Источник

PHP Session with Iframe uri?

Hi everyone, I really haven’t found much that would be fitting in a half
decent or secure way on this issue, but. Let’s say I have a website called mysupportsystem.com and I’ve incorporated
a third party cloud based ticketing system which is fed into the index page
via iframe at mysupportsystem.com/index.php. The user also has to sign in through a fairly simple log in form which is
also made available through the same iframe. Once the user signs in, the uri of the iframe simply changes to the
below uri; (not a real link — just an example only) techportal.ticketsupport.com/protected/examplelandingpage.aspx From there on, the user has a choice between a handful of forms that they
can fill out and send into the third party ticketing system. If the user chooses, he or she also has the option to access a dynamic or custom
form which does not have an iframe embedded in a seperate custom page: mysupportsystem.com/customform_01.php The problem is, I don’t want to make these custom pages on the
mysupportsystem.com site available if the user has not signed in via
the third party ticketing system. The other problem is that I do not have access to the database in which the
cloud based ticketing system is utilizing to keep the user information, so
this is not an option to harness as a session reference either. My thought was that perhaps I could somehow utilize PHP to reference
the url as shown below: techportal.ticketsupport.com/protected/examplelandingpage.aspx In the way that the code works below is that when a user receives a
notification in thier email after filling out a ticket, a ticket reference link
is also embedded. When the user clicks on that reference link, it will take them right to
the techportal.ticketsupport.com website and also resolve the
organizationID as well as TicketID after login. (See “$iframe_url”). After that, the URL in the iframe remains as such, no matter where
the user navigates within the iframe; techportal.ticketsupport.com/protected/examplelandingpage.aspx in a basic sense of what I’m trying to accomplish is, if the url is
“true”, this would allow the user to access the custom form pages
outside from the index page that is serving the iframe. If it is false, it would prevent the user to access the custom form
pages. To put this in another thought, the original idea I had was to treat the “$iframe_url” or
the above URL as a session requirement and perhaps use a php “include” and/or
requirement based on the URL session in each custom page referencing it,
but I’m not sure on how to or if that would be even possible or the best
way to treat this scenario? I’m almost thinking; would I need to use cookies to accomplish this? If the
user has cookies disabled, (which some do) they won’t have access, so I’m
trying to avoid this too. Any solutions, references, code samples and/or directions that any of you
can point me out to would be so much appreciated. To all of you, thank you ahead of time for taking a peak and most of
all — for all of your help!

 else if($_GET == array() || !$_GET)< $iframe_url = 'https://techportal.ticketsupport.com?OrganizationID=xxxx'; >else if($_GET['TicketNumber'] !="")< $iframe_url = 'https://techportal.ticketsupport.com/protected/ticketdetail.aspx'.$qs; >else< $iframe_url = 'https://techportal.ticketsupport.com'.$qs; > function create_qs($vars,$addvar="") < if($vars == "all")< $vars = array_keys($_GET); >$queryString = ""; if(!is_array($addvar)) < $addvar = explode(",",$addvar); $ta = array(); foreach($addvar as $keyval)< $temp = explode("=",$keyval); $k = $temp[0]; $ta[$k] = $temp[1]; >$addvar = $ta; > $addKeys = array_keys($addvar); if(!is_array($vars)) < $vars = explode(",",$vars); foreach($vars as $key =>$value) < $vars[$key] = trim($value); >> foreach($vars as $key) < if(in_array($key,$addKeys))< continue; >if($queryString == "")< $q_a = "?"; >else < $q_a = "&"; >if($_GET[$key] == "")< $x = ""; >else < $x = $q_a.$key."=".$_GET[$key]; >$queryString .= $x; > if($addvar != "") < foreach($addvar as $key =>$value)< if($queryString == "")< $q_a = "?"; >else < $q_a = "&"; >if($value == "")< $x = ""; >else < $x = $q_a.$key."=".$value; >$queryString .= $x; > > return $queryString; > ?>       

Источник

Оцените статью