My app uploads an image and user/email/pass upon registration. iOS to php to mySQL. Email,user & pass & image name get saved to the db just fine. Its just the image that is not getting uploaded to the folder on the server. So its just that part of my code which is failing, but can anyone see where? I have this code on my server:

我的应用会在注册时上传图片和用户/电子邮件/通行证。 iOS到php到mySQL。电子邮件,用户和通行证以及图像名称都可以保存到数据库中。它只是没有上传到服务器上的文件夹的图像。所以它只是我的代码的一部分失败,但任何人都可以看到在哪里?我在我的服务器上有这个代码:

<?
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() );
}

}
?>

and my iOS code I'm pretty sure is working fine:

和我的iOS代码我很确定工作正常:

-(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 个解决方案

#1


2

I know your problem.. I have faced the smilar issue.. You have to give the path for the image.. The following code will get the image from the path.. if the image is in your directory index you have to get the path little different.. Try this and let me know..

我知道你的问题..我面临着微笑的问题..你必须给出图像的路径..以下代码将从路径获取图像..如果图像在你的目录索引中你必须得到路径差异很小..尝试这个让我知道..

        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"];

Ok here is the code you have to write for UIImagePicker

好的,这里是您必须为UIImagePicker编写的代码

- (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];
}

While uploading the image use this code.. You will have the myPicture path set from the image picker..

上传图像时使用此代码..您将从图像选择器设置myPicture路径..

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

The following code is to get the image from the document directory and send it..

以下代码是从文档目录中获取图像并发送它。

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"];

更多相关文章

  1. 在Web Page中包含PHP代码
  2. php mail函数一段好的代码
  3. 在PHP中将PDF文档转换为预览图像,而无需安装Ghostscript
  4. 用于上传多个文件的PHP代码
  5. (phpQuery)对网站产品信息采集代码的优化
  6. 韩顺平_php从入门到精通_视频教程_学习笔记_源代码图解_PPT文档
  7. 【MySQL 技巧分享】 mysql -e 加 v 简化代码
  8. Oracle相当于MySQL代码“插入虚拟”以返回错误消息
  9. 登录使用PHP并´t显示任何html代码

随机推荐

  1. android NDK 各个版本下载地址
  2. [android]android的容器、控件
  3. Android中的AsyncTask
  4. Android(安卓)Studio重构之路,我们重新来
  5. android 布局属性
  6. 居中对齐
  7. Android Contextual Menus之二:contextual
  8. 2010.12.10——— android 定位跟踪
  9. ?android:attr/属性 与 ?android:属性
  10. 【转】android manifest.xml中元素含义