<?php
session_start();
$valid_passwords = array ("LOGIN" => "PASSWORD");
$valid_users = array_keys($valid_passwords);
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];
$validated = isset($_SESSION['logged']) || ((in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]));
if (!$validated) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
die ("Not authorized");
} else {
$_SESSION['logged'] = date(time());
}
10 записей с тегом "network"
Посмотреть все тегиPHP: Как получить данные из тела запроса PUT, PATCH или DELETE?
<?php
// Получение данных из тела запроса
function getFormData($method) {
// GET или POST: данные возвращаем как есть
if ($method === 'GET') return $_GET;
if ($method === 'POST') return $_POST;
// PUT, PATCH или DELETE
$data = array();
$exploded = explode('&', file_get_contents('php://input'));
foreach($exploded as $pair) {
$item = explode('=', $pair);
if (count($item) == 2) {
$data[urldecode($item[0])] = urldecode($item[1]);
}
}
return $data;
}
PHP: Переадресация с передачей параметров
<?php
header("Status: 301 Moved Permanently");
header("Location: ./content/index.html".($_GET ? "?".$_SERVER['QUERY_STRING'] : ""));
die();
PHP: WWW-авторизация
<?php
$valid_passwords = array ("LOGIN" => "PASSWORD");
$valid_users = array_keys($valid_passwords);
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];
$validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);
if (!$validated) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
die ("Not authorized");
}
Python: Запрос JSON методом GET и парсинг
import requests
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below
# JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content
Python: Скачать с Яндекс Диска
import requests
from urllib.parse import urlencode
base_url = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?'
public_key = 'https://yadi.sk/d/UJ8VMK2Y6bJH7A' # Сюда вписываете вашу ссылку
# Получаем загрузочную ссылку
final_url = base_url + urlencode(dict(public_key=public_key))
response = requests.get(final_url)
download_url = response.json()['href']
# Загружаем файл и сохраняем его
download_response = requests.get(download_url)
with open('downloaded_file.txt', 'wb') as f: # Здесь укажите нужный путь к файлу
f.write(download_response.content)
Python: Скачать и сохранить бинарный файл
# Binary request and save
# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
f.write(response.content)
Python: Как отправить файл методом POST на сервер?
Загрузка файла на сервер методом POST и передача дополнительных полей:
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
JS: .htaccess для react-router
# If you are using Apache as your web server, you can insert this into your .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
# I am using react: "^16.12.0" and react-router: "^5.1.2" This method is the Catch-all and is probably the easiest way to get you started.
Python: Получить содержимое страницы «безголовым» Chrome
def get_page(url):
ua = r'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
exe = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
args = f'"{exe}" --headless --disable-gpu --dump-dom --user-agent="{ua}" "{url}"'
sp = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = sp.communicate()
print(err, 'error') if err else None
return out.decode('utf-8') if out else ''