photo upload working on local host but not on server? - php

hi i have a photo upload script which is working fine on my local host but when i upload it to my ftp server it doesn't upload the file. any ideas why this is, i get no error or anything just doesn't upload the file.
heres my index.php file:
<div id="areas">
<input type="file" class="droparea spot" name="xfile" data-post="upload_image_1.php" data-width="90" data-height="90" data-crop="true"/>
<form id="sampleform" action="post_image_1.php" method="post">
</form>
<script>
$('#sampleform').submit(function(e){
e.preventDefault();
$.ajax({
url:$(this).attr('action'),
type:'post',
data:$(this).serialize(),
dataType:'json',
success:function(r){
$('#form-result').append(
'<div><b>Title: </b>'+r.title+'</div>'
,'<div><b>Description: </b>'+r.description+'</div>'
,'<div><b>Image/File: </b>'
+''+ r.url +''
+'</div>'
);
}
});
});
</script>
</div>
<script>
// Calling jQuery "droparea" plugin
$('.droparea').droparea({
'init' : function(result){
//console.log('custom init',result);
},
'start' : function(area){
area.find('.error').remove();
},
'error' : function(result, input, area){
$('<div class="error">').html(result.error).prependTo(area);
return 0;
//console.log('custom error',result.error);
},
'complete' : function(result, file, input, area){
if((/image/i).test(file.type)){
area.find('img').remove();
//area.data('value',result.filename);
area.append($('<img>',{'src': result.path + result.filename + '?' + Math.random()}));
}
//console.log('custom complete',result);
}
});
</script>
<!-- /development area -->
</div>
here's my post.php file:
<?php
// LOG
$log = '=== ' . #date('Y-m-d H:i:s') . ' ===============================' . "\n"
. 'FILES:' . print_r($_FILES, 1) . "\n"
. 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('post-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);
// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');
$data = $_POST['thumbnail'];
unset($_POST['thumbnail']);
if($data){
// Uploading folder
$folder = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder))
mkdir($folder);
// If specifics folder
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
mkdir($folder);
$filename = $_POST['value'] ? $_POST['value'] :
$folder . sha1(#microtime() . '-' . $_POST['pic1']) . '.mp4';
$filename = addslashes($filename);
$sql=mysql_query('INSERT INTO ptb_photos SET file_name ="$filename",id="$_SESSION[user_id]", user_id="$_SESSION[user_id]"');
$data = split(',', $data);
file_put_contents($filename, base64_decode($data[1]));
}
die(json_encode(array_merge(array('url' => $filename), $_POST)));
?>
And lastly heres my upload.php file:
<?php
session_start()
?>
<?
// LOG
$log = '=== ' . #date('Y-m-d H:i:s') . ' ===============================' . "\n"
. 'FILES:' . print_r($_FILES, 1) . "\n"
. 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('upload-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);
// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');
// Maximum file size
$maxsize = 10; //Mb
// File size control
if ($_FILES['xfile']['size'] > ($maxsize * 1048576)) {
$r->error = "Max file size: $maxsize Kb";
}
// Uploading folder
$folder = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder))
mkdir($folder);
// If specifics folder
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
mkdir($folder);
// PASS USER_ID HERE
$folder2 = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder2))
mkdir($folder2);
// New directory with 'files/USER_SESSION_ID/'
$folder = $newDir . $folder2;
// If the file is an image
if (preg_match('/image/i', $_FILES['xfile']['type'])) {
$filename = $_POST['value'] ? $_POST['value'] :
$folder . 'thumb_pic1.jpg';
} else {
$tld = split(',', $_FILES['xfile']['name']);
$tld = $tld[count($tld) - 1];
$filename = $_POST['value'] ? $_POST['value'] :
$folder . sha1(#microtime() . '-' . $_FILES['xfile']['name']) . $tld;
}
// Supporting image file types
$types = Array('image/png', 'image/gif', 'image/jpeg');
// File type control
if (in_array($_FILES['xfile']['type'], $types)) {
// Create an unique file name
// Uploaded file source
$source = file_get_contents($_FILES["xfile"]["tmp_name"]);
// Image resize
imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
} else
// If the file is not an image
if (in_array($_FILES['xfile']['type'], $types))
move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);
// File path
$path = str_replace('upload_image_1.php', '', $_SERVER['SCRIPT_NAME']);
// Result data
$r->filename = $filename;
$r->path = $path;
$r->img = '<img src="' . $path . $filename . '" alt="image" />';
// Return to JSON
echo json_encode($r);
// Image resize function with php + gd2 lib
function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
$quality = $quality ? $quality : 80;
$image = imagecreatefromstring($source);
if ($image) {
// Get dimensions
$w = imagesx($image);
$h = imagesy($image);
if (($width && $w > $width) || ($height && $h > $height)) {
$ratio = $w / $h;
if (($ratio >= 1 || $height == 0) && $width && !$crop) {
$new_height = $width / $ratio;
$new_width = $width;
} elseif ($crop && $ratio <= ($width / $height)) {
$new_height = $width / $ratio;
$new_width = $width;
} else {
$new_width = $height * $ratio;
$new_height = $height;
}
} else {
$new_width = $w;
$new_height = $h;
}
$x_mid = $new_width * .5; //horizontal middle
$y_mid = $new_height * .5; //vertical middle
// Resample
error_log('height: ' . $new_height . ' - width: ' . $new_width);
$new = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Crop
if ($crop) {
$crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
//($y_mid - ($height * .5))
}
// Output
// Enable interlancing [for progressive JPEG]
imageinterlace($crop ? $crop : $new, true);
$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
if ($dext == '') {
$dext = $ext;
$destination .= '.' . $ext;
}
switch ($dext) {
case 'jpeg':
case 'jpg':
imagejpeg($crop ? $crop : $new, $destination, $quality);
break;
case 'png':
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($crop ? $crop : $new, $destination, $pngQuality);
break;
case 'gif':
imagegif($crop ? $crop : $new, $destination);
break;
}
#imagedestroy($image);
#imagedestroy($new);
#imagedestroy($crop);
}
}
?>
<?php
if($_FILES['xfile']['name'])
{
$target_dir = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
$upload_file_name = basename( $_FILES['xfile']['name']);
$upload_file_ext = pathinfo($_FILES['xfile']['name'], PATHINFO_EXTENSION);
$target_file = $target_dir . 'pic1.jpg';
$target_file_sql = $target_dir . mysql_real_escape_string($upload_file_name . '.');
if (move_uploaded_file($_FILES['xfile']['tmp_name'], $target_file))
{
if (copy($target_file, $target_thumb))
{
}
}
}
?>

Did you CHMOD? So not CHMOD the folder to 777

Related

CodeIgniter set image max-size to 0 and validate file type if jpg or png

Anyone can help me to set image max-size to 0.
Because I'm getting Error code: 1
Please help me to construct this code. I don't want to change the limit in php.ini Just want to know if there is a code solution for this problem:
function uploadPhoto()
{
$control = 'filephoto';
$path = './upload/';
$image = $_FILES[$control]['name'];
$size = $_FILES[$control]['size'];
if ($imageName = $this->doUpload($control, $path, $image, 'all')) {
} else {
}
}
function doUpload($control, $path, $imageName, $sizes)
{
if ($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$u_id = $session_data['u_id'];
$alnum = random_string('alnum', 16);
if ( ! isset($_FILES[$control]) || ! is_uploaded_file($_FILES[$control]['tmp_name'])) {
$this->session->set_flashdata('error_nofile', 'No file was chosen Error code: ' . $_FILES[$control]['error']);
header('location:' . base_url() . "indexc/upload/");
return false;
}
if ($_FILES[$control]['size'] > 2048000) {
$this->session->set_flashdata('error_largefile', 'File is too large (' . round(($_FILES[$control]["size"] / 1000)) . 'kb), please choose a file under 2,048kb');
header('location:' . base_url() . "indexc/upload/");
return false;
}
if ($_FILES[$control]['error'] !== UPLOAD_ERR_OK) {
$this->session->set_flashdata('error_failed', 'Upload failed. Error code: ' . $_FILES[$control]['error']);
header('location:' . base_url() . "indexc/upload/");
Return false;
}
switch (strtolower($_FILES[$control]['type'])) {
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
default:
$this->session->set_flashdata('error_notallowed', 'This file type is not allowed');
header('location:' . base_url() . "indexc/upload/");
return false;
}
#unlink($_FILES[$control]['tmp_name']);
$old_width = imagesx($image);
$old_height = imagesy($image);
//Create tn version
if ($sizes == 'tn' || $sizes == 'all') {
$max_width = 600;
$max_height = 600;
$scale = min($max_width / $old_width, $max_height / $old_height);
if ($old_width > 600 || $old_height > 600) {
$new_width = ceil($scale * $old_width);
$new_height = ceil($scale * $old_height);
} else {
$new_width = $old_width;
$new_height = $old_height;
}
$new = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
switch (strtolower($_FILES[$control]['type'])) {
case 'image/jpeg':
imagejpeg($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName, 90);
break;
case 'image/png':
imagealphablending($new, false);
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
imagesavealpha($new, true);
imagepng($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName, 0);
break;
case 'image/gif':
imagegif($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName);
break;
default:
}
}
imagedestroy($image);
imagedestroy($new);
/* print '<div style="font-family:arial;"><b>'.$imageName.'</b> Uploaded successfully. Size: '.round($_FILES[$control]['size']/1000).'kb</div>'; */
$this->session->set_flashdata('success_upload', '<div style="font-family:arial;"><b>' . $imageName . '</b> Uploaded successfully. Size: ' . round($_FILES[$control]['size'] / 1000) . 'kb</div>');
$postdata['p_u_id'] = $u_id;
$postdata['p_content'] = $this->input->post('content');
$postdata['p_image'] = $u_id . '_' . $alnum . '_' . $imageName;
$postdata['p_image_original'] = $imageName;
$postdata['p_posted'] = date("Y-m-d H:i:s");
$res = $this->indexm->postinsert_to_db($postdata);
header('location:' . base_url() . "indexc/upload/");
} else {
$this->load->view('index');
}
}
I also want to validate if the file type is jpg or png
Please help me!
thanks,
joe
try default codeigniter library :
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}

Opencart - Image Resize

i am using opencart 2.1.x version of opencart and i am facing an issue with images in displaying the images.
But image resize function adding Noise in background. It can be seen as in below image::
Tilt the laptop screen or desktop scree to observe noise
Function to resize the image is:
catalog/model/tool/image.php
public function resize($filename, $width, $height) {
if (!is_file(DIR_IMAGE . $filename)) {
return;
}
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$old_image = $filename;
$new_image = 'cache/' . utf8_substr($filename, 0,
utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.'.$extension;
list($width_orig, $height_orig) = getimagesize(DIR_IMAGE . $old_image);
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_IMAGE . $old_image);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $new_image);
} else {
copy(DIR_IMAGE . $old_image, DIR_IMAGE . $new_image);
}
system/library/image.php
public function resize($width = 0, $height = 0, $default = '') {
if (!$this->width || !$this->height) {
return;
}
$xpos = 0;
$ypos = 0;
$scale = 1;
$scale_w = $width / $this->width;
$scale_h = $height / $this->height;
if ($default == 'w') {
$scale = $scale_w;
} elseif ($default == 'h') {
$scale = $scale_h;
} else {
$scale = min($scale_w, $scale_h);
}
if ($scale == 1 && $scale_h == $scale_w && $this->mime != 'image/png') {
return;
}
$new_width = (int)($this->width * $scale);
$new_height = (int)($this->height * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $this->image;
$this->image = imagecreatetruecolor($width, $height);
if ($this->mime == 'image/png') {
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
$background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
imagecolortransparent($this->image, $background);
} else {
$background = imagecolorallocate($this->image, 255, 255, 255);
}
imagefilledrectangle($this->image, 0, 0, $width, $height, $background);
imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width,
$new_height, $this->width, $this->height);
imagedestroy($image_old);
$this->width = $width;
$this->height = $height;
}
Please assist i ngetting rid from background noise.
It looks like your catalog/model/tool/image.php code snippet is incomplete.
I solved this issue by commenting main part of a function code and returning the path to initial image (OpenCart 2.3.0.2):
<?php
class ModelToolImage extends Model {
public function resize($filename, $width, $height) {
if (!is_file(DIR_IMAGE . $filename) || substr(str_replace('\\', '/', realpath(DIR_IMAGE . $filename)), 0, strlen(DIR_IMAGE)) != DIR_IMAGE) {
return;
}
/*$extension = pathinfo($filename, PATHINFO_EXTENSION);
$image_old = $filename;
$image_new = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . (int)$width . 'x' . (int)$height . '.' . $extension;
if (!is_file(DIR_IMAGE . $image_new) || (filectime(DIR_IMAGE . $image_old) > filectime(DIR_IMAGE . $image_new))) {
list($width_orig, $height_orig, $image_type) = getimagesize(DIR_IMAGE . $image_old);
if (!in_array($image_type, array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) {
return DIR_IMAGE . $image_old;
}
$path = '';
$directories = explode('/', dirname($image_new));
foreach ($directories as $directory) {
$path = $path . '/' . $directory;
if (!is_dir(DIR_IMAGE . $path)) {
#mkdir(DIR_IMAGE . $path, 0777);
}
}
if ($width_orig != $width || $height_orig != $height) {
$image = new Image(DIR_IMAGE . $image_old);
$image->resize($width, $height);
$image->save(DIR_IMAGE . $image_new);
} else {
copy(DIR_IMAGE . $image_old, DIR_IMAGE . $image_new);
}
}
$image_new = str_replace(' ', '%20', $image_new); // fix bug when attach image on email (gmail.com). it is automatic changing space " " to +
if ($this->request->server['HTTPS']) {
return $this->config->get('config_ssl') . 'image/' . $image_new;
} else {
return $this->config->get('config_url') . 'image/' . $image_new;
}*/
return 'image/' . $filename;
}
}
Have You tried by changing quality to 100 on function save in parameter
public function save($file, $quality = 100) {
$info = pathinfo($file);
$extension = strtolower($info['extension']);
if (is_resource($this->image)) {
if ($extension == 'jpeg' || $extension == 'jpg') {
imagejpeg($this->image, $file, $quality);
} elseif ($extension == 'png') {
imagepng($this->image, $file);
} elseif ($extension == 'gif') {
imagegif($this->image, $file);
}
imagedestroy($this->image);
}
}

Uploading image to server does not work when .jpeg is the type

I'm using this script to upload images in .jpg & .png type to the server and database but when it comes to .jpeg or .JPG it does not work, instead of placing the file in right directory with correct extension it just does this /galleri/uploads/a4b7c7fb0de9c561110c2279f24ec820jpeg.php it automaticly adds .php on the end.
What I've been trying to do is to add these lines
if ( $type == 'image/jpeg' ) { $filetype = '.jpeg'; } else { $filetype = str_replace( 'image/', '', $type ); }
if ( $type == 'image/jpeg' ) { $filetype = '.JPG'; } else { $filetype = str_replace( 'image/', '', $type ); }
but with no use..
Aside from that is there any better crop tool I can use in this case that ain't so advanced?
This is the complete script:
if(isset($_POST['addmedia'])) {
$mediatype = escape(striptags($_POST['mediatype']));
$title = escape(striptags($_POST['title']));
$video = escape(striptags($_POST['medialink']));
$date = date('Y-m-d');
if ($mediatype === 'img') {
if( !isset( $_POST['p'] ) ) { $_POST['p']= 0; }
if( $_POST['p'] == 1 ) {
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
if ( $type == 'image/jpeg' ) { $filetype = '.jpg'; } else { $filetype = str_replace( 'image/', '', $type ); }
if ( $type == 'image/png' ) { $filetype = '.png'; } else { $filetype = str_replace( 'image/', '', $type ); }
$path = md5( rand(0, 1000) . rand(0, 1000) . rand(0, 1000) . rand(0, 1000) ) . $filetype;
$thumb_path = md5( rand(0, 1000) . rand(0, 1000) . rand(0, 1000) . rand(0, 1000) ) . $filetype;
$size2 = getimagesize ($temp);
$width = $size2[0];
$height = $size2[1];
$maxwidth = 1281;
$maxheight = 751;
$allowed = array('image/jpeg', 'image/png');
if( in_array( $type, $allowed ) ) {
if( $width < $maxwidth && $height < $maxheight) {
if( $size < 10485760) {
if( $width == $height ) { $case = 1;} // Square form
if( $width > $height ) { $case = 2;} // Lying form
if( $width < $height ) { $case = 3;} // Standing form
switch($case) {
case 1:
$newwidth = 280;
$newheight = 150;
break;
case 2:
$newheight = 150;
$ratio = $newheight / $height;
$newwidth = round($width * $ratio);
break;
case 3:
$newwidth = 280;
$ratio = $newwidth / $width;
$newheight = round($height * $ratio);
break;
}
switch($type) {
case 'image/jpeg':
$img = imagecreatefromjpeg( $temp );
$thumb = imagecreatetruecolor( $newwidth, $newheight );
imagecopyresized( $thumb, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
imagejpeg( $thumb, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/thumbs/" . $thumb_path );
break;
case 'image/png':
$img = imagecreatefrompng( $temp );
$thumb = imagecreatetruecolor( $newwidth, $newheight );
imagecopyresized( $thumb, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
imagepng( $thumb, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/thumbs/" . $thumb_path );
break;
}
move_uploaded_file( $temp, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/" . $path );
$addimg = "INSERT INTO uploads (`type`, `title`, `src`, `thumb`, `date`) VALUES ('$mediatype', '$title', '$path', '$thumb_path', '$date')";
if ($add_img = $db_connect->query($addimg)) {}
echo 'Din bild har laddats upp!';
header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
echo '10MB';
}
} else {
echo 'To big in size';
}
} else {
echo '.jpg, .jpeg, .png!';
}
}
} else if ($mediatype === 'vid') {
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$size = $_FILES['image']['size'];
$thumb_path = md5( rand(0, 1000) . rand(0, 1000) . rand(0, 1000) . rand(0, 1000) ) . '.jpg';
move_uploaded_file( $temp, $_SERVER['DOCUMENT_ROOT'] . "/galleri/uploads/thumbs/" . $thumb_path );
$addvid = "INSERT INTO uploads (`type`, `title`, `thumb`, `videolink`, `date`) VALUES ('$mediatype', '$title', '$thumb_path', '$video', '$date')";
if ($add_vid = $db_connect->query($addvid)) {}
echo 'Video uploaded';
header("Location: " . $_SERVER['HTTP_REFERER']);
}
}
Try this :
<?php
...
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$size = $_FILES['image']['size'];
$type = image_type_to_mime_type(exif_imagetype($temp)); // get the real image mime type
if ( $type == 'image/jpeg' ) { // jpeg
$filetype = '.jpg';
} else if ( $type == 'image/png' ){ // png
$filetype = '.png';
} else { // other image type
$filetype = '.' . str_replace( 'image/', '', $type ); // to get .gif for a gif image, for example
}
...
?>

Insert Into database upon image upload?

Hi i am trying to make my image upload script insert the file name as well as date_added, user_id and id into my database upon upload into the file directory.
At the moment it uploads and stores it into a file directory but i can't get it to insert into the database.
The table name is ptb_photos and the columns are id, user_id (id = user_id), file_name and date_added.
Here's my code, can someone let me know where i'm going wrong. I'm new to php and still learning so apologies if it's completely wrong.
<?php
session_start()
?>
<?
$sql=mysql_query("INSERT INTO ptb_photos SET file_name ='".addslashes($filename)."' WHERE id=".$_SESSION['user_id']." AND user_id=".$_SESSION['user_id']."");
// LOG
$log = '=== ' . #date('Y-m-d H:i:s') . ' ===============================' . "\n"
. 'FILES:' . print_r($_FILES, 1) . "\n"
. 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('upload-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);
// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');
// Maximum file size
$maxsize = 10; //Mb
// File size control
if ($_FILES['xfile']['size'] > ($maxsize * 1048576)) {
$r->error = "Max file size: $maxsize Kb";
}
// Uploading folder
$folder = 'files/';
if (!is_dir($folder))
mkdir($folder);
// If specifics folder
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
mkdir($folder);
// PASS USER_ID HERE
$folder2 = '../'. '../'. 'data/'. 'photos/'. $_SESSION['user_id'] . '/';
if (!is_dir($folder2))
mkdir($folder2);
// New directory with 'files/USER_SESSION_ID/'
$folder = $newDir . $folder2;
// If the file is an image
if (preg_match('/image/i', $_FILES['xfile']['type'])) {
$filename = $_POST['value'] ? $_POST['value'] :
$folder . 'pic1.jpg';
} else {
$tld = split(',', $_FILES['xfile']['name']);
$tld = $tld[count($tld) - 1];
$filename = $_POST['value'] ? $_POST['value'] :
$folder . sha1(#microtime() . '-' . $_FILES['xfile']['name']) . $tld;
}
// Supporting image file types
$types = Array('image/png', 'image/gif', 'image/jpeg');
// File type control
if (in_array($_FILES['xfile']['type'], $types)) {
// Create an unique file name
// Uploaded file source
$source = file_get_contents($_FILES["xfile"]["tmp_name"]);
// Image resize
imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
} else
// If the file is not an image
if (in_array($_FILES['xfile']['type'], $types))
move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);
// File path
$path = str_replace('upload_image_1.php', '', $_SERVER['SCRIPT_NAME']);
// Result data
$r->filename = $filename;
$r->path = $path;
$r->img = '<img src="' . $path . $filename . '" alt="image" />';
// Return to JSON
echo json_encode($r);
// Image resize function with php + gd2 lib
function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
$quality = $quality ? $quality : 80;
$image = imagecreatefromstring($source);
if ($image) {
// Get dimensions
$w = imagesx($image);
$h = imagesy($image);
if (($width && $w > $width) || ($height && $h > $height)) {
$ratio = $w / $h;
if (($ratio >= 1 || $height == 0) && $width && !$crop) {
$new_height = $width / $ratio;
$new_width = $width;
} elseif ($crop && $ratio <= ($width / $height)) {
$new_height = $width / $ratio;
$new_width = $width;
} else {
$new_width = $height * $ratio;
$new_height = $height;
}
} else {
$new_width = $w;
$new_height = $h;
}
$x_mid = $new_width * .5; //horizontal middle
$y_mid = $new_height * .5; //vertical middle
// Resample
error_log('height: ' . $new_height . ' - width: ' . $new_width);
$new = imagecreatetruecolor(round($new_width), round($new_height));
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Crop
if ($crop) {
$crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
//($y_mid - ($height * .5))
}
// Output
// Enable interlancing [for progressive JPEG]
imageinterlace($crop ? $crop : $new, true);
$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
if ($dext == '') {
$dext = $ext;
$destination .= '.' . $ext;
}
switch ($dext) {
case 'jpeg':
case 'jpg':
imagejpeg($crop ? $crop : $new, $destination, $quality);
break;
case 'png':
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($crop ? $crop : $new, $destination, $pngQuality);
break;
case 'gif':
imagegif($crop ? $crop : $new, $destination);
break;
}
#imagedestroy($image);
#imagedestroy($new);
#imagedestroy($crop);
}
}
?>
Try this:
$sql = mysql_query('INSERT INTO ptb_photos (file_name, id, user_id)
values ("$filename","$_SESSION[user_id]", "$_SESSION[user_id]"');
By the way, INSERT INTO syntax can never have WHERE clause, unless you're using:
INSERT INTO ... SELECT * FROM ... WHERE

How to crop this image?

I have this image,
I want to crop this image to several sizes, for that i use this function-
function thumbanail_for_image($Id, $newfilename, $size=NULL) {
$file_extension = substr($newfilename, strrpos($newfilename, '.') + 1);
$arr = explode('.', $newfilename);
$thumb1 = LOCAL_FOLDER . $arr[0] . "_" . $Id . "." . $file_extension;
$thumb2 = LOCAL_FOLDER . $arr[0] . "_" . $Id . "b" . "." . $file_extension;
$old = LOCAL_FOLDER . $newfilename;
$newfilename = LOCAL_FOLDER . $newfilename;
$srcImage = "";
$sizee = getimagesize($newfilename);
switch ($sizee['mime']) {
case "image/jpeg" :
$srcImage = imagecreatefromjpeg($old);
break;
case "image/png":
$srcImage = imagecreatefrompng($old);
break;
case "image/gif":
$srcImage = imagecreatefromgif($old);
break;
}
$srcwidth = $sizee[0];
$srcheight = $sizee[1];
if ($srcwidth > $srcheight || $srcwidth < $srcheight) {
$destwidth1 = 65;
$rat = $destwidth1 / $srcwidth;
$destheight1 = (int) ($srcheight * $rat);
}
elseif ($srcwidth == $srcheight) {
$destwidth1 = 65;
$destheight1 = 65;
}
if ($srcwidth > $srcheight || $srcwidth < $srcheight) {
$destwidth2 = 300;
$rat = $destwidth2 / $srcwidth;
$destheight2 = (int) ($srcheight * $rat);
}
elseif ($srcwidth == $srcheight) {
$destwidth2 = 300;
$destheight2 = 300;
}
$destImage1 = imagecreatetruecolor($destwidth1, $destheight1);
$destImage2 = imagecreatetruecolor($destwidth2, $destheight2);
imagecopyresampled($destImage1, $srcImage, 0, 0, 0, 0, $destwidth1, $destheight1, $srcwidth, $srcheight);
imagecopyresampled($destImage2, $srcImage, 0, 0, 0, 0, $destwidth2, $destheight2, $srcwidth, $srcheight);
if ($sizee['mime'] == "image/jpeg") {
imagejpeg($destImage1, $thumb1, 80);
imagejpeg($destImage2, $thumb2, 80);
} elseif ($sizee['mime'] == "image/png") {
imagepng($destImage1, $thumb1, 80);
imagepng($destImage2, $thumb2, 80);
} elseif ($sizee['mime'] == "image/gif") {
imagegif($destImage1, $thumb1, 80);
imagegif($destImage2, $thumb2, 80);
}
imagedestroy($destImage1);
imagedestroy($destImage2);
chmod($destImage1, 0777);
chmod($destImage2, 0777);
return $destImage1;
}
LOCAL_FOLDER is variable path to local
The problem i saw is when i print $_FILES info about it shows
[type] =>image/jpeg
and when i print getimagesize() function it prints
[mime] => image/png
Please help,
thanks
Why do you not use a lib that handles all these things for you?
For instance, check out WideImage:
include "path-to/WideImage.php";
$image = WideImage::load("path-to/image.jpg");
$cropped = $image->crop(0, 0, 100, 50);
$cropped->saveToFile("cropped-image.jpg");
PHP's POST method uploads page says:
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information.
An example would be "image/gif". This mime type is however not checked
on the PHP side and therefore don't take its value for granted.
So the image type data here is provided by the client that uploaded the file, and PHP recommends don't trust it. Trust what getimagesize() gives you instead.

Categories