2013-01-03 3 views
0

이미지 경로를 데이터베이스에 저장하고 업로드 한 후에 표시하는 방법은 무엇입니까?이미지 경로를 데이터베이스에 삽입하는 방법은 무엇입니까?

<?php 
$sub=0; 
ini_set("display_errors", 0); 
if(isset($_REQUEST['submited'])) { 
// your save code goes here 

$allowedExts = array("jpg", "jpeg", "gif", "png"); 
$extension = end(explode(".", $_FILES["file"]["name"])); 
if ((($_FILES["file"]["type"] == "image/gif") 
|| ($_FILES["file"]["type"] == "image/jpeg") 
|| ($_FILES["file"]["type"] == "image/png") 
|| ($_FILES["file"]["type"] == "image/pjpeg")) 
&& ($_FILES["file"]["size"] < 2097152) 
&& in_array($extension, $allowedExts)) 
{ 
if ($_FILES["file"]["error"] > 0) 
{ 
echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; 
} 
else 
{ 
echo ""; 
if (file_exists("images/" . $_FILES["file"]["name"])) 
{ 
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload already exists.</b></font>"; 
    } 

else 
{ 
move_uploaded_file($_FILES["file"]["tmp_name"], 
"images/" . $_FILES["file"]["name"]); 
$sub= 1; 
echo "<font size='7' color='white'><b> Success! Your photo has been uploaded.</b></font>"; 

} 

} 
} 
else 
{ 
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload is not an image or it exceeds 2MB in size.</b></font><br><font color='blue'><i>Only images under size of 2MB are allowed</i></font>."; 
} 
} 

?> 
<form action="" method="post" enctype="multipart/form-data"> 
<input type="hidden" name="submited" value="true" /> 

<?php 
ini_set("display_errors", 0); 
if($sub==0) 
{ 
?> 
<label size="16" for="file">Choose Photo:</label> 
<input id="shiny" type="file" name="file" onchange="file_selected = true;"> 
<input id="shiny" type="submit" value="Upload" name="submit"> 
<?php 
} 
?> 

</form> 

여기서 데이터베이스 정보는 ... 어떻게 데이터베이스에 이미지 경로를 삽입 한 후 그림을 표시합니까? 나는 VALUES ('$_FILES["file"]["name"]')"; 시도했지만 그것은 작동하지 않는 것 ..

<?php 
$con = mysql_connect("localhost","root",""); 
if (!$con) 
{ 
die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db("simple_login", $con); 

$sql="INSERT INTO photo (photo) 
VALUES 
('$_FILES["file"]["name"]')"; 

if (!mysql_query($sql,$con)) 
{ 
die('Error: ' . mysql_error()); 
} 

mysql_close($con); 
?> 
+2

** 경고 ** 당신의 코드는 [SQL 주입 취약점]를 포함 (http://en.wikipedia.org/wiki/SQL_injection)! - 직접 원시, 필터링되지 않은, 확인되지 않은 사용자 입력을 전달하는 SQL 문자열로 변환합니다. SQL 주입은 [매우 쉽게 고칠 수 있습니다] (http://stackoverflow.com/q/60174/168868). [PDO로 전환] (http://php.net/book.pdo) 또는 [mysqli] (http://php.net/book.mysqli)를 고려하여 [매개 변수화 된 쿼리와 함께 준비된 문구] (http : //en.wikipedia.org/wiki/Prepared_statement). – Charles

+0

왜이 작업을 수행할까요? – Woot4Moo

답변

1
"INSERT INTO photo (photo) VALUES ('{$_FILES["file"]["name"]}')" 

작동합니다 그. 문자열에서 연관 배열을 사용하려면 중괄호 ({}) 대괄호로 묶어야합니다. 나는 특정 질문과 관련이없는 것을 확인하고 싶은


3 포인트 :

1 : 당신은 항상 데이터베이스에로두기 전에 사용자 입력을 sanatize한다. 그래서 당신이해야 할 일은 다음과 같습니다 :

"INSERT INTO photo (photo) VALUES ('" . mysql_real_escape_string($_FILES["file"]["name"]) . "')" 

또는 mysqli 또는 pdo와 함께 prepared statement를 사용하십시오.

: 데이터베이스의 파일 목록을 저장하는 중일 때는 요점은 무엇입니까? 왜 당신이 그들을 저장하고있는 디렉토리를 반복하지 않는가?

3 : mysql_* 기능은 당신이 당신의 도움들에 대한 ..... 나는 그냥 내가 너무 SQL 주입을 방지 할 수 있습니다 Mysqli를 사용하여 해결 가지고 감사를

+0

내가 실제로 원하는 것은 "images /"디렉토리에 이미지를 저장하는 것이 었습니다 ... 데이터베이스에 이미지 경로를 저장하지 않으면 어떻게 검색합니까? – Magna

+0

정확하게 "검색"한다는 것은 무엇을 의미합니까? 웹 사이트에 표시하고 수정 하시겠습니까? 디렉토리의 다른 파일과 마찬가지로 파일 이름 (이 파일 이름을 검색하려고하면 이미 알고있는 파일 이름)에 액세스 할 수 있습니다. 사용자 (또는 다른 데이터)와 이미지를 연관시키지 않는 한, 데이터베이스 내에 파일 이름 목록을 저장하는 것이 중요하지 않습니다. – Supericy

+0

검색하여 나는 디스플레이를 의미 ...... 내 웹 사이트에 다른 텍스트 데이터로 이미지를 표시 할 것입니다. 그래서 데이터베이스에 파일 이름을 저장해야합니까? – Magna

0

mysqli 또는 pdo 사용을 고려해야합니다, 감가 상각하고 있습니다 .. .

<?php 
$sub=0; 
ini_set("display_errors", 0); 
if(isset($_REQUEST['submited'])) { 

// your save code goes here 

$allowedExts = array("jpg", "jpeg", "gif", "png"); 
$extension = end(explode(".", $_FILES["file"]["name"])); 
if ((($_FILES["file"]["type"] == "image/gif") 
|| ($_FILES["file"]["type"] == "image/jpeg") 
|| ($_FILES["file"]["type"] == "image/png") 
|| ($_FILES["file"]["type"] == "image/pjpeg")) 
&& ($_FILES["file"]["size"] < 2097152) 
&& in_array($extension, $allowedExts)) 
{ 
if ($_FILES["file"]["error"] > 0) 
{ 
echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; 
} 
else 
{ 
echo ""; 
if (file_exists("images/" . $_FILES["file"]["name"])) 
{ 
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload already exists.</b></font>"; 
    } 

else 
{ 
move_uploaded_file($_FILES["file"]["tmp_name"], 
"images/" . $_FILES["file"]["name"]); 
$sub= 1; 
$mysqli = new mysqli("localhost", "root", "", "simple_login"); 

// TODO - Check that connection was successful. 

$photo= $_FILES["file"]["name"]; 

$stmt = $mysqli->prepare("INSERT INTO photo (photo) VALUES (?)"); 

// TODO check that $stmt creation succeeded 

// "s" means the database expects a string 
$stmt->bind_param("s", $photo); 

$stmt->execute(); 

$stmt->close(); 

$mysqli->close(); 

echo "<font size='7' color='white'><b> Success! Your photo has been uploaded.</b></font>"; 
} 

} 
} 
else 
{ 
echo "<font size='4' color='red'><b>We are sorry, the file you trying to upload is not an image or it exceeds 2MB in size.</b></font><br><font color='blue'><i>Only images under size of 2MB are allowed</i></font>."; 
} 
} 

?> 
<form action="" method="post" enctype="multipart/form-data"> 
<input type="hidden" name="submited" value="true" /> 


<?php 
ini_set("display_errors", 0); 
if($sub==0) 
{ 
?> 
<label size="16" for="file">Choose Photo:</label> 
<input id="shiny" type="file" name="file" onchange="file_selected = true;"> 
<input id="shiny" type="submit" value="Upload" name="submit"> 
<?php 
} 
?> 


</form> 
</div> 
관련 문제