• 0

PHP Function, Pass Empty $username Value


Question

On Symfony's Friends of Symfony User Bundle, I managed to modify a profile action that allows me to view specific user profiles instead of only seeing my own. I basically took the Group Controller's function, and made some code useable for the User Controller, as the Group Controller allows you to view the group, using the name in the URL; now in the User Controller, where profile/ becomes profile/mrxxiv. I'm trying to keep profile/ as well, but the way I have the function set up, it's almost impossible due to Symfony giving me an error, telling me about the empty value in the function, where I'd need to enter a username in order to find & view the user's data.

This is the error when not entering a username in the URL:

Controller "FOS\UserBundle\Controller\ProfileController::showAction()" requires that you provide a value for the "$username" argument (because there is no default value or because there is a non optional argument after this one).

I don't want to enter a default value, I just want to find a way to pass the parameter when it's empty as when I use only the url profile/, I can view my own profile data on the spot. Plus I can't be specific against all users. Disregard the IF statement by the way.

public function showAction($username) {
	$user = $this->container->get('security.context')->getToken()->getUser();

	if (!is_object($user) || !$user instanceof UserInterface) {
			throw new AccessDeniedException('This user does not have access to this section.');
	}

	$user = $this->findUserBy('username', $username);
	return $this->container->get('templating')->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container->getParameter('fos_user.template.engine'), array('user' => $user));
}

14 answers to this question

Recommended Posts

  • 0

On Symfony's Friends of Symfony User Bundle, I managed to modify a profile action that allows me to view specific user profiles instead of only seeing my own. I basically took the Group Controller's function, and made some code useable for the User Controller, as the Group Controller allows you to view the group, using the name in the URL; now in the User Controller, where profile/ becomes profile/mrxxiv. I'm trying to keep profile/ as well, but the way I have the function set up, it's almost impossible due to Symfony giving me an error, telling me about the empty value in the function, where I'd need to enter a username in order to find & view the user's data.

This is the error when not entering a username in the URL:

Controller "FOS\UserBundle\Controller\ProfileController::showAction()" requires that you provide a value for the "$username" argument (because there is no default value or because there is a non optional argument after this one).

I don't want to enter a default value, I just want to find a way to pass the parameter when it's empty as when I use only the url profile/, I can view my own profile data on the spot. Plus I can't be specific against all users. Disregard the IF statement by the way.

public function showAction($username) {
	$user = $this->container->get('security.context')->getToken()->getUser();

	if (!is_object($user) || !$user instanceof UserInterface) {
			throw new AccessDeniedException('This user does not have access to this section.');
	}

	$user = $this->findUserBy('username', $username);
	return $this->container->get('templating')->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container->getParameter('fos_user.template.engine'), array('user' => $user));
}

I'm not familiar with Symfony, but you should be able to assign a 'default' value (I know you said you didn't want to assign a default but this is sort of different?) when the function is defined:

public function showAction($username='') {

That way, if nothing is passed to the function, it assigns an empty value.

  • 0

Your question makes no sense, if there's no username provided, don't run the function.

Obviously you can't get a profile for a user that doesn't exist.

EDIT: If what I think you mean is you want to access profiles via /<username> instead of /index.php?user=<username> then you've got 3 methods of doing it.

1) Use apache rewrites to rewrite the URL.

2) Modify the symfony function above which means you've forked symphony - congratulations if you upgrade you'll break it and if you don't upgrade you'll be stuck with all future security flaws

3) Make your own functions to do all the calling... Which as said in the other thread is why it's MUCH easier and better to create your own code from scratch rather than using a framework that you've no clue about, you could be going back and forth between many many functions looking for how things happen like why the function is being called twice.

Edited by n_K
  • 0

Your question makes no sense, if there's no username provided, don't run the function.

Obviously you can't get a profile for a user that doesn't exist.

There are 2 users in the database. Where I go to both /profile/mrxxiv and /profile/mrsxxiv. Originally, it only set up /profile to where I can just see my profile, but I wanted to extend that user feature to allow users to see each other's profiles.

I'm not sure how to prevent that function, because that is a controller that renders the page. Remember, this is an MVC Framework, I practically have no choice at the moment because this is how all the other controllers run.

