PHP checking function output - php

I have a basic function to resize image given below:
function resize() {
.....
...
..
imagejpeg($image_new,$img_path,80);
imagedestroy($image_old);
imagedestroy($image_new);
}
I need to call it in another function and see its output. How can i do that? I want something like:
function test(){
//calling resize function
if (resize() === true){
echo "Success";
} else {
echo "resized failed";
}
}
What I'm not understanding is that the resize function simply creates the image and detroys the older image files. How it will return the output that it was successful or not? Thanks.

As written your resize function is not returning information on whether it succeeds or fails and, furthermore, it always destroys both images (the two imagedestroy calls). You'll need to rewrite the function to take account of the return codes from imagedestroy and imagejpeg. The documentation for the latter indicates that that function will return a boolean indicating whether it was successful or not.

imagejpeg() returns a boolean FALSE on failure (according to the API; collect its return and use that as the return of your resize() function:
function resize () {
...
$success = imagejpeg($image_new, $img_path, 80);
...
return $success
}
Also, you should probably be passing in the image as a parameter to resize()... it looks like you have a few global variables, which isn't good(1) practise(2)

Related

Force return statement on caller function

I am just curious if it's possible to force parent method to return a value from within method called in that parent method? Let's say I have:
public function myApiEndpoint()
{
// I DO NOT want to to have return statement here
$this->validOrUnprocessable();
// some other code
//return value
return $someValue;
}
public function validOrUnprocessable()
{
if ($condition) {
... here goes the code that forces return statement on myApiEndpoint function without putting the word `return` in front of this call...
}
}
So in other words validOrUnprocessable method, when it needs to do so forces or tricks PHP into thinking that myApiEndpoint returns the value. I do not want to use return statement when validOrUnprocessable is called or any if conditions.
I do know other ways of doing what I want to do but I wanted to know if something like that is possible. I am not interested in any workarounds as I know very well how to implement what I need to achieve in many other ways. I just need to know if this what I described is possible to do exactly how I described it.
I did try to get there with reflections and other scope related things but so far no luck. Any ideas?
Just to add. I am doing this because I want to check how far I can push it. I am building a tool for myself and I want it to be as convenient and easy to use as possible.
If it's not possible I have another idea but that's a bit out of the scope of this post.
You should throw an exception.
public function validOrUnprocessable()
{
if ($condition) {
throw Exception('foo bar');
}
}
The code calling this method should be ready to catch an exception:
public function myApiEndpoint()
{
try {
// I DO NOT want to to have return statement here
$this->validOrUnprocessable();
// some other code
//this code will never be called because of exception thrown in validOrUnprocessable
return value;
} catch (Exception $e) {
//do something else
return -1; //you can return another value as example.
}
return $someValue;
}

Check if the text file was empty

I'd like to know how to check if a text file is empty or not. It means that there is no text even some space, i.e. it was blank
function keyRemain($path)
{
$ambil = file_get_contents("data/$path/keywords.txt");
$kw = explode(",", $ambil);
if (count($kw) > 1) {
return false;
} else {
return true;
}
}
You have to check the empty function along with trim
function keyRemain($path)
{
$ambil = trim(file_get_contents("data/$path/keywords.txt"));
var_dump($ambil); // check the output here
if(!empty($ambil)) {
return false;
} else {
return true;
}
}
Maybe this was not the answer, just the another way to check the file. Before this was happend, the code appear instead the class. After i cut it and move it outside of the class it work perfectly without any errors.
file_get_contents() will read the whole file while filesize() uses stat() to detirmine the file size. Use filesize(), it should consume less disk I/O.
That's the answer found here, on stack...
You can also (on same link there's this answer):
clearstatcache();
if(filesize($path_to_your_file)) {
// your file is not empty
}

PHP: how to check if a given file has been included() inside a function

I have a PHP file that can be include'd() in various places inside another page. I want to know whether it has been included inside a function. How can I do this? Thanks.
There's a function called debug_backtrace() that will return the current call stack as an array. It feels like a somewhat ugly solution but it'll probably work for most cases:
$allowedFunctions = array('include', 'include_once', 'require', 'require_once');
foreach (debug_backtrace() as $call) {
// ignore calls to include/require
if (isset($call['function']) && !in_array($call['function'], $allowedFunctions)) {
echo 'File has not been included in the top scope.';
exit;
}
}
You can set a variable in the included file and check for that variable in your functions:
include.php:
$included = true;
anotherfile.php:
function whatever() {
global $included;
if (isset($included)) {
// It has been included.
}
}
whatever();
You can check if the file is in the array returned by get_included_files(). (Note that list elements are full pathnames.) To see if inclusion occurred during a particular function call, check get_included_files before and after the function call.

php function in array broken

I am trying to setup an array that pulls the filename and function name to run, but it not fully working.
The code is
$actionArray = array(
'register' => array('Register.php', 'Register'),
);
if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']])) {
echo '<br><br>index<br><br>';
echo 'test';
exit;
}
require_once($actionArray[$_REQUEST['action']][0]);
return $actionArray[$_REQUEST['action']][1];
Register.php has
function Register()
{
echo 'register';
}
echo '<br>sdfdfsd<br>';
But it does not echo register and just sdfdfsd.
If I change the first lot of code from
return $actionArray[$_REQUEST['action']][1];
to
return Register();
It works, any ideas?
Thanks
Change the last line to:
return call_user_func($actionArray[$_REQUEST['action']][1]);
This uses the call_user_func function for more readable code and better portability. The following also should work (Only tested on PHP 5.4+)
return $actionArray[$_REQUEST['action']][1]();
It's almost the same as your code, but I'm actually invoking the function instead of returning the value of the array. Without the function invocation syntax () you're just asking PHP get to get the value of the variable (in this case, an array) and return it.
You'll find something usefull here:
How to call PHP function from string stored in a Variable
Call a function name stored in a string is what you want...

displaying blob images - symfony

I have blob data in my database and they are images that I want to display as a basic gallery.
I have a method that I have written to display the images, but I'm getting an error, saying that it is a string, rather than blob data being returned:
public function getFilenamePath()
{
$file_src = false;
if (null !== $fp = $this->getFilename())
{
$file = stream_get_contents($fp);
$file_src = '/uploads/gallery/'.$this->getId().'.jpg';
}
return $file_src;
}
where getFilename() is my blob column.
action:
public function executeSingle(sfWebRequest $request)
{
$application_id = $this->getRequestParameter('id');
$c = new Criteria();
$c->addJoin(GalleryPeer::APPLICATION_ID, ApplicationPeer::ID);
$c->addJoin(GalleryImagePeer::GALLERY_ID, GalleryPeer::ID);
$c->add(GalleryPeer::APPLICATION_ID, $application_id);
$this->galleries = GalleryImagePeer::doSelect ( $c );
}
template:
foreach($galleries as $gallery)
{
$path = $gallery->getFilenamePath();
if($path)
{
echo '<img src="'.$path.'" />';
}
}
The error I get is that stream_get_contents seems to be returning a string.
Is there anyway, I can get the blob data, or rather than use a model method, use an action to return all the images attached to the application?
Thanks
If you store images in the database, you have (basically) two options to show them on the client:
First solution: Get file content and encode it with base64 encoding. You can find a working example here:
http://www.php.net/manual/en/function.base64-encode.php#99842
This method is not the best as if you do it like that, the client won't be able to cache these images, that means more traffic, more processing time, more database connection, slower page loading etc.
Second solution: You create an image loading action in Symfony. The routing is like:
mapimage:
url: /myimage/:image_id.png
param: { module: myimagemodul, action: myimageaction }
You have to create a controller action myimageaction and there you can get the image ID like
$request->getParameter('image_id');
And get the blob data from the database and return it as binary with specific http headers. You can find working examples with simple Googleing, one example:
$this->image = ImagePeer::retrieveByPk ($request->getParameter('image_id'));
$response = $this->getResponse();
$response->clearHttpHeaders();
$response->setContentType ($this->image->getMimeType());
$response->setHttpHeader ('Content-Disposition', 'inline;filename='.$filename);
$content = $this->image->getData();
$response->setContent (stream_get_contents ($content));
$this->setLayout (false);
return sfView::NONE;
So in the template you can do like:
<img src='<?= url_for ('route_to_action_above', array ('image_id' => $image->getId()) ?>'/>
I have found this one at
http://forum.symfony-project.org/viewtopic.php?f=22&t=31207#p109705
This code doesn't make any sense.
Why do you feed binary(read string) data from ->getFilename() to stream_get_contents() which operates ONLY on resource data type? Of course it will complain.
Outputing blob to a browser is as simple as:
$this->getResponse->setContentType('image/jpeg');
echo $data->getFilename(); // assuming filename column is your blob column
try switching your getFilenamePath function to this.
public function getFilenamePath() {
$file_src = '/uploads/gallery/'.$this->getId().'.jpg';
if (file_exists($file_src ) {
return $file_src;
} else {
return false;
}
}
$profile_picture = base64_encode(stream_get_contents($image->getContent()));
echo '<img src="data:image/jpeg;base64,'.$profile_picture.'" />';

Categories