上传前重命名图像,并使用PHP在数据库中插入名称

时间:2015-01-05 10:24:30

标签: php mysql rename

我希望在上传之前重命名图像,并且在重命名的图像名称之后应该使用PHP插入到数据库中。我使用以下代码上传图像并将一些其他数据插入数据库。请帮我重新命名图片,因为我是PHP的初学者。

<?php

  if(isset($_POST['submit'])) {
    $post_image = $_FILES['post_image']['name'];
    $post_image_tmp = $_FILES['post_image']['tmp_name'];
    $post_content = $_POST['post_content'];
    if ($post_image=='' OR $post_content=='') {
      echo "<script>alert('Fiil In All Fields')</script>";
    } else {
      move_uploaded_file($post_image_tmp, "../post_imgs/$post_image");
      $insert_post ="INSERT INTO posts(post_image,post_content)values('$post_image','$post_content')";
      $run_post= mysql_query($insert_post);
      echo "<script>alert('Post has been Published Now...')</script>";
      echo "<script>window.open('index.php?insert_post=insert','_self')</script>";
    }
  }

?>

2 个答案:

答案 0 :(得分:2)

        $tmp_file = $_FILES['uploadedfile']['tmp_name'];
        $ext = pathinfo($_FILES["uploadedfile"]["name"], PATHINFO_EXTENSION);
        $rand = md5(uniqid().rand());
        $post_image = $rand.".".$ext;
        move_uploaded_file($tmp_file,"../post_imgs/".$post_image);

答案 1 :(得分:2)

试试这个..

 <?php

  if(isset($_POST['submit'])) {
    $post_image = $_FILES['post_image']['name'];
    $post_image_tmp = $_FILES['post_image']['tmp_name'];
    $post_content = $_POST['post_content'];
    if ($post_image=='' OR $post_content=='') {
      echo "<script>alert('Fiil In All Fields')</script>";
    } else {
    $newname="image".$post_image; 
    $path='../post_imgs/';
$pathAndName = $path.$newname;
$moveResult = move_uploaded_file($post_image_tmp, $pathAndName);//move to folder
 $insert_post ="INSERT INTO posts(post_image,post_content)values('$newname','$post_content')";
      $run_post= mysql_query($insert_post);
      echo "<script>alert('Post has been Published Now...')</script>";
      echo "<script>window.open('index.php?insert_post=insert','_self')</script>";
    }
  }

?>