I'm basically asking for help on how to keep a variable ignored, if the value is empty. This has nothing to do with existence.

  • 0

In that case it's passing the argument via another function, as I said you'll need to go through and find how and where the function is being called and rewrite it which means you've forked it *wrong buzzer noise*

Keep a value ignored?

if (!is_null($Username))

{

//Insert all the above function here

}

Edited by n_K
  • 0

In that case it's passing the argument via another function, as I said you'll need to go through and find how and where the function is being called and rewrite it which means you've forked it *wrong buzzer noise*

I've already done a rewrite to use app.php (the index) as the base of the URL, as the site already uses the Address as subdirectories, not query's and variables.

I'm not sure passing another will work because the function right there that renders the page basically works with the router for the GET function.

You've used Symfony before right? :/

  • 0

No, I don't bother with frameworks, and I don't need to in order to see that the error is coming from a file that is part of the framework. Modify any of the framework files = fork, the idea of the framework is you use the functions of the framework without modifying the framework itself.

Yes it uses other functions to get and process the username, get out grep and look for what other files call that function, then comment them out one by one until you find the function you need to change.

  • 0

I'm basically asking for help on how to keep a variable ignored, if the value is empty. This has nothing to do with existence.

Doesn't my way essentially do that? And then do this if need be:

if($username != '')

$user = $this-&gt;findUserBy('username', $username);

  • 0

I don't think he's asking about that, he's saying that it always gets the profile of the logged in user and he wants it to get the profile of the user in the URL.

I already get the other users profiles using the username in the URL, but using this function will pass an error for an empty value when only using /profile. Like so.

post-388684-0-03413100-1357266911.png

post-388684-0-45501000-1357266917.png

  • 0

WAIT!

This is what's throwing the exception.

protected function findUserBy($key, $value)
    {
        if (!empty($value)) {
            $user = $this-&gt;container-&gt;get('fos_user.user_manager')-&gt;{'findUserBy'.ucfirst($key)}($value);
        }

        if (empty($user)) {
            throw new NotFoundHttpException(sprintf('The user with "%s" does not exist for value "%s"', $key, $value));
        }

        return $user;
    }

  • 0

Are you using this function to get the profile then?? If so, return out of the function if you aren't using it:


public function showAction($username='') {
if($username == '')
return;
		$user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();

		if (!is_object($user) || !$user instanceof UserInterface) {
						throw new AccessDeniedException('This user does not have access to this section.');
		}

		$user = $this-&gt;findUserBy('username', $username);
		return $this-&gt;container-&gt;get('templating')-&gt;renderResponse('FOSUserBundle:Profile:show.html.'.$this-&gt;container-&gt;getParameter('fos_user.template.engine'), array('user' =&gt; $user));
}

Edit:

If thats throwing the exception, skip it like posted a couple posts above?

  • 0

So you want it to get the profile of the logged in user when no profile is given?

if (is_null($Username))

{

GLOBAL $x;

$Username = $x;

}

$x being the variable that holds the logged in username, if it's a session variable you can remove the GLOBAL line.

  • 0

Are you using this function to get the profile then?? If so, return out of the function if you aren't using it:

Edit:

If thats throwing the exception, skip it like posted a couple posts above?

So you want it to get the profile of the logged in user when no profile is given?

if (is_null($Username))

{

GLOBAL $x;

$Username = $x;

}

$x being the variable that holds the logged in username, if it's a session variable you can remove the GLOBAL line.

The function "findUserBy" is the function that searches for the user, it's right under the showAction function. There's already if(empty) exception there, but even if I modify it. I can't get the logged in user info as another exception from the showAction will appear, thus into a paradox (ahh hell).

EDIT:

Let me try, using 2 different functions, since this is a controller working with a router. I'll try to render profile/ and profile/{user} from 2 different public functions.

EDIT #2:

Really appreciate your help guys. I used 2 different functions as said by also using the router to modify what function I want to use.

XML Router:

    &lt;route id="fos_user_profile_show" pattern="/"&gt;
        &lt;default key="_controller"&gt;FOSUserBundle:Profile:main&lt;/default&gt;
        &lt;requirement key="_method"&gt;GET&lt;/requirement&gt;
    &lt;/route&gt;

&lt;route id="fos_other_user_profile_show" pattern="/{username}"&gt;
        &lt;default key="_controller"&gt;FOSUserBundle:Profile:show&lt;/default&gt;
        &lt;requirement key="_method"&gt;GET&lt;/requirement&gt;
    &lt;/route&gt;

Controller:


    /**
     * Show the main user
     */
    public function mainAction()
    {
        $user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();

if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this-&gt;container-&gt;get('templating')-&gt;renderResponse('FOSUserBundle:Profile:show.html.'.$this-&gt;container-&gt;getParameter('fos_user.template.engine'), array('user' =&gt; $user));
    }


    /**
     * Show the user
     */
    public function showAction($username)
    {
        $user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();

$user = $this-&gt;findUserBy('username', $username);

if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this-&gt;container-&gt;get('templating')-&gt;renderResponse('FOSUserBundle:Profile:show.html.'.$this-&gt;container-&gt;getParameter('fos_user.template.engine'), array('user' =&gt; $user));
    }

Edited by Mr.XXIV
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Just for anyone reading, AdGuard (the free, standalone MV3 extension) is quite good now, a direct competitor to uBlock Origin Lite and much more built-out than it.
    • Microsoft Edge 149.0.4022.62 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Yeah, when I saw that, I wanted to find the nearest nose. You can't find a good nose these days when you need one.
    • Anthropic launches Claude Fable 5, a state-of-the-art AI model that beats OpenAI's GPT-5.5 by Pradeep Viswanathan Back in April, Anthropic announced Claude Mythos Preview, a frontier model with state-of-the-art coding capabilities. Due to the cybersecurity implications that would occur due to the availability of such a powerful model, Anthropic made it available to only a select set of companies around the world. The company's plan was to prepare appropriate guardrails before releasing such a powerful model to everyone. Now, after nearly two months, Anthropic announced Claude Fable 5, its most capable AI model yet for general users. The company also announced Claude Mythos 5, the same underlying model as Fable 5, but with safeguards lifted, making it more suitable for selected cybersecurity and biology use cases. Claude Fable 5 sits a tier above its Opus models and it beats most other generally available models across areas including software engineering, knowledge work, vision, scientific research, and long-running autonomous tasks. To prevent model misuse, when Claude Fable 5 detects certain requests related to cybersecurity, biology, chemistry, or model distillation, the request will be routed to the Claude Opus 4.8 model. Anthropic claims that these safeguards trigger in less than 5% of sessions on average. However, for large organizations working on critical software, Claude Mythos 5 can be availed through Project Glasswing. Later, Anthropic has plans to expand access through a broader trusted access program. As you can notice in the benchmarks above, Fable 5 and Mythos 5 are state-of-the-art on most key AI benchmarks and they are well ahead of OpenAI's frontier model, GPT-5.5. For example, Fable 5 is the new state-of-the-art model for vision tasks. Also, Mythos 5 has the strongest cybersecurity capabilities of any model in the world. Claude Fable 5 and Claude Mythos 5 are priced at $10 per million input tokens and $50 per million output tokens, which is less than half the price of Claude Mythos Preview. Another big change is that Anthropic is making a change to the way they handle business customer data for both Fable 5 and Mythos 5 models. The company will now require 30-day retention for all traffic on both first- and third-party surfaces. Anthropic promises that it won't use the data to train Claude models, instead it will use it against complex and novel attacks. Claude Fable 5 is available today on the Claude API and consumption-based Enterprise plans. It is also included at no extra cost for Pro, Max, Team, and seat-based Enterprise customers from today through June 22. After that, users on those plans will need usage credits to continue using Fable 5, unless Anthropic extends the included access window based on capacity. Developers can access Fable 5 through the Claude API using the claude-fable-5 model name.
  • Recent Achievements

    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
    • One Year In
      jojodbn earned a badge
      One Year In
    • One Month Later
      jojodbn earned a badge
      One Month Later
    • Week One Done
      jojodbn earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      525
    2. 2
      PsYcHoKiLLa
      232
    3. 3
      +Edouard
      124
    4. 4
      ATLien_0
      88
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!