Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php // upload.php
- // 'images' refers to your file input name attribute
- if (empty($_FILES['images'])) {
- echo json_encode(['success'=>'No files found for upload.']);
- // or you can throw an exception
- return; // terminate
- }
- // get the files posted
- $images = $_FILES['images'];
- // a flag to see if everything is ok
- $success = null;
- // file paths to store
- $paths= [];
- // get file names
- $filenames = $images['name'];
- // loop and process files
- for($i=0; $i < count($filenames); $i++){
- $ext = explode('.', basename($filenames[$i]));
- $target = "images" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
- if(move_uploaded_file($images['tmp_name'][$i], $target)) {
- $success = true;
- $paths[] = $target;
- } else {
- $success = false;
- break;
- }
- }
- // check and process based on successful status
- if ($success === true) {
- // call the function to save all data to database
- // code for the following function `save_data` is not
- // mentioned in this example
- $servername = "localhost";
- $username = "root";
- $password = "";
- $dbname = "keviandra";
- try {
- $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
- // set the PDO error mode to exception
- $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $sql = "INSERT INTO `gambar` (`image_id`, `url`) VALUES (NULL, '$target')";
- // use exec() because no results are returned
- $conn->exec($sql);
- echo $target;
- echo "New record created successfully";
- }
- catch(PDOException $e)
- {
- echo $sql . "<br>" . $e->getMessage();
- }
- $conn = null;
- // store a successful response (default at least an empty array). You
- // could return any additional response info you need to the plugin for
- // advanced implementations.
- $output = [];
- // for example you can get the list of files uploaded this way
- // $output = ['uploaded' => $paths];
- } elseif ($success === false) {
- $output = ['error'=>'Error while uploading images. Contact the system administrator'];
- // delete any uploaded files
- foreach ($paths as $file) {
- unlink($file);
- }
- } else {
- $output = ['error'=>'No files were processed.'];
- }
- // return a json encoded response for plugin to process successfully
- echo json_encode($output);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement