I develop a social android app that users upload high quality image to my server and then download them to show in list view in app feed.
Uploaded image save in ./uploads/ directory in my server. I use the below code in PHP to save image in server:
<?php
// Path to move uploaded files
error_reporting(E_ALL ^ E_DEPRECATED);
include 'conf.php';
$target_path = "uploads/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
print "error1";
}
print basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
print "error2";
}
} else {
// File parameter is missing
print "error3";
}
?>
Now I want to save low resolution of every image in different directory(or in real time get low resolution ) and get url of it and using php send to android app and users in my app can see a thumbnail or low resolution of image before download whole image.
How I should do it?
Easy. You can use the code below to do this :
<?php
$org_info = getimagesize("source image");
echo $org_info[3] . '<br><br>';
$rsr_org = imagecreatefromjpeg("source image");
$rsr_scl = imagescale($rsr_org, new_width, new_height, IMG_BICUBIC_FIXED);
imagejpeg($rsr_scl, "destination image");
imagedestroy($rsr_org);
imagedestroy($rsr_scl);
?>
Related
I am working with facebook graph api, in my code i want to store a user profile image url in my database & the image store in my database file, it can find the source file also show it but it can't store image my database. The error says that:
file_put_contents(celebrity_u_look_alike/youtube_star/fb_user_image/img_1264053943663652.png): failed to open stream: No such file or directory in /home/smartcarsassocia/public_html/celebrity_u_look_alike/youtube_star/youtube_star.php on line 101
My source code shown below :
try {
$requestPicture = $fb->get('/me/picture?redirect=false&height=250&width=250'); //getting user picture
$requestProfile = $fb->get('/me'); // getting basic info
$picture = $requestPicture->getGraphUser();
$profile = $requestProfile->getGraphUser();
$url= $picture['url'];
echo $url;
$filename = 'img_' . $profile_data['id'] . '.png';
echo $filename;
$path1 = "celebrity_u_look_alike/youtube_star/fb_user_image/" . basename($filename);
$image_file = file_get_contents($url);
file_put_contents($path1, $image_file );
//file_put_contents($path2, file_get_contents($url));
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
This is because:
file_put_contents($path1, $image_file );
the path you have provided in $path1 doesn't exist physically. So make sure the directory exist. If not, then create it using mkdir() function.
Below is the code for me to generate a unique file Url of each image uploaded and store it to database.
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHisu');
// Path to move uploaded files
$target_path = "uploads";
//the file name
$path = "$target_path/$id.jpeg";
// getting server ip address
$server_ip = gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://'. $server_ip . '/' . 'abc' . '/' .$path;
What I expect for this code should generate the url in json_encode as below:
http://111.111.11.1/abc/uploads/20170226041004809200.jpeg
But now the problem is it generate the Url but in json_encode result is like below
http:\/\/111.111.11.1\/abc\/uploads\/20170226041004809200.jpeg
What I tried so far,
$file_upload_url = 'http:'. $server_ip . 'abc' .$path;
But it not what I want,it become this
http:111.111.11.1.1abcuploads\/20170226041515563600.jpeg
Can somebody have any idea how to solve this?Or have a better suggestion?
If you are working on same server then why don't you try to upload file with code snippet-
$file_upload_url = realpath($_SERVER["DOCUMENT_ROOT"]). '/abc' . '/' .$path;
// you can manage url by -
$base_url = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$base_url.=$_SERVER['SERVER_ADDR'];
$base_url.='/abc/'.$path
// now print your url-
echo $base_url;
Use str_replace to replace the \
<?php
$file_upload_url = "http:\/\/111.111.11.1\/abc\/uploads\/20170226041004809200.jpeg";
$upload_path = str_replace('\\','',$file_upload_url);
echo $upload_path;
?>
I am trying to insert values into a mysql database and I am getting an "Internal Server Error" and do not know why. I am using an upload form to get user data and then using an upload processor file to write the data to the server. The form is based off of a working tutorial online so everything works, but whenever I added the SQL code, it stopped working. My code is below, and I appreciate your time looking at it.
<?php
// Upload form based off of http://www.htmlgoodies.com/beyond/php/article.php/3877766
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded file
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.form.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';
// fieldname used within the file <input> of the HTML form
$fieldname = 'file';
$promoName = 'sale_name';
$expirDate = 'sale_expir';
// Now let's deal with the upload
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print the form
isset($_POST['submit'])
or error('the upload form is needed', $uploadForm);
// check for PHP's built-in uploading errors
($_FILES[$fieldname]['error'] == 0)
or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
// check that the file we are working on really was the subject of an HTTP upload
#is_uploaded_file($_FILES[$fieldname]['tmp_name'])
or error('not an HTTP upload', $uploadForm);
// validation... since this is an image upload script we should run a check
// to make sure the uploaded file is in fact an image. Here is a simple check:
// getimagesize() returns false if the file tested is not an image.
#getimagesize($_FILES[$fieldname]['tmp_name'])
or error('only image uploads are allowed', $uploadForm);
// make a unique filename for the uploaded file and check it is not already
// taken... if it is already taken keep trying until we find a vacant one
// sample filename: 1140732936-filename.jpg
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
// now let's move the file to its final location and allocate the new filename to it
#move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
or error('receiving directory insuffiecient permission', $uploadForm);
// these commands move the information onto the database
$imageURL = $uploadsDirectory.$uploadFilename;
$host = '***removed***';
$dbName = '***removed***';
$dbUser = '***removed***';
$dbPass = '***removed***';
$conn = mysql_connect($host, $dbUser, $dbPass);
if (!$conn){
die('Could not connect: '.mysql_error());
} else {
echo 'Connected successfully!';
}
$sql = "INSERT INTO '$dbName'.sales (name, date, saleImage) VALUES ('$promoName', '$expirDate', '$imageURL');";
mysql_select_db($dbName, $conn);
mysql_query($sql, $conn);
mysql_close($conn);
// database work is done
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to a success page.
header('Location: ' . $uploadSuccess);
// The following function is an error handler which is used
// to output an HTML error page if the file upload fails
function error($error, $location, $seconds = 5)
{
header("Refresh: $seconds; URL="$location"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."n".
'"http://www.w3.org/TR/html4/strict.dtd">'."nn".
'<html lang="en">'."n".
' <head>'."n".
' <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."nn".
' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."nn".
' <title>Upload error</title>'."nn".
' </head>'."nn".
' <body>'."nn".
' <div id="Upload">'."nn".
' <h1>Upload failure</h1>'."nn".
' <p>An error has occurred: '."nn".
' <span class="red">' . $error . '...</span>'."nn".
' The upload form is reloading</p>'."nn".
' </div>'."nn".
'</html>';
exit;
} // end error handler
?>
You have this code in your 95th line:
header("Refresh: $seconds; URL="$location"");
Which should be
header("Refresh: $seconds; URL=\"$location\"");
I have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>
I have written a pretty basic upload script that takes the file and uploads it using the standard move_uploaded_file method as you see below:
//UPLOAD IMAGE
$path = "../../clients/$realClient/" . $_FILES["image"]["name"][$x];
move_uploaded_file($_FILES["image"]["tmp_name"][$x], $path);
$displayPath = "private/clients/$realClient/" . $_FILES["image"]["name"][$x];
mysql_query("INSERT INTO images VALUES(NULL, '$displayPath', '$client', '$project', '$newWeight')") or die("Unable to Insert Image - Please Try Again");
echo "File Successfully Uploaded<br />";
This upload script works perfectly for most purposes. Here's my issue:
I have a standard shared hosting package so sometimes when the user tries to upload a file that takes over five minutes to upload (say a video or some other high res media), the server times out. The hosting company has said that as it's a shared hosting server they are unwilling to increase the timeout limit for me.
Is there a more efficient upload script that will allow files to go up in under five minutes or is there perhaps an alternative you could suggest?
Cheers,
Dan
The PHP script is run after the upload completes; so if there's a timeout during the upload, there's nothing you can do in the script (as it won't be run at all).
If the timeout occurs during the script, you could split it into multiple parts - have the first script just store the uploaded file and HTTP redirect to another, which will do the processing and database work. In the script you're showing, the processing seems simple enough, not sure if splitting that would help.
Assuming you're showing just a simplified version:
script1.php
// upload is complete
$fname= basename($_FILES["image"]["name"][$x]); //prevent directory traversal
$uniqid = uniqid("",true);
$path = "../../clients/$realClient/temporary/" . $uniqid . '/' . $fname;
// move to temporary location and redirect
move_uploaded_file($_FILES["image"]["tmp_name"][$x], $path);
header('Location: /script2.php?file=' . $uniqid . '/' . $fname);
script2.php
$path = $_GET['file'];
$uniqid = basename(dirname($path));
$fname = basename($path);
$temp_path = "../../clients/$realClient/temporary/" . $uniqid . '/' . $fname;
$final_path = "../../clients/$realClient/" . $fname;
move($temp_path,$final_path);
// do whatever processing is necessary
mysql_query("INSERT INTO images VALUES(NULL, '$displayPath', '$client', '$project', '$newWeight')") or die("Unable to Insert Image - Please Try Again");
echo "File Successfully Uploaded<br />";