php curl php session

How do I get session_id() from cURL

I have a few questions about cURL:

Do I need to use session_start() with cURL?

If not, how do I get the session_id() from cURL?

When is that session_id() generated?

What’s the difference between initializing a cURL session ( curl_init ) and execute a cURL session ( curl_exec )?

php curl php session. Смотреть фото php curl php session. Смотреть картинку php curl php session. Картинка про php curl php session. Фото php curl php session

4 Answers 4

php session is transmited in cookies by default, if you get the web by cURL, and trying to access another section of the same web, then you must add session which you got from cURL

php curl php session. Смотреть фото php curl php session. Смотреть картинку php curl php session. Картинка про php curl php session. Фото php curl php session

You may want to consider an alternative solution to your problem of handing off a user from one site to another and still maintain their ‘logged in’ status.

I posted a response to a similar topic you may want to check out: Session lost when switching from HTTP to HTTPS in PHP

In a nutshell, you can create a hash key, redirect the user to siteB, look up the hash key and if they line-up, log the user into siteB.

php curl php session. Смотреть фото php curl php session. Смотреть картинку php curl php session. Картинка про php curl php session. Фото php curl php session

First, sessions and cURL are completely different and unrelated things. The session acts like a server side cache for the current user. cURL is a way of sending HTTP requests in PHP such as GET and POST. Some APIs require the use of cURL to interact with them from within your own PHP scripts/code.

The session_id() function is used to either get or set the current session id of the current user. If you want to set the session id to 7 for example, you would call

If you wanted to get the session id, you would call

The session id is generated when you call session_start() unless you’ve set it yourself before session_start() is called.

php curl php session. Смотреть фото php curl php session. Смотреть картинку php curl php session. Картинка про php curl php session. Фото php curl php session

cURL is a library for establishing connections to servers (just like your web browser does) and has no session_id to speak of (as it’s just retrieving what the client sees and session_id() would be a server-side method).

With that said, usually the session ID can be found in the headers of the request, such as the Set-Cookie header (or sometimes in the URL itself). So, if you need to determine the session I would look in to using the Cookie Jar functionality of cURL or make sure to retrieve the contents with headers so you can view the Set-Cookie value(s).

Источник

curl_init

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_init — Initialize a cURL session

Description

Parameters

If provided, the CURLOPT_URL option will be set to its value. You can manually set this using the curl_setopt() function.

The file protocol is disabled by cURL if open_basedir is set.

Return Values

Returns a cURL handle on success, false on errors.

Changelog

VersionDescription
8.0.0On success, this function returns a CurlHandle instance now; previously, a resource was returned.
8.0.0url is nullable now.

Examples

Example #1 Initializing a new cURL session and fetching a web page

// create a new cURL resource
$ch = curl_init ();

See Also

User Contributed Notes 1 note

On recent distributions CURL and PHP support for CURL have not been included in the main product. In particular in recent distributions of Ubuntu Linux CURL and PHP support for CURL are not even available from the official repositories. The steps to incorporate support are complex and require adding a non-standard repository. It is therefore advisable for programmers to rewrite code to use the stream interface to access resources across the Internet. For example:

«`php
$opts = array(
‘http’ => array (
‘method’=>»POST»,
‘header’=>
«Accept-language: en\r\n».
«Content-type: application/x-www-form-urlencoded\r\n»,
‘content’=>http_build_query(array(‘foo’=>’bar’))
)
);

This stream support can also be accessed using the object-oriented interface of SplFileObject.

Источник

PHP NTLM session with cURL

So a little trivia first..

There is written in ASP.NET website, which uses NTLM protocol to authenticate users that want to log in. It’s perfectly ok when they normally use it, they type in website URL, they provide their credentials, authenticate and maintain session in web browser.

What I want to do, is create PHP website that will act as bot. It is my companys internal website and I am approved to do so. The problem I run into, is managing session. Users will be able to type in their credentials in my PHP website, and my PHP website will authenticate them to target site, using cURL.

The code I got so far is:

Above code logs in to target website by cURL (which manages NTLM handshake, as it seems), and fetches websites content. It also stores Session ID that is sent back in cookie file.

What I’m trying to do next, is comment the CURLOPT_USERPWD option, in hope that this script will use session ID stored in cookie file to authenticate previously logged in user in second execution of this script. It could get rid of user credentials and do not store it anywhere that way, becouse it is not safe to store it in manually created session, database, or anywhere else.

I need this becouse bot will be using CRON to periodically check if website status has changed and perform some user actions as reaction to this. But to do this, user first must be authenticated, and his username and password must not be stored anywhere, so I have to use session information estabilished when he initially logged in.

CURL seems to NOT DO THIS. When I execute script second time with commented CURLOPT_USERPWD option, it does not use stored cookie to keep beeing authenticated. Instead, it REWRITES cookie file with not relevant data send to me from service as response to NOT AUTHRORISED access request.

My questions are: Why cURL doesnt use stored session information to keep beeing authenticated? Is there any way to maintain this session with cURL and NTLM protocol based website?

Источник

Client URL Library

User Contributed Notes 27 notes

I wrote the following to see if a submitted URL has a valid http response code and also if it responds quickly.

Use the code like this:

Hey I modified script for php 5. Also I add support server auth. and fixed some little bugs on the script.

[EDIT BY danbrown AT php DOT net: Original was written by (unlcuky13 AT gmail DOT com) on 19-APR-09. The following note was included:
Below is the my way of using through PHP 5 objecte oriented encapsulation to make thing easier.]

I needed to use cURL in a php script to download data using not only SSL for the server authentication but also for client authentication.
On a default install of Fedora, setting up the proper cURL parameters, I would get an error:

$ php curl.php
Peer certificate cannot be authenticated with known CA certificates

The data on http://curl.haxx.se/docs/sslcerts.html was most useful. Indeed, toward to bottom it tells you to add a missing link inside /etc/pki/nssdb to use the ca-bundle.crt file. You do it so:

Now you can do client authentication, provided you have your certificate handy with:

In this example: http://php.net/manual/en/book.curl.php#102885 by «frank at interactinet dot com»

There’s a small bug in

?>

The code will immediately leave the function at the `return`, and pcntl_wait() will NEVER be executed, under any circumstances.

I can’t see any other issues with this function however.

Sharing is caring, handles included.

$user_agent = ‘Mozilla HotFox 1.0’ ;

CURL failed with PHP5.3 and Apache2.2.X on my Windows 7 machine.

It turns out that it’s not enough to copy the two dll’s mentioned (libeay32 and sslea32) from the php folder into your system32 folder. You HAVE TO UNBLOCK THESE TWO FILES.

Right click the file, select unblock, for each one. Then restart Apache.

Another very handy security feature added into Windows.

Here you have a function that I use to get the content of a URL using cURL:

You can use this class for fast entry

[EDIT BY danbrown AT php DOT net: Includes a bugfix provided by (manuel AT rankone DOT ch) on 24-NOV-09 to properly reference cURL initialization.]

Источник

Php curl php session

PHP поддерживает libcurl, библиотеку, созданную Daniel»ом Stenberg»ом, которая даёт возможность соединяться с серверами различных типов и по разным протоколам.
libcurl в настоящее время поддерживает протоколы http, https, ftp, gopher, telnet, dict, file и ldap.
libcurl также поддерживает сертификаты HTTPS, HTTP POST, HTTP PUT, загрузку по FTP (это можно сделать также РНР-расширением ftp), загрузку на основе форм HTTP, прокси, куки и аутентификацию user+password.

Эти функции были введены в PHP 4.0.2.

curl_init

Описание

resource curl_init([string url])

Функция curl_init() инициализирует новую сессию и возвратит CURL-дескриптор для использования в функциях curl_setopt(), curl_exec() и curl_close(). Если необязательный параметр url предоставлен, то опция CURLOPT_URL получит значение этого параметра. Вы можете вручную устанавливать его с помощью функции curl_setopt().

curl_setopt

Описание

bool curl_setopt (resource ch, string option, mixed value)

Функция curl_setopt() устанавливает опции для CURL-сессии, идентифицируемой параметром ch. Параметр option является опцией, которую вы хотите установить, а value это значение опции option.

Параметр value должен быть long для следующих опций (специфицированных параметром option):

Параметр value должен быть строкой для следующих значений параметра option:

Следующие опции ожидают дескриптора файла, который получается с помощью функции fopen():

Параметр value должен быть функцией следующего вида long write_callback (resource ch, string data) для следующих значений параметра option:

Параметр value должен быть функцией следующего вида string read_callback (resource ch, resource fd, long length)<> для следующих значений параметра option:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *