【PHP】POSTで画像アップロード
キーボードを新調したので、だいぶご機嫌です。
やっと家と会社で同じのが使えるー♪
キーボード届くから仕事放置でさっさと帰ってきました♪
ちょっと前にiOSとASP .NETのやつ晒しましたが、今日はPHPですねー
今日も手抜きでまたまた昔書いたやつからの抜粋です。
これ書いたの何年前だろう。。。
common.php
<?php class common { public function path_to_url($path, $default_port = 80){ $document_root_url = $_SERVER['SCRIPT_NAME']; $document_root_path = $_SERVER['SCRIPT_FILENAME']; while(basename($document_root_url) === basename($document_root_path)){ $document_root_url = dirname($document_root_url); $document_root_path = dirname($document_root_path); } if($document_root_path === '/') $document_root_path = ''; if($document_root_url === '/') $document_root_url = ''; $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] !== 'off')? 'https': 'http'; $port = ($_SERVER['SERVER_PORT'] && $_SERVER['SERVER_PORT'] != $default_port)? ':'.$_SERVER['SERVER_PORT']: ''; $document_root_url = $protocol.'://'.$_SERVER['SERVER_NAME'].$port.$document_root_url; $absolute_path = realpath($path); if(!$absolute_path) return false; if(substr($absolute_path, -1) !== '/' && substr($path, -1) === '/') $absolute_path .= '/'; $url = str_replace($document_root_path, $document_root_url, $absolute_path); if($absolute_path === $url) return false; return $url; } }
uploadPhoto.php
<?php include 'common.php'; $common = new common(); $uploaddir = '../../photo/'; $arr = split("_", basename($_FILES['file']['name'][0])); $uploadfile = $uploaddir . $arr[0] . "/" . $arr[1]; if (move_uploaded_file($_FILES['file']['tmp_name'][0], $uploadfile)) { $result = array(); $result["url"] = $common->path_to_url($uploadfile); print(json_encode($result)); } else { print(0); } ?>