2012-06-17 5 views
2

내 앱은 등록시 이미지와 사용자/이메일/패스를 업로드합니다. iOS에서 php로 mySQL. 이메일, 사용자 & 패스 & 이미지 이름은 db에 저장됩니다. 그 이미지는 서버의 폴더로 업로드되지 않습니다. 그래서 내 코드의 일부분이 실패하고 있지만, 어디서 볼 수 있습니까? 내가 잘 작동 확신ASIHTTPRequest를 사용하여 iOS에서 이미지 업로드

<? 
include"master_inc.php"; 
//--------------------------------------------------------------------------RECEIVE LOCAL VARIABLES FROM FORM 
$lastname = strip_tags(substr($_POST['lastname'],0,32)); 
$firstname = strip_tags(substr($_POST['firstname'],0,32)); 
$phone = strip_tags(substr($_POST['phone'],0,32)); 
//$image = $_POST['image']; 
$photo=($_FILES['photo']['name']); 

$password_hint=$_REQUEST['password_hint']; 
$noERROR=1; 
$udidposted = 9; 

//---------------------------------------------------------------------------CHECK IF USERNAME IS LONG ENOUGH 
$username = strip_tags(substr($_POST['username'],0,32)); 
if(trim($username)!=='' && strlen(trim($username)) >= 4){ 
//---------------------------------------------------------------------------IF LONG ENOUGH THEN RUN A QUERY GETTING ALL DATA FROM THAT USER 
$sql="SELECT * FROM users WHERE username='$username'"; 
$result=mysql_query($sql); 
$count=mysql_num_rows($result); 
//---------------------------------------------------------------------------IF $sql GOTTEN HAS ROW COUNT > 1 THEN USER ALREADY EXISTS----------------SET EXISTING USER 104 FLAG 
if($count>0){ 
$username_already_in_use = 3141; 
} 
//---------------------------------------------------------------------------ELSE USERNAME IS TOO SHORT?!?!-------------------------------------------------------SET USER TOO SHORT 104 FLAG 
}else{ 
$username_too_short = 3142;} 

//---------------------------------------------------------------------------EMAIL FORMAT CHECK 
$email_raw = $_REQUEST['email']; 
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@([a-z0-9-]{2,3})+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email_raw)) 
{ 
$email = $email_raw; 
}else{ 
//---------------------------------------------------------------------------IF INVALID EMAIL THEN----------------------------------------------------------------------SET INVALID EMAIL 104 FLAG 
$bad_email=3143; 
} 

//email unique? 
$sql="SELECT * FROM users WHERE email='$email'"; 
$result=mysql_query($sql); 
$count=mysql_num_rows($result); 
if($count>0){ 
//---------------------------------------------------------------------------IF SQL FOR EMAIL RETURNS A ROW THEN------------------------------------------------SET EMAIL 104 FLAG 
$email_already_in_use=3144; 
} 

//Secure Password Format Checks 
$pw_clean = strip_tags(substr($_POST['password'],0,32)); 
if (preg_match("/^.*(?=.{4,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pw_clean, $matches)) { 
}else{ 
//---------------------------------------------------------------------------IF PW NOT IN FORMAT THEN-----------------------------------------------------------------SET PW 104 FLAG 
$pw_insecure = 3145; 
} 

//---------------------------------------------------------------------------IF ERROR FLAGS ARE SET THEN LOG HEADERS---------------------------- 
if($username_already_in_use==3141 OR $email_already_in_use==3144 OR $pw_insecure==3145 OR $bad_email==3143 OR $username_too_short==3142){ 
header(
"location:user_add_errors.php?pw_insecure=$pw_insecure&email_already_in_use=$email_already_in_use&username_already_in_use=$username_already_in_use&bad_email=$bad_email&username_too_short=$username_too_short"); 
die(); 
} 
else {header("location:user_add_errors.php?noERROR=$noERROR");} 

//End Error Checks________________________ 

//-------------------------------------------------------------------INSERT INTO SQL 
//Encrypt Password 
$encrypted_pw = md5($pw_clean); 
$query = "INSERT INTO `users` (`username`, 
`password`, 
`lastname`, 
`firstname`, 
`email`, 
`phone`, 
`password_hint`, 
`udid`, 
`userCreated`, 
`photo`) 
VALUES 
(
'$username', 
'$encrypted_pw', 
'$lastname', 
'$firstname', 
'$email', 
'$phone', 
'$password_hint', 
'$udidposted', 
now(), 
'$photo')"; 
// save the info to the database 
$results = mysql_query($query); 

//-----------------------CODE FOR SAVING IMAGE STARTS 
//This is the directory where images will be saved 
$target = "images/"; 
$target = $target . basename($_FILES['photo']['name']); 

//This gets all the other information from the form 
$photo=($_FILES['photo']['name']); 

//Writes the photo to the server 
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 

//Tells you if its all ok 
echo "The file ". basename($_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
} 
//-----------------------CODE FOR SAVING IMAGE ENDS 

// print out the results 
if($results) 
{ 
    if($username_too_short==3142){echo"ShortUser=".$username_too_short;} 

    if($username_already_in_use==3141){echo"UserTaken=".$username_already_in_use;} 

    if($email_already_in_use==3144){echo"EmailTaken=".$email_already_in_use;} 

    if($pw_insecure==3145){echo"ShortPass=".$pw_insecure;} 

    if($bad_email==3143){echo"BadEmail".$bad_email;} 



//echo("<font size='2' face='Verdana, Arial, Helvetica, sans-serif'>Your changes have been made sucessfully. <br><br><a href='login.php'>Back to login</a></font> "); 
} 
else 
{ 
die("Trouble saving information to the database: " . mysql_error()); 
} 
//--------------------------------------AGAIN?! THIS IS FOR THE FIRST ENTRY I THINK 
$sql="SELECT * FROM users"; 
$result=mysql_query($sql); 
$count=mysql_num_rows($result); 
if($count==1){ 

$query = "UPDATE `users` SET `permissions`='5' WHERE `email`='$email'"; 
//---------------------------------------SAVE the info to the database 
$results = mysql_query($query); 
//---------------------------------------JUST PRINT CODE 
if($results) 
{ echo("ADMINCREATED"); 
} 
else 
{ 
die("ERRORSAVINGADMIN" . mysql_error()); 
} 

} 
?> 

내 아이폰 OS 코드 : 내 서버에이 코드가

-(void)callASIHTTP{ 

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.myserver.com/learn/login/user_save2.php"]];  
    // Upload an NSData instance 
    NSData *imageData = UIImageJPEGRepresentation(self.pickedImage, 90); 

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 
    [request addPostValue:self.userName.text forKey:@"username"]; 
    [request addPostValue:self.userPass.text forKey:@"password"]; 
    [request addPostValue:self.userEmail.text forKey:@"email"]; 
    [request addData:imageData withFileName:self.userName.text andContentType:@"image/jpeg" forKey:@"photo"]; 

    //check if passedData is nil 
    if (imageData == nil) { 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title:iDnil" message:@"msg:iDnil" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [alertView show]; 
     [alertView release]; 
    } 

    //completion blocks 
    [request setCompletionBlock:^{ 
     NSString *responseString = [request responseString]; 
     if (responseString == nil) { 
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title:rStrg" message:@"msg:rStrg" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
      [alertView show]; 
      [alertView release]; 
     } 
    }]; 
    [request setFailedBlock:^{ 
     NSError *error = [request error]; 
     NSLog(@"Error: %@", error.localizedDescription); 
    }]; 

    [request startAsynchronous]; 

} 

답변

2

나는 당신의 문제를 안다. 나는 smilar 문제에 직면했다 .. 당신은 이미지의 경로를 주어야한다. 다음 코드는 이미지에서 경로를 얻을 것이다. 이미지가 디렉토리 색인에 있다면 .. 여기 좋아

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder 
     NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"photo.jpg"]; 
[request setFile:[NSURL URLWithString:dataPath] forKey:@"photo"]; 

//IF the photo is in directory index use the following code to get the url 
NSString *filename = [[NSBundle mainBundle] pathForResource:@"photo" ofType:@"png"]; 
[request setFile:[NSURL URLWithString:filename] forKey:@"photo"]; 

.. 경로는 조금 다른 받기를 시도하고 알려해야하면 이미지가이 코드를 사용하여 업로드하는 동안

- (void) imagePickerController:(UIImagePickerController *)thePicker didFinishPickingMediaWithInfo:(NSDictionary *)imageInfo 
{ 
    imagePicker = nil; 

    UIImage *image = [imageInfo objectForKey:@"UIImagePickerControllerEditedImage"]; 
    image = [image roundedCornerImage:23.5 borderSize:1]; 




    // Get the data for the image as a JPEG 
    NSData* imageData = UIImageJPEGRepresentation(image, 0.5); 

    // Give a name to the file 
    NSString* imageName = @"photo.png"; 

    // Now, we have to find the documents directory so we can save it 
    // Note that you might want to save it elsewhere, like the cache directory, or something similar. 
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString* documentsDirectory = [paths objectAtIndex:0]; 

    // Now we get the full path to the file 
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName]; 
    [imageData writeToFile:fullPathToFile atomically:NO]; 
    myPicture = imageData; 
    myPicturePath = fullPathToFile;  

    // Dismissing the image picker view 
    [self dismissModalViewControllerAnimated: YES]; 
} 

UIImagePicker

위해 작성해야하는 코드입니다. 이미지 픽커에서 myPicture 경로를 설정하게됩니다 ..

Request setFile:myPicturePath forKey:@"photo"]; 

다음 코드는 ... 문서 디렉토리에서 이미지를 얻을 그것을 보내 내가 내 PHP 코드에 뭔가 생각 폴더 777을 준

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
       NSString* documentsDirectory = [paths objectAtIndex:0]; 

       // Now we get the full path to the file 
       NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"photo.png"]; 
       [imageData writeToFile:fullPathToFile atomically:NO]; 

       [Request setFile:fullPathToFile forKey:@"photo"]; 
+0

이 코드가 작동하지 않으면 .. 알려주세요 ... –

+0

uiimage를 nsdata로 설정하면 왜 경로가 필요합니까? – marciokoko

+0

"[NSString stringWithFormat : @"% @ ", @"photo.jpg "]"이 (가) 코드에 있습니까? 내 번들 에서이 파일을 업로드하지, 그것의 UIImagePicker에서 선택한 이미지 – marciokoko

0

내가 바보 것을 알고,하지만 난 단지에 비슷한 문제가 있었다 그것은 웹 서버에서 폴더 권한이었습니다.

+0

하지만 난 아니에요 물론 나는 PHP 전문가가 아니야. 이미지를 업로드하는 코드는 db 코드 바로 뒤에 있습니다. – marciokoko

관련 문제